-
Notifications
You must be signed in to change notification settings - Fork 35
/
aporia.nim
2730 lines (2297 loc) · 98.3 KB
/
aporia.nim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
#
# Aporia - Nim IDE
# (c) Copyright 2015 Dominik Picheta
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
# Stdlib imports:
import glib2, gtk2, gtksourceview, dialogs, os, pango, osproc
import strutils except toLower
import gdk2 except `delete`, string # Don't import delete to avoid "ambiguous identifier" error under Windows
import pegs, streams, times, parseopt, parseutils, asyncio, sockets, encodings, unicode
import tables, algorithm
when defined(macosx):
import gtkmacintegration
# Local imports:
import settings, utils, cfg, search, suggest, AboutDialog, processes,
CustomStatusBar, autocomplete
{.push callConv:cdecl.}
const
GTKVerReq = (2.guint, 24.guint, 0.guint) # Version of GTK required for Aporia to run.
aporiaVersion = "0.4.2"
helpText = """./aporia [args] filename...
-v --version Reports aporia's version
-h --help Shows this message
"""
var win: utils.MainWin
win.tabs = @[]
var lastSession: seq[string] = @[]
proc writeHelp() =
echo(helpText)
quit(QuitSuccess)
proc writeVersion() =
echo("Aporia v$1 compiled at $2 $3.\nCopyright (c) Dominik Picheta 2010-2015" %
[aporiaVersion, CompileDate, CompileTime])
quit(QuitSuccess)
proc parseArgs(): seq[string] =
result = @[]
for kind, key, val in getopt():
case kind
of cmdArgument:
result.add(key)
of cmdLongOption, cmdShortOption:
case key
of "help", "h": writeHelp()
of "version", "v": writeVersion()
else: discard
of cmdEnd: assert(false) # cannot happen
var loadFiles = parseArgs()
# Load the settings
var cfgErrors: seq[AporiaError] = @[]
let (auto, global) = cfg.load(cfgErrors, lastSession)
win.autoSettings = auto
win.globalSettings = global
proc showConfigErrors*() =
if cfgErrors.len > 0:
for error in cfgErrors:
addError(win, error)
dialogs.warning(win.w, "Error parsing config file, see Error List.")
proc updateMainTitle(pageNum: int) =
if win.tabs.len()-1 >= pageNum:
var title = ""
if win.tabs[pageNum].filename == "":
title = "Untitled"
else:
title = win.tabs[pageNum].filename.extractFilename
if not win.tabs[pageNum].saved:
title.add("*")
title.add(" - Aporia")
win.w.setTitle(title)
proc plCheckUpdate(pageNum: int) =
## Updates the 'check state' of the syntax highlighting CheckMenuItems,
## depending on the syntax highlighting language that has been set.
let currentToggledLang = win.tempStuff.currentToggledLang
let newLang = win.getCurrentLanguage(pageNum)
assert win.tempStuff.plMenuItems.hasKey(currentToggledLang)
assert win.tempStuff.plMenuItems.hasKey(newLang)
win.tempStuff.stopPLToggle = true
win.tempStuff.plMenuItems[currentToggledLang].mi.itemSetActive(false)
win.tempStuff.plMenuItems[newLang].mi.itemSetActive(true)
win.tempStuff.currentToggledLang = newLang
win.tempStuff.stopPLToggle = false
proc setTabTooltip(t: Tab) =
## (Re)sets the tab tooltip text.
if t.filename != "":
var tooltip = "<b>Path: </b> " & t.filename & "\n" &
"<b>Language: </b> " & getLanguageName(win, t.buffer) & "\n" &
"<b>Line Ending: </b> " & $t.lineEnding
if t.filename.startsWith(getTempDir()):
tooltip.add("\n<i>File is saved in temporary files and may be deleted.</i>")
t.label.setTooltipMarkup(tooltip)
else:
var tooltip = "<i>Tab is not saved.</i>\n" &
"<b>Language: </b> " & getLanguageName(win, t.buffer) & "\n" &
"<b>Line Ending: </b> " & $t.lineEnding
t.label.setTooltipMarkup(tooltip)
proc updateTabUI(t: Tab) =
## Updates Tab's label and tooltip. Call this when the tab's filename or
## language changes.
var name = ""
if t.filename == "":
name = "Untitled"
else:
name = extractFilename(t.filename)
if win.globalSettings.truncateLongTitles:
if len(name) > 20: name = name[0..16] & "..."
if not t.saved:
name.add(" *")
if t.saved and t.isTemporary:
t.label.setMarkup(name & "<span color=\"#CC0E0E\"> *</span>")
else:
t.label.setText(name)
setTabTooltip(t)
proc checkFileUpdate(pageNum: int) =
## Checks if the currently opened tab has been updated outside of Aporia.
if win.tabs[pageNum].filename == "":
return
var changedInfo: FileInfo = getFileInfo(win.tabs[pageNum].filename)
if win.tabs[pageNum].lastEdit != changedInfo.lastWriteTime:
win.filecheckbar.show()
proc updateFile(infobar: PInfoBar, response: gint) =
## Updates the currently opened tab to the most recent revision
## of the file.
var pageNum = win.sourceViewTabs.getCurrentPage()
var changedInfo: FileInfo = getFileInfo(win.tabs[pageNum].filename)
if response == ResponseAccept:
var fileTxt: string = readFile(win.tabs[pageNum].filename)
win.tabs[pageNum].buffer.set_text(fileTxt, len(fileTxt).int32)
win.tabs[pageNum].saved = true
else:
win.tabs[pageNum].saved = false
win.tabs[pageNum].lastEdit = changedInfo.lastWriteTime
win.filecheckbar.hide()
proc updateSettings() =
## Updates the settings.
# Toggle toolbar:
if win.globalSettings.toolBarVisible:
win.toolBar.show()
else:
win.toolBar.hide()
# Toggle bottom panel:
if win.autoSettings.bottomPanelVisible:
win.bottomPanelTabs.show()
else:
win.bottomPanelTabs.hide()
# Output font:
var outputFont = font_description_from_string(win.globalSettings.outputFont)
win.outputTextView.modifyFont(outputFont)
var schemeMan = schemeManagerGetDefault()
win.scheme = schemeMan.getScheme(win.globalSettings.colorSchemeID)
var font = fontDescriptionFromString(win.globalSettings.font)
for i in 0..high(win.tabs):
var tab = win.tabs[i]
# Color scheme:
tab.buffer.setScheme(win.scheme)
# Font:
tab.sourceView.modifyFont(font)
# Line numbers:
tab.sourceView.setShowLineNumbers(win.globalSettings.showLineNumbers)
# Highlight current line:
tab.sourceView.setHighlightCurrentLine(win.globalSettings.highlightCurrentLine)
# Show right margin:
tab.sourceView.setShowRightMargin(win.globalSettings.rightMargin)
# Bracket matching:
tab.buffer.setHighlightMatchingBrackets(win.globalSettings.highlightMatchingBrackets)
# Indent width:
tab.sourceView.setIndentWidth(win.globalSettings.indentWidth)
# Auto indent:
tab.sourceView.setAutoIndent(win.globalSettings.autoIndent)
# Wrap mode:
tab.sourceView.setWrapMode(win.globalSettings.wrapMode)
# Tab close buttons:
if win.globalSettings.showCloseOnAllTabs:
tab.closeBtn.show()
else:
if i == win.sourceViewTabs.getCurrentPage():
tab.closeBtn.show()
else:
tab.closeBtn.hide()
# Tab titles:
updateTabUI(tab)
proc saveTab(tabNr: int, startpath: string, updateGUI: bool = true) =
## If tab's filename is ``""`` and the user clicks "Cancel", the filename will
## remain ``""``.
# TODO: Refactor this function. It's a disgrace.
if tabNr < 0: return
if win.tabs[tabNr].saved: return
var path = ""
if win.tabs[tabNr].filename == "":
path = chooseFileToSave(win.w, startpath)
if path != "":
# Change syntax highlighting for this tab.
var langMan = languageManagerGetDefault()
var lang = langMan.guessLanguage(path, nil)
if lang != nil:
win.setLanguage(tabNr, lang)
win.setHighlightSyntax(tabNr, true)
else:
win.setHighlightSyntax(tabNr, false)
if tabNr == win.getCurrentTab:
plCheckUpdate(tabNr)
else:
path = win.tabs[tabNr].filename
if path != "":
var buffer = PTextBuffer(win.tabs[tabNr].buffer)
# Get the text from the TextView
var startIter: TTextIter
buffer.getStartIter(addr(startIter))
var endIter: TTextIter
buffer.getEndIter(addr(endIter))
var text = $buffer.getText(addr(startIter), addr(endIter), false)
var config = false
if path == os.getConfigDir() / "Aporia" / "config.global.ini":
# If we are overwriting Aporia's config file, validate it.
cfgErrors = @[]
var newSettings = cfg.loadGlobal(cfgErrors, newStringStream($text))
if cfgErrors.len > 0:
showConfigErrors()
return
win.globalSettings = newSettings
updateSettings()
config = true
# Handle text before saving
text = win.tabs[tabNr].lineEnding.normalize(text)
win.tabs[tabNr].lineEnding.addExtraNL(text)
# Save it to a file
var f: File
if open(f, path, fmWrite):
f.write(text)
f.close()
win.tempStuff.lastSaveDir = splitFile(path).dir
# Change the tab name and .Tabs.filename etc.
win.tabs[tabNr].filename = path
win.tabs[tabNr].lastEdit = getTime()
if updateGUI:
win.tabs[tabNr].saved = true
updateMainTitle(tabNr)
if config:
win.statusbar.setTemp("Config saved successfully.", UrgSuccess)
else:
win.statusbar.setTemp("File saved successfully.", UrgSuccess)
else:
error(win.w, "Unable to write to file: " & oSErrorMsg(osLastError()))
proc saveTabAs(tab: int, startPath: string): bool =
## Returns whether we saved to a different filename.
var (filename, saved) = (win.tabs[tab].filename, win.tabs[tab].saved)
win.tabs[tab].saved = false
win.tabs[tab].filename = ""
# saveTab will ask the user for a filename if the tab's filename is "".
saveTab(tab, startpath)
# If the user cancels the save file dialog. Restore the previous filename
# and saved state
if win.tabs[tab].filename == "":
win.tabs[tab].filename = filename
win.tabs[tab].saved = saved
result = win.tabs[tab].filename != filename
updateMainTitle(tab)
proc saveAllTabs() =
for i in 0..high(win.tabs):
saveTab(i, os.splitFile(win.tabs[i].filename).dir)
proc exit() =
# gather some settings
win.autoSettings.VPanedPos = PPaned(win.sourceViewTabs.getParent()).getPosition()
win.autoSettings.winWidth = win.w.allocation.width
win.autoSettings.winHeight = win.w.allocation.height
# save the settings
win.save()
# then quit
main_quit()
# GTK Events
# -- w(PWindow)
proc confirmUnsaved(win: var MainWin, t: Tab): int =
var askSave = win.w.messageDialogNew(0, MessageWarning, BUTTONS_NONE, nil)
askSave.setTransientFor(win.w)
if t.filename != "":
let name = t.filename.extractFilename
if t.isTemporary:
if t.saved:
askSave.setMarkup(name & " is saved in your system's temporary" &
" directory, what would you like to do?")
askSave.addButtons("_Save in a different directory", ResponseAccept,
STOCK_CANCEL, ResponseCancel,
"Close _without saving", ResponseReject, nil)
else:
askSave.setMarkup("An old version of " & name & " is saved in your " &
"system's temporary directory. What would you like to do?")
askSave.addButtons("Save in a _different directory", ResponseAccept,
STOCK_SAVE, ResponseOK,
STOCK_CANCEL, ResponseCancel,
"Close _without saving", ResponseReject, nil)
else:
askSave.setMarkup(name & " is not saved, would you like to save it?")
askSave.addButtons(STOCK_SAVE, ResponseAccept, STOCK_CANCEL, ResponseCancel,
"Close _without saving", ResponseReject, nil)
else:
askSave.setMarkup("Would you like to save this tab?")
askSave.addButtons(STOCK_SAVE, ResponseAccept, STOCK_CANCEL, ResponseCancel,
"Close _without saving", ResponseReject, nil)
# TODO: GtkMessageDialog's label seems to wrap lines...
result = askSave.run()
gtk2.destroy(PWidget(askSave))
proc askCloseTab(tab: int): bool =
result = true
if not win.tabs[tab].saved and not win.tabs[tab].isTemporary:
# Only ask to save if file isn't empty or has a "history" (undo can be performed)
if win.tabs[tab].buffer.get_char_count != 0 or can_undo(win.tabs[tab].buffer):
var resp = win.confirmUnsaved(win.tabs[tab])
if resp == RESPONSE_ACCEPT:
saveTab(tab, os.splitFile(win.tabs[tab].filename).dir)
result = true
elif resp == RESPONSE_CANCEL:
result = false
elif resp == RESPONSE_REJECT:
result = true
else:
result = false
if win.tabs[tab].isTemporary:
var resp = win.confirmUnsaved(win.tabs[tab])
if resp == RESPONSE_ACCEPT:
result = saveTabAs(tab, os.splitFile(win.tabs[tab].filename).dir)
elif resp == RESPONSE_OK:
assert(not win.tabs[tab].saved)
saveTab(tab, os.splitFile(win.tabs[tab].filename).dir)
result = true
elif resp == RESPONSE_CANCEL:
result = false
elif resp == RESPONSE_REJECT:
result = true
else:
result = false
proc delete_event(widget: PWidget, event: PEvent, user_data: Pgpointer): gboolean =
var quit = true
for i in win.tabs.low .. win.tabs.len-1:
if not win.tabs[i].saved or win.tabs[i].isTemporary:
win.sourceViewTabs.setCurrentPage(i.int32)
quit = askCloseTab(i)
if not quit: break
# If false is returned the window will close
return not quit
proc windowState_Changed(widget: PWidget, event: PEventWindowState,
user_data: Pgpointer) =
win.autoSettings.winMaximized = (event.newWindowState and
WINDOW_STATE_MAXIMIZED) != 0
if (event.newWindowState and WINDOW_STATE_ICONIFIED) != 0:
win.suggest.hide()
proc window_configureEvent(widget: PWidget, event: PEventConfigure,
ud: Pgpointer): gboolean =
if win.suggest.shown:
var current = win.sourceViewTabs.getCurrentPage()
var tab = win.tabs[current]
var start: TTextIter
# Get the iter at the cursor position.
tab.buffer.getIterAtMark(addr(start), tab.buffer.getInsert())
moveSuggest(win, addr(start), tab)
return false
proc cycleTab(win: var MainWin) =
var current = win.sourceViewTabs.getCurrentPage()
if current + 1 >= win.tabs.len():
current = 0
else:
current.inc(1)
# select next tab
win.sourceViewTabs.setCurrentPage(current)
proc fileMenuItem_Activate(menu: PMenuItem, user_data: Pgpointer)
proc closeTab(tab: int) =
proc recentlyOpenedAdd(filename: string) =
for i in 0 .. win.autoSettings.recentlyOpenedFiles.len-1:
if win.autoSettings.recentlyOpenedFiles[i] == filename:
system.delete(win.autoSettings.recentlyOpenedFiles, i)
break
win.autoSettings.recentlyOpenedFiles.add(filename)
when defined(macosx):
# FIXME: This is a small workaround because the activate event isn't
# triggered through OSX's top menu bar.
fileMenuItem_Activate(nil, nil)
var close = askCloseTab(tab)
if close:
# Add to recently opened files.
if win.tabs[tab].filename != "":
recentlyOpenedAdd(win.tabs[tab].filename)
system.delete(win.tabs, tab)
win.sourceViewTabs.removePage(int32(tab))
win.save()
proc window_keyPress(widg: PWidget, event: PEventKey,
userData: Pgpointer): gboolean =
result = false
var modifiers = acceleratorGetDefaultModMask()
if (event.state and modifiers) == CONTROL_MASK:
# Ctrl pressed.
case event.keyval
of KeyTab:
# Ctrl + Tab
win.cycleTab()
return true
of KeyW:
# Ctrl + W
if win.sourceViewTabs.getNPages() > 1:
closeTab(win.sourceViewTabs.getCurrentPage())
return true
else:
discard
if event.keyval == KeyEscape:
# Esc pressed
win.findBar.hide()
win.goLineBar.bar.hide()
var current = win.sourceViewTabs.getCurrentPage()
win.tabs[current].sourceView.grabFocus()
# -- SourceView(PSourceView) & SourceBuffer
proc updateHighlightAll(buffer: PTextBuffer, markName: string = "") =
# Called when the highlighted text should be updated. i.e. new selection
# has been made.
var insert, selectBound: TTextIter
if buffer.getSelectionBounds(addr(insert), addr(selectBound)):
# There is a selection
let frmLn = getLine(addr(insert)) + 1
let toLn = getLine(addr(selectBound)) + 1
# Highlighting
if frmLn == toLn and win.globalSettings.selectHighlightAll:
template h: untyped = win.tabs[getCurrentTab(win)].highlighted
# Same line.
var term = buffer.getText(addr(insert), addr(selectBound), false)
highlightAll(win, $term, false)
if not win.globalSettings.searchHighlightAll and h.forSearch and
markName == "selection_bound":
# Override the search selection block, this means that after searching
# selecting text manually will still highlight things instead of you
# having to close the find bar.
h = newNoHighlightAll()
else: # multiple lines selected
if win.globalSettings.selectHighlightAll:
stopHighlightAll(win, false)
else:
if win.globalSettings.selectHighlightAll:
stopHighlightAll(win, false)
proc updateStatusBar(buffer: PTextBuffer, markName: string = "") =
# Incase this event gets fired before
# statusBar is initialized
if win.statusbar != nil and not win.tempStuff.stopSBUpdates:
var insert, selectBound: TTextIter
if buffer.getSelectionBounds(addr(insert), addr(selectBound)):
# There is a selection
let frmLn = getLine(addr(insert)) + 1
let toLn = getLine(addr(selectBound)) + 1
let frmChar = getLineOffset(addr(insert))
let toChar = getLineOffset(addr(selectBound))
win.statusbar.setDocInfoSelected(frmLn, toLn, frmChar, toChar)
else:
let ln = getLine(addr(insert)) + 1
let ch = getLineOffset(addr(insert))
win.statusbar.setDocInfo(ln, ch)
proc cursorMoved(buffer: PTextBuffer, location: PTextIter,
mark: PTextMark, user_data: Pgpointer){.cdecl.} =
var markName = mark.getName()
if markName == nil:
return # We don't want anonymous marks.
if $markName == "insert" or $markName == "selection_bound":
updateStatusBar(buffer, $markName)
updateHighlightAll(buffer, $markName)
proc onCloseTab(btn: PButton, child: PWidget)
proc tab_buttonRelease(widg: PWidget, ev: PEventButton,
userDat: PWidget): gboolean
proc createTabLabel(name: string, t_child: PWidget, filename: string): tuple[box: PWidget,
label: PLabel, closeBtn: PButton] =
var eventBox = eventBoxNew()
eventBox.setVisibleWindow(false)
discard signal_connect(eventBox, "button-release-event",
SIGNAL_FUNC(tab_buttonRelease), t_child)
var box = hboxNew(false, 0)
var label = labelNew(name)
if filename.startsWith(getTempDir()):
# If this is a temporary tab, mark it as such.
label.setMarkup(name & "<span color=\"#CC0E0E\"> *</span>")
var closebtn = buttonNew()
closeBtn.setLabel(nil)
var iconSize = iconSizeFromName("tabIconSize")
if iconSize == 0:
iconSize = iconSizeRegister("tabIconSize", 10, 10)
var image = imageNewFromStock(STOCK_CLOSE, iconSize)
discard gSignalConnect(closebtn, "clicked", G_Callback(onCloseTab), t_child)
closebtn.setImage(image)
gtk2.setRelief(closebtn, RELIEF_NONE)
box.packStart(label, true, true, 0)
box.packEnd(closebtn, false, false, 0)
box.showAll()
eventBox.add(box)
return (eventBox, label, closeBtn)
proc onModifiedChanged(buffer: PTextBuffer, theTab: gpointer) =
## This signal is called when the modification state of ``buffer`` is changed.
# <del>*Warning* we assume here that the currently selected tab was modified.</del>
var ctab = cast[Tab](theTab)
#assert ((current > 0) and (current < win.tabs.len))
updateTabUI(cTab)
updateMainTitle(win.sourceViewTabs.getCurrentPage())
proc onChanged(buffer: PTextBuffer, sv: PSourceView) =
## This function is connected to the "changed" event on `buffer`.
updateStatusBar(buffer, "")
updateHighlightAll(buffer)
proc sourceViewKeyPress(sourceView: PWidget, event: PEventKey,
userData: Pgpointer): gboolean =
result = false
let keyNameCString = keyval_name(event.keyval)
if keyNameCString == nil: return
let key = $keyNameCString
case unicode.toLower(key)
of "up", "down", "page_up", "page_down":
if win.globalSettings.suggestFeature and win.suggest.shown:
var selection = win.suggest.treeview.getSelection()
var selectedIter: TTreeIter
var TreeModel = win.suggest.treeView.getModel()
let childrenLen = TreeModel.iter_n_children(nil)
# Get current tab (for tooltip)
var current = win.sourceViewTabs.getCurrentPage()
var tab = win.tabs[current]
template nextTimes(t: untyped): typed {.immediate.} =
for i in 0..t:
if selectedPath.getIndices[]+1 < childrenLen:
next(selectedPath)
template prevTimes(t: untyped): typed {.immediate.} =
for i in 0..t:
discard prev(selectedPath)
if selection.getSelected(cast[PPGtkTreeModel](addr(TreeModel)),
addr(selectedIter)):
var selectedPath = TreeModel.getPath(addr(selectedIter))
var moved = false
case unicode.toLower(key):
of "up":
moved = prev(selectedPath)
of "down":
moved = true
next(selectedPath)
of "page_up":
moved = true
prevTimes(5)
of "page_down":
moved = true
nextTimes(5)
else:
discard
if moved:
# selectedPath is now the next or prev path.
selection.selectPath(selectedPath)
win.suggest.treeview.scroll_to_cell(selectedPath, nil, false, 0.5, 0.5)
var index = selectedPath.getIndices()[]
if win.suggest.items.len() > index:
win.showTooltip(tab, win.suggest.items[index], selectedPath)
else:
# No item selected, select the first one.
var selectedPath = tree_path_new_first()
selection.selectPath(selectedPath)
win.suggest.treeview.scroll_to_cell(selectedPath, nil, false, 0.5, 0.5)
var index = selectedPath.getIndices()[]
assert(index == 0)
if win.suggest.items.len() > index:
win.showTooltip(tab, win.suggest.items[index], selectedPath)
# Return true to stop this event from moving the cursor down in the
# source view.
return true
of "left", "right", "home", "end", "delete":
if win.globalSettings.suggestFeature and win.suggest.shown:
win.suggest.hide()
of "return", "space", "tab", "period":
if win.globalSettings.suggestFeature and win.suggest.shown:
echod("[Suggest] Selected.")
var selection = win.suggest.treeview.getSelection()
var selectedIter: TTreeIter
var TreeModel = win.suggest.treeView.getModel()
if selection.getSelected(cast[PPGtkTreeModel](addr(TreeModel)),
addr(selectedIter)):
var selectedPath = TreeModel.getPath(addr(selectedIter))
var index = selectedPath.getIndices()[]
win.insertSuggestItem(index)
return unicode.toLower(key) != "period"
of "backspace":
if win.globalSettings.suggestFeature and win.suggest.shown:
var current = win.sourceViewTabs.getCurrentPage()
var tab = win.tabs[current]
var endIter: TTextIter
# Get the iter at the cursor position.
tab.buffer.getIterAtMark(addr(endIter), tab.buffer.getInsert())
# Get an iter one char behind.
var startIter: TTextIter = endIter
if (addr(startIter)).backwardChar(): # Can move back.
# Get the character immediately behind.
var behind = (addr(startIter)).getText(addr(endIter))
assert(behind.len() == 1)
if $behind == ".": # Note the $, I guess I must convert it into a nimstr
win.suggest.hide()
else:
# handled in ...KeyRelease
discard
else:
discard
proc sourceViewKeyRelease(sourceView: PWidget, event: PEventKey,
userData: Pgpointer): gboolean =
result = true
let ctrlPressed = (event.state and ControlMask) != 0
let keyNameCString = keyval_name(event.keyval)
if keyNameCString == nil: return
let key = $keyNameCString
case unicode.toLower(key)
of "period":
discard
# TODO: Disable implicit invocation of suggest until it's more stable.
#if win.globalSettings.suggestFeature and win.getCurrentLanguage() == "nim":
# if win.suggest.items.len() != 0: win.suggest.clear()
# doSuggest(win)
of "backspace":
if win.globalSettings.suggestFeature and win.suggest.shown:
# Don't need to know the char behind, because if it is a dot, then
# the suggest dialog is hidden by ...KeyPress
win.filterSuggest()
win.doMoveSuggest()
of "space":
if win.globalSettings.suggestFeature and not win.suggest.shown and
unicode.toLower(key) == "space" and ctrlPressed and
win.getCurrentLanguage() == "nim":
if win.suggest.items.len() != 0: win.suggest.clear()
doSuggest(win)
result = false
#win.filterSuggest()
else:
if unicode.toLower(key) notin ["up", "down", "page_up", "page_down", "home", "end"]:
if win.globalSettings.suggestFeature and win.suggest.shown:
win.filterSuggest()
win.doMoveSuggest()
proc sourceViewMousePress(sourceView: PWidget, ev: PEvent, usr: gpointer): gboolean =
win.suggest.hide()
type
AddTabOption = enum
tabSetCurrent,
tabTryToReload
proc addTab(name, filename: string, options = {tabSetCurrent},
encoding = "utf-8"): int
proc goToDef_Activate(i: PMenuItem, p: pointer) {.cdecl.} =
let currentPage = win.sourceViewTabs.getCurrentPage()
let tab = win.tabs[currentPage]
if win.getCurrentLanguage(currentPage) != "nim":
win.statusbar.setTemp("This feature is only supported for Nim.", UrgError)
return
var cursor: TTextIter
tab.buffer.getIterAtMark(addr(cursor), tab.buffer.getInsert())
proc onSugLine(win: var MainWin, line: string) {.closure.} =
var def: SuggestItem
if parseIDEToolsLine("def", line, def):
win.tempStuff.gotDefinition = true
let existingTab = win.findTab(def.file, true)
if existingTab != -1:
win.sourceViewTabs.setCurrentPage(existingTab.gint)
else:
doAssert addTab("", def.file) != -1
let currentPage = win.sourceViewTabs.getCurrentPage()
# Go to that line/col
var iter: TTextIter
win.tabs[currentPage].buffer.getIterAtLineIndex(addr(iter),
def.line-1, def.col-1)
win.tabs[currentPage].buffer.placeCursor(addr(iter))
win.forceScrollToInsert()
echod("goToDef, parsed definition as:")
echod(def)
proc onSugExit(win: var MainWin, exitCode: int) {.closure.} =
if not win.tempStuff.gotDefinition:
win.statusbar.setTemp("Definition retrieval failed.", UrgError, 5000)
proc onSugError(win: var MainWin, error: string) {.closure.} =
if not win.tempStuff.gotDefinition:
win.statusbar.setTemp("Definition retrieval failed: " & error,
UrgError, 5000)
win.tempStuff.gotDefinition = false
var err = win.asyncGetDef(tab.filename, getLine(addr cursor),
getLineOffset(addr cursor), onSugLine, onSugExit, onSugError)
if err != "":
win.statusbar.setTemp(err, UrgError, 5000)
proc sourceView_PopulatePopup(entry: PTextView, menu: PMenu, u: pointer) =
if win.getCurrentLanguage() == "nim":
createSeparator(menu)
createMenuItem(menu, "Go to definition...", goToDef_Activate)
proc sourceView_Adjustment_valueChanged(adjustment: PAdjustment,
spb: ptr tuple[lastUpper, value: float]) =
let value = adjustment.getValue
if adjustment.getUpper == spb[][0]:
spb[][1] = value
proc sourceView_sizeAllocate(sourceView: PSourceView,
allocation: gdk2.PRectangle, spb: ptr tuple[lastUpper, value: float]) =
# TODO: This implementation has some issues: when we add a new line
# when at the very bottom of the TextView, the TextView jumps up and down.
# TODO: Go back to my old implementation. Where the adjustment's upper
# value only gets adjusted when scrolling past bottom. This will get rid of
# the scroll bar jumping.
let adjustment = sourceView.get_vadjustment()
var upper = adjustment.get_upper()
let pagesize = adjustment.get_page_size()
# we have less lines than the viewport can hold
if upper == pagesize:
let buffer = sourceView.getBuffer()
var iter: TTextIter
getIterAtLine(buffer, addr iter, buffer.getLineCount)
var y, height: gint
sourceView.getLineYRange(addr iter, addr y, addr height)
upper = gdouble(y + height)
#echo("Changed upper to ", upper)
let lineheight = 14.0
let set_to = upper + pagesize - lineheight
adjustment.set_upper(set_to)
#echo("New upper: ", setTo)
# scroll back to our old position, unless we actually scroll downward,
# which means we just added a new line
if adjustment.get_value() < spb[][1]:
adjustment.set_value(spb[][1])
#echo("New Value: ", spb[][1])
spb[] = (set_to, adjustment.get_value())
# Other(Helper) functions
proc initSourceView(sourceView: var PSourceView, scrollWindow: var PScrolledWindow,
buffer: var PSourceBuffer) =
# This gets called by addTab
# Each tabs creates a new SourceView
# SourceScrolledWindow(ScrolledWindow)
scrollWindow = scrolledWindowNew(nil, nil)
scrollWindow.setPolicy(POLICY_AUTOMATIC, POLICY_AUTOMATIC)
scrollWindow.show()
# SourceView(gtkSourceView)
sourceView = sourceViewNew(buffer)
sourceView.setInsertSpacesInsteadOfTabs(true)
sourceView.setIndentWidth(win.globalSettings.indentWidth)
sourceView.setShowLineNumbers(win.globalSettings.showLineNumbers)
sourceView.setHighlightCurrentLine(
win.globalSettings.highlightCurrentLine)
sourceView.setShowRightMargin(win.globalSettings.rightMargin)
sourceView.setAutoIndent(win.globalSettings.autoIndent)
sourceView.setSmartHomeEnd(SmartHomeEndBefore)
sourceView.setWrapMode(win.globalSettings.wrapMode)
discard signalConnect(sourceView, "button-press-event",
SIGNALFUNC(sourceViewMousePress), nil)
discard gSignalConnect(sourceView, "populate-popup",
GCallback(sourceViewPopulatePopup), nil)
var font = font_description_from_string(win.globalSettings.font)
sourceView.modifyFont(font)
scrollWindow.add(sourceView)
sourceView.show()
buffer.setHighlightMatchingBrackets(
win.globalSettings.highlightMatchingBrackets)
discard signalConnect(sourceView, "key-press-event",
SIGNALFUNC(sourceViewKeyPress), nil)
discard signalConnect(sourceView, "key-release-event",
SIGNALFUNC(sourceViewKeyRelease), nil)
# -- Set the syntax highlighter scheme
buffer.setScheme(win.scheme)
proc loadFileIntoTab(nTab: Tab; buffer: PSourceBuffer; filename, encoding: string): bool =
var fileTxt = readFile(filename)
if encoding.toLowerAscii() != "utf-8":
fileTxt = convert(fileTxt, "UTF-8", encoding)
if not g_utf8_validate(fileTxt, fileTxt.len().gssize, nil):
win.tempStuff.pendingFilename = filename
win.statusbar.setTemp("Could not open file with " &
encoding & " encoding.", UrgError, 5000)
win.infobar.show()
return false
# Detect line endings.
nTab.lineEnding = detectLineEndings(fileTxt)
# Normalize to LF to fix extra newline after copying issue on Windows.
fileTxt = normalize(leLf, fileTxt)
# Read in the file.
buffer.set_text(fileTxt, len(fileTxt).int32)
return true
proc addTab(name, filename: string, options = {tabSetCurrent},
encoding = "utf-8"): int =
## Adds a tab. If filename is not "", a file is read and set as the content
## of the new tab. If name is "" it will be either "Unknown" or the last part
## of the filename.
## If filename doesn't exist IOError is raised.
##
## Returns the index of the added tab (or existing tab if setCurrent is true).
## ``-1`` is returned upon error.
assert(win.nimLang != nil)
var buffer: PSourceBuffer = sourceBufferNew(win.nimLang)
if filename != nil and filename != "":
if tabSetCurrent in options:
# If a tab with the same filename already exists select it.
var existingTab = win.findTab(filename)
if existingTab != -1:
if tabTryToReload in options:
discard loadFileIntoTab(win.tabs[existingTab],
win.tabs[existingTab].buffer,
filename, encoding)
# Select the existing tab
win.sourceViewTabs.setCurrentPage(int32(existingTab))
return existingTab
# Guess the language of the file loaded
var langMan = languageManagerGetDefault()
var lang = langMan.guessLanguage(filename, nil)
if lang != nil:
buffer.setLanguage(lang)
else:
buffer.setHighlightSyntax(false)
# Init tab
var nTab: Tab; new(nTab)
# Init the sourceview
var sourceView: PSourceView
var scrollWindow: PScrolledWindow
initSourceView(sourceView, scrollWindow, buffer)
var nam = name
if nam == "": nam = "Untitled"
if filename == "": nam.add(" *")
elif filename != "" and name == "":
# Disable the undo/redo manager.
buffer.begin_not_undoable_action()
# Read the file first so that we can affirm its encoding.
try:
if not loadFileIntoTab(nTab, buffer, filename, encoding):
return -1
except IOError: raise
finally:
# Enable the undo/redo manager.
buffer.end_not_undoable_action()
# Get the name.ext of the filename, for the tabs title
nam = extractFilename(filename)
# Truncate title to 20 chars
if win.globalSettings.truncateLongTitles:
if len(nam) > 20: nam = nam[0..16] & "..."
var (TabLabel, labelText, closeBtn) = createTabLabel(nam, scrollWindow, filename)
# Add a tab
nTab.buffer = buffer
nTab.sourceView = sourceView
nTab.label = labelText
nTab.saved = (filename != "")
nTab.filename = filename
nTab.closeBtn = closeBtn
nTab.highlighted = newNoHighlightAll()
if not win.globalSettings.showCloseOnAllTabs:
nTab.closeBtn.hide()
if filename != "":
nTab.lastEdit = getFileInfo(filename).lastWriteTime
win.tabs.add(nTab)
# Set the tooltip
setTabTooltip(win.tabs[win.tabs.len-1])
# Add the tab to the GtkNotebook
let res = win.sourceViewTabs.appendPage(scrollWindow, TabLabel)
assert res != -1
win.sourceViewTabs.setTabReorderable(scrollWindow, true)
PTextView(sourceView).setBuffer(nTab.buffer)
# UGLY workaround for yet another compiler bug:
discard gsignalConnect(buffer, "mark-set",
GCallback(aporia.cursorMoved), nil)
discard gsignalConnect(buffer, "modified-changed",
GCallback(onModifiedChanged),
cast[gpointer](win.tabs[win.tabs.len-1]))
# TODO: If the following gets called at any time because text was loaded from a file,
# use connect_after to connect "insert-text" signal, and then connect this signal
# in the handler of "insert-text".
discard gsignalConnect(buffer, "changed", GCallback(aporia.onChanged), sourceView)
# Adjustment signals for scrolling past bottom.
if win.globalSettings.scrollPastBottom:
discard sourceView.get_vadjustment().signalConnect("value_changed",
SIGNALFUNC(sourceView_Adjustment_valueChanged), addr nTab.spbInfo)
discard sourceView.signalConnect("size-allocate",