-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy patheditor.py
executable file
·1278 lines (1134 loc) · 43.5 KB
/
editor.py
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys
import os
import os.path
import keyword
import code
import inspect
import operator
use_subprocess = True
try:
import subprocess
except ImportError:
use_subprocess = False
from .. import ui
from ..application import dApp
from .. import events
from ..dLocalize import _
from ..lib.reportUtils import getTempFile
from ..ui import dBaseMenuBar
from ..ui import dBitmapButton
from ..ui import dDropdownList
from ..ui import dEditBox
from ..ui import dEditor
from ..ui import dForm
from ..ui import dImage
from ..ui import dLabel
from ..ui import dMenu
from ..ui import dOkCancelDialog
from ..ui import dPage
from ..ui import dPageFrame
from ..ui import dPanel
from ..ui import dSizer
from ..ui import dSplitter
from ..ui import dTextBox
class EditPageSplitter(dSplitter):
def __init__(self, *args, **kwargs):
kwargs["createPanes"] = True
super(EditPageSplitter, self).__init__(*args, **kwargs)
self.ShowPanelSplitMenu = False
def initProperties(self):
self.Width = 250
self.Height = 200
self.MinimumPanelSize = 20
def onSashDoubleClick(self, evt):
evt.stop()
def onContextMenu(self, evt):
evt.stop()
def onSashPositionChanged(self, evt):
self.Parent.updateSashPos()
class EditorEditor(dEditor):
def addDroppedText(self, txt):
curr = self.Value
ss, se = self.SelectionStart, self.SelectionEnd
self.Value = "%s%s%s" % (curr[:ss], txt, curr[se:])
self.SelectionStart = ss
self.SelectionEnd = ss + len(txt)
def _getTextSource(self):
return self.Form.getTextSource()
class EditorPage(dPage):
def initProperties(self):
self.p = None
self.outputText = ""
self._outputSashExtra = self.Application.getUserSetting("editorform.outputSashExtra", 100)
def afterInit(self):
self.splitter = EditPageSplitter(self, Orientation="h")
self.splitter.SashPosition = self.Height - self._outputSashExtra
self.splitter.Panel1.Sizer = dSizer()
self.splitter.Panel2.Sizer = dSizer()
self.editor = EditorEditor(self.splitter.Panel1)
self.editor.UseBookmarks = True
self.editor.page = self
self.output = dEditBox(self.splitter.Panel2)
self.output.ReadOnly = True
self.splitter.Panel1.Sizer.append1x(self.editor)
self.splitter.Panel2.Sizer.append1x(self.output)
self.Sizer = dSizer()
self.Sizer.append1x(self.splitter)
self.updateTimer = ui.callEvery(1000, self.outputUpdate)
self.layout()
self.editor.setFocus()
self.editor.bindEvent(events.TitleChanged, self.onTitleChanged)
self.editor.bindEvent(events.MouseRightClick, self.Form.onEditorRightClick)
# Set up the file drop target
self.editor.DroppedFileHandler = self.Form
# Set up the text drop target
### NOTE: currently we can only have text or file drops, not both
self.editor.DroppedTextHandler = self.Form
# Update Hide/Show of output. Default to hidden
self.showOutput(self.Application.getUserSetting("visibleOutput", False))
# Set the initial title
ui.callAfter(self.onTitleChanged, None)
# It's weird without this, self.splitter._constructed is not true
ui.callAfter(self.splitter._setOrientation, "h")
ui.callAfter(self.updateSashPos)
def onResize(self, evt):
self.splitter.SashPosition = self.Height - self._outputSashExtra
def updateSashPos(self):
if self.splitter.SashPosition > 0:
self._outputSashExtra = self.Height - self.splitter.SashPosition
self.Application.setUserSetting("editorform.outputSashExtra", self._outputSashExtra)
def outputUpdate(self):
if self and self.p:
# need a nonblocking way of getting stdout and stderr
self.outputText = self.outputText + self.p.stdout.read() + self.p.stderr.read()
if not self.p.poll() is None:
self.p = None
self.output.Value = self.outputText
def showOutput(self, show):
self.splitter.Split = show
def onTitleChanged(self, evt):
title = self.editor._title
self.Caption = title
self.Form.onTitleChanged(evt)
def onPageEnter(self, evt):
self.editor.setFocus()
def onPageLeave(self, evt):
self.editor.setInactive()
def onDestroy(self, evt):
ui.callAfter(self.Form.onTitleChanged, evt)
def _getPathInfo(self):
try:
ret = self.editor._fileName
except:
ret = ""
return ret
PathInfo = property(_getPathInfo, None, None, _("Path to the file being edited (str)"))
class EditorPageFrame(dPageFrame):
def beforeInit(self):
self.PageClass = EditorPage
def getTextSource(self):
txt = []
for pg in self.Pages:
txt.append(pg.editor.Value)
return " ".join(txt)
def checkChanges(self, closing=False):
"""Cycle through the pages, and if any contain unsaved changes,
ask the user if they should be saved. If they cancel, immediately
stop and return False. If they say yes, save the contents. Unless
they cancel, close each page.
"""
ret = True
for pg in self.Pages[::-1]:
ed = pg.editor
ret = ed.checkChangesAndContinue()
if not ret:
break
elif closing:
self.PageCount -= 1
return ret
def findEditor(self, pth, selectIt=False):
"""Returns the editor that is editing the specified file. If there
is no matching editor, returns None. If selectIt is True, makes that
editor the active editor.
"""
ret = None
for pg in self.Pages:
if pg.editor._fileName == pth:
ret = pg.editor
if selectIt:
self.SelectedPage = pg
return ret
def editFile(self, pth, selectIt=False):
ret = self.findEditor(pth, selectIt)
if ret is None:
# Create a new page
pg = self.getBlankPage(True)
try:
fileTarget = pg.editor.openFile(pth)
if fileTarget:
self.SelectedPage = pg
ret = pg
except Exception as e:
dabo.log.error(_("Error opening file '%(pth)s': %(e)s") % locals())
ui.callAfter(self.removePage, pg)
ret = None
return ret
def getBlankPage(self, create=False):
"""Returns the first page that is not associated with a file,
and which has not been modified. If no such page exists, and
the 'create' parameter is True, a new blank page is created
and returned. Otherwise, returns None.
"""
ret = None
for pg in self.Pages:
ed = pg.editor
if ed._title.strip() == ed._newFileName.strip():
ret = pg
break
if ret is None and create:
self.PageCount += 1
ret = self.Pages[-1]
return ret
def closeEditor(self, ed=None, checkChanges=True):
if ed is None:
ed = self.SelectedPage.editor
if checkChanges:
ret = ed.checkChangesAndContinue()
else:
ret = True
if ret is not False:
self.removePage(ed.page)
return ret
def newEditor(self):
ret = self.getBlankPage(True)
self.SelectedPage = ret
return ret
def selectByCaption(self, cap):
pgs = [pg for pg in self.Pages if pg.Caption == cap]
if pgs:
pg = pgs[0]
else:
dabo.log.error(_("No matching page for %s") % cap)
return
self.SelectedPage = pg
pg.editor.setFocus()
def edFocus(self):
self.SelectedPage.editor.setFocus()
def _getCurrentEditor(self):
try:
return self.SelectedPage.editor
except:
return None
def _getTitle(self):
sp = self.SelectedPage
try:
ret = sp.PathInfo
if sp.editor.Modified:
ret += " *"
except:
ret = ""
return ret
CurrentEditor = property(
_getCurrentEditor,
None,
None,
_("References the currently active editor (dEditor)"),
)
Title = property(_getTitle, None, None, _("Title of the active page (str)"))
class EditorForm(dForm):
def __init__(self, *args, **kwargs):
super(EditorForm, self).__init__(*args, **kwargs)
def afterInit(self):
# Set up the file drop target
self.DroppedFileHandler = self
pnl = dPanel(self)
self.Sizer.append1x(pnl)
pnl.Sizer = dSizer("v")
self._lastPath = self.Application.getUserSetting("lastPath", os.getcwd())
super(EditorForm, self).afterInit()
self.Caption = _("Dabo Editor")
self.funcButton = dImage(
pnl,
ScaleMode="Clip",
Size=(22, 22),
ToolTipText=_("Show list of functions"),
)
# self.funcButton.Picture = ui.imageFromData(funcButtonData())
self.funcButton.bindEvent(events.MouseLeftDown, self.onFuncButton)
self.bmkButton = dImage(
pnl, ScaleMode="Clip", Size=(22, 22), ToolTipText=_("Manage Bookmarks")
)
# self.bmkButton.Picture = ui.imageFromData(bmkButtonData())
self.bmkButton.bindEvent(events.MouseLeftDown, self.onBmkButton)
self.prntButton = dBitmapButton(pnl, Size=(22, 22), ToolTipText=_("Print..."))
self.prntButton.Picture = "print"
self.prntButton.bindEvent(events.Hit, self.onPrint)
self.lexSelector = dDropdownList(pnl, ValueMode="String")
self.lexSelector.bindEvent(events.Hit, self.onLexSelect)
btnSizer = dSizer("H", DefaultSpacing=4)
btnSizer.append(self.funcButton)
btnSizer.append(self.bmkButton)
btnSizer.append(self.prntButton)
btnSizer.appendSpacer(10, proportion=1)
lbl = dLabel(pnl, Caption=_("Language:"))
if not self.Application.Platform.lower() == "win":
lbl.FontSize -= 2
self.lexSelector.FontSize -= 2
btnSizer.append(lbl, valign="middle")
btnSizer.append(self.lexSelector, valign="middle")
pnl.Sizer.append(btnSizer, "x", border=4)
self.pgfEditor = EditorPageFrame(pnl, TabPosition="Top")
self.pgfEditor.bindEvent(events.PageChanged, self.onEditorPageChanged)
pnl.Sizer.append1x(self.pgfEditor)
self.layout()
self.fillMenu()
ui.callAfter(self.showPage, 0)
def showPage(self, pg):
"""Shows the specified page, if it exists."""
try:
self.pgfEditor.SelectedPage = pg
self.pgfEditor.edFocus()
except:
pass
def onPrint(self, evt):
self.CurrentEditor.onPrint()
def onActivate(self, evt):
"""Check the files to see if any have been updated on disk."""
self.checkForUpdatedFiles()
def checkForUpdatedFiles(self):
"""If any file being edited has not been modified, and there is a more recent version
on disk, update the file with the version on disk.
"""
for pg in self.pgfEditor.Pages:
ed = pg.editor
if not ed.isChanged() and ed.checkForDiskUpdate():
selpos = ed.SelectionPosition
ed.openFile(ed._fileName)
ed.SelectionPosition = selpos
def onLexSelect(self, evt):
self.CurrentEditor.Language = self.lexSelector.Value
def onFuncButton(self, evt):
evt.stop()
flist = self.CurrentEditor.getFunctionList()
pop = dMenu()
if flist:
for nm, pos, iscls in flist:
prompt = nm
if not iscls:
prompt = " - %s" % nm
itm = pop.append(prompt, OnHit=self.onFunctionPop)
itm.textPosition = pos
else:
pop.append(_("- no functions found -"))
self.showContextMenu(pop)
del pop
def onFunctionPop(self, evt):
ed = self.CurrentEditor
pos = evt.menuItem.textPosition
currLine = ed.LineNumber
newLine = ed.getLineFromPosition(pos)
if newLine > currLine:
ed.moveToEnd()
ed.ensureLineVisible(newLine)
ed.LineNumber = newLine
nextLinePos = ed.getPositionFromLine(newLine + 1)
ed.SelectionPosition = (pos, nextLinePos - 1)
def onIdle(self, evt):
ed = self.CurrentEditor
if ed:
self.StatusText = "Line: %s, Col: %s" % (ed.LineNumber, ed.Column)
def getTextSource(self):
return self.pgfEditor.getTextSource()
def onEditorRightClick(self, evt):
ed = self.CurrentEditor
pos = evt.mousePosition
pp = ed.getPositionFromXY(pos)
if pp < 0:
# They clicked outside of the text area of the line. Find
# a position just to the right of the margin
lpos = ed.getMarginWidth()
pp = ed.getPositionFromXY(lpos, pos[1])
if pp < 0:
# This is a totally blank line. Nothing can be done
return
ln = ed.getLineFromPosition(pp)
ed.LineNumber = ln
self.onBmkButton(evt)
def onBmkButton(self, evt):
evt.stop()
ed = self.CurrentEditor
bmkList = ed.getBookmarkList()
pop = dMenu()
currBmk = ed.getCurrentLineBookmark()
if not currBmk:
pop.append(_("Set Bookmark..."), OnHit=self.onSetBmk)
else:
pop.append(_("Clear Bookmark..."), OnHit=self.onClearBmk)
if bmkList:
pop.append(_("Clear All Bookmarks"), OnHit=self.onClearAllBmk)
pop.appendSeparator()
for nm in bmkList:
itm = pop.append(nm, OnHit=self.onBookmarkPop)
self.showContextMenu(pop)
del pop
def onBookmarkPop(self, evt):
"""Navigate to the chosen bookmark."""
self.CurrentEditor.findBookmark(evt.prompt)
def onSetBmk(self, evt):
"""Need to ask the user for a name for this bookmark."""
nm = ui.getString(message=_("Name for this bookmark:"), caption=_("New Bookmark"))
if not nm:
# User canceled
return
ed = self.CurrentEditor
if nm in ed.getBookmarkList():
msg = (
_(
"There is already a bookmark named '%s'. Creating a new bookmark with the same "
"name will delete the old one. Are you sure you want to do this?"
)
% nm
)
if not ui.areYouSure(
message=msg,
title=_("Duplicate Name"),
defaultNo=True,
cancelButton=False,
):
return
self.CurrentEditor.setBookmark(nm)
def onClearBmk(self, evt):
"""Clear the current bookmark."""
ed = self.CurrentEditor
bmk = ed.getCurrentLineBookmark()
if bmk:
ed.clearBookmark(bmk)
def onClearAllBmk(self, evt):
"""Remove all the bookmarks."""
self.CurrentEditor.clearAllBookmarks()
def onEditorPageChanged(self, evt):
self.checkForUpdatedFiles()
self.onTitleChanged(evt)
self.setCheckedMenus()
self.updateLex()
def updateLex(self):
if self.CurrentEditor:
if not self.lexSelector.Choices:
self.lexSelector.Choices = self.CurrentEditor.getAvailableLanguages()
self.lexSelector.Value = self.CurrentEditor.Language
def setCheckedMenus(self):
ed = self.CurrentEditor
if ed is None:
self._autoAutoItem.Checked = self._wrapItem.Checked = False
self._synColorItem.Checked = self._useTabsItem.Checked = self._lineNumItem = False
else:
self._autoAutoItem.Checked = ed.AutoAutoComplete
self._wrapItem.Checked = ed.WordWrap
self._synColorItem.Checked = ed.SyntaxColoring
self._useTabsItem.Checked = ed.UseTabs
self._lineNumItem.Checked = ed.ShowLineNumbers
self._whiteSpaceItem.Checked = ed.ShowWhiteSpace
self._showOutItem.Checked = self.Application.getUserSetting("visibleOutput", False)
def beforeClose(self, evt):
ret = self.pgfEditor.checkChanges(closing=True)
return ret
def processDroppedFiles(self, filelist):
"""Try to open each file up in an editor tab."""
self.openRecursively(filelist)
def processDroppedText(self, txt):
"""Add the text to the current editor."""
self.CurrentEditor.addDroppedText(txt)
def openRecursively(self, filelist):
if isinstance(filelist, str):
# Individual file passed
filelist = [filelist]
for ff in filelist:
if os.path.isdir(ff):
for fname in os.listdir(ff):
self.openRecursively(os.path.join(ff, fname))
else:
if os.path.isfile(ff):
self.openFile(ff, justReportErrors=True)
def onDocumentationHint(self, evt):
# Eventually, a separate IDE window can optionally display help contents
# for the object. For now, just print the longdoc to the infolog.
dabo.log.info(_("Documentation Hint received:\n\n%s") % evt.EventData["longDoc"])
def onTitleChanged(self, evt):
if self and self.pgfEditor:
self.Caption = _("Dabo Editor: %s") % self.pgfEditor.Title
def _curr_editor_attval(self, att):
"""Returns the value of the specified attribute for self.CurrentEditor
if it is not None. Otherwise, it returns an empty string.
"""
if self.CurrentEditor is None:
return ""
return getattr(self.CurrentEditor, att)
def fillMenu(self):
app = self.Application
if not self.MenuBar:
mb = self.MenuBar = dBaseMenuBar()
else:
mb = self.MenuBar
fileMenu = mb.getMenu("base_file")
editMenu = mb.getMenu("base_edit")
mb.remove(mb.getMenuIndex("base_view"))
runMenu = dMenu(Caption=_("&Run"), MenuID="base_run")
mb.insertMenu(3, runMenu)
fileMenu.prependSeparator()
itm = fileMenu.prepend(
_("Reload from Disk"),
OnHit=self.onFileReload,
ItemID="file_reload",
help=_("Refresh the editor with the current version of the file on disk"),
)
itm.DynamicEnabled = self.hasFile
fileMenu.prependSeparator()
fileMenu.prepend(
_("Save &As"),
HotKey="Ctrl+Shift+S",
OnHit=self.onFileSaveAs,
bmp="saveAs",
ItemID="file_saveas",
help=_("Save under a different file name"),
)
fileMenu.prepend(
_("&Save"),
HotKey="Ctrl+S",
OnHit=self.onFileSave,
ItemID="file_save",
DynamicEnabled=lambda: self._curr_editor_attval("Modified"),
bmp="save",
help=_("Save file"),
)
clsItem = fileMenu.getItem("file_close")
if clsItem is not None:
fileMenu.remove(clsItem)
fileMenu.prepend(
_("&Close Editor"),
HotKey="Ctrl+W",
OnHit=self.onFileClose,
bmp="close",
ItemID="file_close_editor",
help=_("Close file"),
)
recentMenu = dMenu(Caption=_("Open Recent"), MenuID="file_open_recent", MRU=True)
fileMenu.prependMenu(recentMenu)
fileMenu.prepend(
_("&Open"),
HotKey="Ctrl+O",
OnHit=self.onFileOpen,
bmp="open",
ItemID="file_open",
help=_("Open file"),
)
fileMenu.prepend(
_("&New"),
HotKey="Ctrl+N",
OnHit=self.onFileNew,
bmp="new",
ItemID="file_new",
help=_("New file"),
)
editMenu.appendSeparator()
editMenu.append(
_("&Jump to line..."),
HotKey="Ctrl+J",
OnHit=self.onEditJumpToLine,
bmp="",
ItemID="edit_jump",
help=_("Jump to line"),
)
editMenu.appendSeparator()
editMenu.append(
_("Co&mment Line"),
HotKey="Ctrl+M",
OnHit=self.onCommentLine,
bmp="",
ItemID="edit_comment",
help=_("Comment out selection"),
)
editMenu.append(
_("&Uncomment Line"),
HotKey="Ctrl+Shift+M",
OnHit=self.onUncommentLine,
bmp="",
ItemID="edit_uncomment",
help=_("Uncomme&nt selection"),
)
editMenu.append(
_("&AutoComplete"),
HotKey="F5",
OnHit=self.onAutoComplete,
bmp="",
ItemID="edit_autocomplete",
help=_("Auto-complete the current text"),
)
editMenu.append(
_("AutoComplete Length"),
OnHit=self.onSetAutoCompleteLength,
bmp="",
ItemID="edit_autocompletelength",
help=_("Set the length to trigger the AutoCompletion popup"),
)
self._autoAutoItem = editMenu.append(
_("Automa&tic AutoComplete"),
OnHit=self.onAutoAutoComp,
bmp="",
help=_("Toggle Automatic Autocomplete"),
ItemID="edit_autoautocomplete",
menutype="check",
)
editMenu.appendSeparator()
moveMenu = dMenu(Caption=_("Move..."), MenuID="edit_move")
editMenu.appendMenu(moveMenu)
moveMenu.append(
_("Previous Page"),
HotKey="Alt+Left",
OnHit=self.onPrevPage,
DynamicEnabled=lambda: self.pgfEditor.PageCount > 1,
bmp="",
ItemID="move_prev",
help=_("Switch to the tab to the left"),
)
moveMenu.append(
_("Next Page"),
HotKey="Alt+Right",
OnHit=self.onNextPage,
DynamicEnabled=lambda: self.pgfEditor.PageCount > 1,
bmp="",
ItemID="move_next",
help=_("Switch to the tab to the right"),
)
moveMenu.append(
_("Move Page Left"),
HotKey="Alt+Shift+Left",
OnHit=self.onMovePageLeft,
DynamicEnabled=lambda: self.pgfEditor.PageCount > 1,
bmp="",
ItemID="move_pageleft",
help=_("Move this editor tab to the left"),
)
moveMenu.append(
_("Move Page Right"),
HotKey="Alt+Shift+Right",
OnHit=self.onMovePageRight,
DynamicEnabled=lambda: self.pgfEditor.PageCount > 1,
bmp="",
ItemID="move_pageright",
help=_("Move this editor tab to the right"),
)
moveMenu.append(
_("Next Block"),
HotKey="Ctrl+Shift+K",
OnHit=self.onMoveUpBlock,
DynamicEnabled=lambda: self._curr_editor_attval("Language") == "python",
bmp="",
ItemID="move_nextblock",
help=_("Move to the next 'def' or 'class' statement"),
)
moveMenu.append(
_("Previous Block"),
HotKey="Ctrl+Shift+D",
OnHit=self.onMoveDownBlock,
DynamicEnabled=lambda: self._curr_editor_attval("Language") == "python",
bmp="",
ItemID="move_prevblock",
help=_("Move to the previous 'def' or 'class' statement"),
)
editMenu.appendSeparator()
self._wrapItem = editMenu.append(
_("&Word Wrap"),
HotKey="Ctrl+Shift+W",
OnHit=self.onWordWrap,
bmp="",
ItemID="edit_wordwrap",
help=_("Toggle WordWrap"),
menutype="check",
)
self._synColorItem = editMenu.append(
_("S&yntax Coloring"),
HotKey="Ctrl+Shift+Y",
OnHit=self.onSyntaxColoring,
bmp="",
ItemID="edit_syntaxcolor",
help=_("Toggle Syntax Coloring"),
menutype="check",
)
self._useTabsItem = editMenu.append(
_("&Tabs"),
HotKey="Ctrl+Shift+T",
OnHit=self.onUseTabs,
bmp="",
ItemID="edit_usetabs",
help=_("Toggle Tabs"),
menutype="check",
)
self._lineNumItem = editMenu.append(
_("Show &Line Numbers"),
HotKey="Ctrl+Shift+L",
OnHit=self.onLineNumber,
bmp="",
ItemID="edit_linenum",
help=_("Toggle Line Numbers"),
menutype="check",
)
self._whiteSpaceItem = editMenu.append(
_("Show WhiteSpace"),
HotKey="Ctrl+Shift+E",
OnHit=self.onWhiteSpace,
bmp="",
ItemID="edit_whiteSpace",
help=_("Toggle WhiteSpace Visibility"),
menutype="check",
)
runMenu.append(
_("&Run Script"),
HotKey="Ctrl+Shift+R",
OnHit=self.onRunScript,
bmp="",
ItemID="run_script",
help=_("Run Script"),
)
self._showOutItem = runMenu.append(
_("Hide/Show Output"),
HotKey="Ctrl+Shift+O",
OnHit=self.onOutput,
bmp="",
ItemID="run_output",
help=_("Toggle the visibility of the Output pane"),
menutype="check",
)
runMenu.append(
_("Clear Output"),
OnHit=self.onClearOutput,
bmp="",
ItemID="run_clear",
help=_("Clear the contents of the Output pane"),
)
fontMenu = dMenu(Caption=_("Fo&nt"), MenuID="base_font")
mb.insertMenu(4, fontMenu)
fontMenu.append(
_("Set Font Size"),
OnHit=self.onFontSize,
ItemID="font_setsize",
help=_("Set Default Font Size"),
)
fontMenu.appendSeparator()
fontMenu.append(
_("Zoom &In"),
HotKey="Ctrl++",
OnHit=self.onViewZoomIn,
bmp="zoomIn",
ItemID="font_zoomin",
help=_("Zoom In"),
)
fontMenu.append(
_("&Normal Zoom"),
HotKey="Ctrl+/",
OnHit=self.onViewZoomNormal,
bmp="zoomNormal",
ItemID="font_zoomnormal",
help=_("Normal Zoom"),
)
fontMenu.append(
_("Zoom &Out"),
HotKey="Ctrl+-",
OnHit=self.onViewZoomOut,
bmp="zoomOut",
ItemID="font_zoomout",
help=_("Zoom Out"),
)
fixed_width_fonts = ui.getAvailableFonts(fixed_width_only=True)
all_fonts = ui.getAvailableFonts(fixed_width_only=False)
fontMenu.appendSeparator()
fontMenu.append(_("Fixed Width Fonts"), Enabled=False)
for font in fixed_width_fonts:
fontMenu.append(
font,
OnHit=self.onFontSelection,
ItemID="font_%s" % font.replace(" ", "_"),
menutype="Radio",
)
fontMenu.appendSeparator()
fontMenu.append(_("All Fonts"), Enabled=False)
for font in all_fonts:
fontMenu.append(
font,
OnHit=self.onFontSelection,
ItemID="font_%s" % font.replace(" ", "_"),
menutype="Radio",
)
vp = mb.getMenuIndex("base_font")
editorMenu = mb.insert(vp + 1, _("E&ditors"), MenuID="base_editors")
editorMenu.bindEvent(events.MenuHighlight, self.onMenuOpen)
# On non-Mac platforms, we may need to move the Help Menu
# to the end.
if app.Platform != "Mac":
hlp = mb.getMenu("base_help")
if hlp:
mb.remove(hlp, False)
mb.appendMenu(hlp)
def hasFile(self, evt=None):
"""Dynamic method for the Reload From Disk menu."""
# If there's a file, enable the menu
return self._curr_editor_attval("_fileName")
def onFileReload(self, evt):
"""Reload the file from disk."""
ed = self.CurrentEditor
fname = ed._fileName
ed.openFile(fname)
def onFontSelection(self, evt):
"""The user selected a font face for the editor."""
face = evt.EventObject.Caption
if self.CurrentEditor:
self.CurrentEditor.changeFontFace(face)
def onFontSize(self, evt):
"""Change the default font size for the editor."""
if not self.CurrentEditor:
return
val = ui.getInt(_("Select new font size"), _("Font Size"), self.CurrentEditor._fontSize)
if val is not None:
self.CurrentEditor.changeFontSize(val)
def onMenuOpen(self, evt):
"""Currently this never fires under Windows."""
mn = evt.EventObject
prm = mn.Caption
if prm.replace("&", "") == _("Editors"):
mn.clear()
for pg in self.pgfEditor.Pages:
prmpt = pg.editor._title
mn.append(prmpt, OnHit=self.onEditorSelected, help=_("Select %s") % prmpt)
if len(self.pgfEditor.Pages) > 1:
mn.appendSeparator()
mn.append(
_("Open in New Window"),
OnHit=self.onOpenInNew,
help=_("Open this document in a new window"),
)
elif prm == _("Font"):
mn.setCheck(self.CurrentEditor._fontFace)
def onOpenInNew(self, evt):
"""Open the current doc in a separate Editor window."""
# Get the current state of the doc
ed = self.CurrentEditor
txt = ed.Text
fname = ed.FilePath
# Close the editor
self.pgfEditor.closeEditor(ed, False)
# Create a new editor form
frm = EditorForm()
frm.onFileNew(None)
frm.openFile(fname)
newEd = frm.CurrentEditor
if newEd.Text != txt:
newEd.Text = txt
frm.show()
frm.Position = self.Left + 20, self.Top + 20
def onEditorSelected(self, evt):
"""Called when a menuitem in the Editors menu is chosen."""
cap = evt.EventObject.Caption
self.pgfEditor.selectByCaption(cap)
def onFileNew(self, evt):
target = self.pgfEditor.newEditor()
target.setFocus()
def onFileOpen(self, evt):
fileNames = self.CurrentEditor.promptForFileName(
prompt=_("Open"), path=self._lastPath, multiple=True
)
if fileNames is None:
# They bailed
return
for fileName in fileNames:
self._lastPath = os.path.split(fileName)[0]
self.Application.setUserSetting("lastPath", self._lastPath)
self.openFile(fileName)
@classmethod
def onMRUSelection(cls, evt):
"""This needs to be a classmethod, since the form
that originally opens a file path might get closed, and
if we bound the MRU action to an instance method, it
would barf. So we make this a classmethod, and pass
the call to the first EditorForm instance we can find.
"""
# The prompt will have a number prepended to the actual path,
# separated by a space.
pth = evt.prompt.split(" ", 1)[-1]
# Find the topmost form that is an EditorForm
app = dabo.dAppRef
try:
app.ActiveForm.openFile(pth)
except:
# Call the first available EditorForm
edf = [frm for frm in app.uiForms if isinstance(frm, EditorForm)][0]
edf.openFile(pth)
def openFile(self, pth, justReportErrors=False):
"""Open the selected file, if it isn't already open. If it is,
bring its Editor to the front. If the specified file is not
able to be opened and justReportErrors is True, a message is
output to the error log; otherwise, and error is raised.
"""
try:
target = self.pgfEditor.editFile(pth, True)
except Exception as e:
if justReportErrors:
dabo.log.error(_("Could not open file: %s") % e)
target = None
else:
raise
if target:
# Add to the MRU list
self.Application.addToMRU(_("Open Recent"), pth, self.onMRUSelection)
self.updateLex()
return target
def onFileSave(self, evt):
self.CurrentEditor.saveFile()
def onFileClose(self, evt):
self.pgfEditor.closeEditor()
if self.pgfEditor.PageCount == 0:
self.release()
evt.stop()
def onFileSaveAs(self, evt):
fname = self.CurrentEditor.promptForSaveAs()
if fname:
self.CurrentEditor.saveFile(fname, force=True)