-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmainframe.py
1333 lines (1139 loc) · 50.5 KB
/
mainframe.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
import sys, os, string, traceback, errno, shutil, subprocess, webbrowser
import wx
import aui
import app_info, async, fileutil, ID
from about_dialog import AboutDialog
from async import async_call, coroutine, queued_coroutine, managed, CoroutineManager, CoroutineQueue
from commands_dialog import CommandsDialog, save_options
from dialogs import dialogs
from dirtree import DirNode
from dirtree_filter import DirTreeFilter
from edit_project_dialog import EditProjectDialog
from editor import Editor
from editor_dirtree import EditorDirTreeCtrl
from file_monitor import FileMonitor
from find_replace_dialog import FindReplaceDetails
from lru import LruQueue
from menu import MenuItem
from menu_defs import menubar
from new_project_dialog import NewProjectDialog
from preview import Preview, is_preview_available
from resources import load_icon_bundle
from search_ctrl import SearchCtrl
from search_dialog import SearchDetails, SearchDialog
from settings import read_settings, write_settings
from shell import run_shell_command
from styled_text_ctrl import StyledTextCtrl, MARKER_FIND, MARKER_ERROR
from terminal_ctrl import TerminalCtrl
from util import frozen_window, is_text_file, new_id_range, shorten_path
from view_settings_dialog import ViewSettingsDialog, get_font_from_settings
def make_project_filename(project_root):
return os.path.join(project_root, ".devo-project")
def make_session_filename(project_root):
return os.path.join(project_root, ".devo-session")
class AppEnv(object):
def __init__(self, mainframe):
self._mainframe = mainframe
def new_editor(self, path=""):
return self._mainframe.NewEditor(path=path)
def open_file(self, path, line=None, marker_type=None):
return self._mainframe.OpenEditor(path, line, marker_type)
def open_text(self, text):
return self._mainframe.OpenEditorWithText(text)
def open_preview(self, path):
self._mainframe.OpenPreview(path)
def open_web_view(self, url):
self._mainframe.NewPreview(url=url)
def open_static_text(self, title, text):
return self._mainframe.OpenStaticEditor(title, text)
def show_terminal(self):
self._mainframe.ShowPane(self._mainframe.terminal)
def add_recent_file(self, path):
self._mainframe.AddRecentFile(path)
def clear_highlight(self, marker_type):
self._mainframe.ClearHighlight(marker_type)
def set_highlighted_file(self, path, line, marker_type):
self._mainframe.SetHighlightedFile(path, line, marker_type)
def get_file_to_save(self, path=""):
if not path:
path = self._mainframe.project_root
if path:
return dialogs.get_file_to_save(self._mainframe, path=path)
else:
return dialogs.get_file_to_save(self._mainframe, context="open")
def search(self, **kwargs):
self._mainframe.Search(**kwargs)
def add_monitor_path(self, path):
self._mainframe.fmon.add_path(path)
def remove_monitor_path(self, path):
self._mainframe.fmon.remove_path(path)
def stopped_file_monitor(self):
return self._mainframe.fmon.stopped_context()
def updating_path(self, path):
return self._mainframe.fmon.updating_path(path)
def close_view(self, view):
self._mainframe.ClosePage(view)
def shell_open(self, path):
self._mainframe.tree.shell_open(path)
@property
def find_details(self):
return self._mainframe.find_details
@find_details.setter
def find_details(self, find_details):
self._mainframe.find_details = find_details
@property
def project_root(self):
return self._mainframe.project_root
@property
def editor_font(self):
return self._mainframe.editor_font
class NewEditorWriter(object):
def __init__(self, env):
self.env = env
def write(self, s):
self.env.open_text(s)
MAX_RECENT_FILES = 20
DEFAULT_WIDTH = 1200
AUI_MANAGER_STYLE = aui.AUI_MGR_TRANSPARENT_HINT \
| aui.AUI_MGR_HINT_FADE \
| aui.AUI_MGR_NO_VENETIAN_BLINDS_FADE \
| (aui.AUI_MGR_LIVE_RESIZE if wx.Platform == "__WXMSW__" else 0)
AUI_NOTEBOOK_STYLE = aui.AUI_NB_TOP \
| aui.AUI_NB_CLOSE_ON_ALL_TABS \
| aui.AUI_NB_TAB_FIXED_WIDTH \
| aui.AUI_NB_TAB_SPLIT \
| aui.AUI_NB_TAB_MOVE \
| aui.AUI_NB_SCROLL_BUTTONS \
| aui.AUI_NB_WINDOWLIST_BUTTON \
| aui.AUI_NB_MIDDLE_CLICK_CLOSE
class MainFrame(wx.Frame, wx.FileDropTarget):
def __init__(self, args):
wx.Frame.__init__(self, None, title="Devo")
wx.FileDropTarget.__init__(self)
self.SetDropTarget(self)
self.SetMenuBar(menubar.Create())
self.CreateStatusBar(3)
self.SetStatusWidths([200, -1, 160])
if wx.Platform != "__WXMAC__":
self.SetIcons(load_icon_bundle(
"icons/devo-icon-%s.png" % size for size in (16, 24, 32, 48, 64, 128, 256)))
self.recent_file_first_id, self.recent_file_last_id = new_id_range(MAX_RECENT_FILES)
self.global_command_first_id, self.global_command_last_id = new_id_range(100)
self.project_command_first_id, self.project_command_last_id = new_id_range(100)
self.project_first_id, self.project_last_id = new_id_range(100)
self.config_dir = fileutil.get_user_config_dir("devo")
self.settings_filename = os.path.join(self.config_dir, "devo.conf")
self.project_filename = ""
self.session_filename = ""
self.save_settings = not args.new_instance
self.settings = {}
self.project = {}
self.project_root = ""
self.project_info = {}
self.recent_files = LruQueue(maxlen=MAX_RECENT_FILES)
self.cm = CoroutineManager()
self.cq = CoroutineQueue()
self.env = AppEnv(self)
self.fmon = FileMonitor(self.OnFilesChanged, self)
self.updated_paths = set()
self.deleted_paths = set()
self.reloading = False
self.find_details = FindReplaceDetails()
self.search_details = SearchDetails()
self.editor_focus = None
self.editor_highlight = [None, None]
self.editor_font = get_font_from_settings({})
self.closing = False
self.closed = False
self.manager = aui.AuiManager(self, agwFlags=AUI_MANAGER_STYLE)
self.notebook = aui.AuiNotebook(self, agwStyle=AUI_NOTEBOOK_STYLE)
self.filter = DirTreeFilter()
self.tree = EditorDirTreeCtrl(self, self.env, filter=self.filter)
self.terminal = TerminalCtrl(self, self.env)
self.search = SearchCtrl(self, self.env)
self.manager.AddPane(self.tree,
aui.AuiPaneInfo().Left().BestSize((220, -1)).CaptionVisible(False))
self.manager.AddPane(self.notebook,
aui.AuiPaneInfo().CentrePane())
self.manager.AddPane(self.terminal,
aui.AuiPaneInfo().Hide().Bottom().BestSize((-1, 180)).Caption("Terminal"))
self.manager.AddPane(self.search,
aui.AuiPaneInfo().Hide().Top().BestSize((-1, 250)).Caption("Search"))
self.manager.Update()
self.Bind(wx.EVT_CLOSE, self.OnClose)
self.Bind(wx.EVT_ACTIVATE, self.OnActivate)
self.Bind(wx.EVT_CHILD_FOCUS, self.OnChildFocus)
self.Bind(aui.EVT_AUI_PANE_CLOSE, self.OnPaneClose)
self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CLOSE, self.OnPageClose)
self.Bind(aui.EVT_AUINOTEBOOK_PAGE_CHANGED, self.OnPageChanged)
self.Bind(aui.EVT_AUINOTEBOOK_BG_DCLICK, self.OnTabAreaDClick)
self.Bind(wx.EVT_MENU, self.OnNewFile, id=ID.NEW)
self.Bind(wx.EVT_MENU, self.OnOpenFile, id=ID.OPEN)
self.Bind(wx.EVT_MENU, self.OnCloseFile, id=ID.CLOSE)
self.Bind(wx.EVT_MENU, self.OnClose, id=ID.EXIT)
self.Bind(wx.EVT_MENU, self.OnSearch, id=ID.SEARCH)
self.Bind(wx.EVT_MENU_RANGE, self.OnRecentFile,
id=self.recent_file_first_id, id2=self.recent_file_last_id)
self.BindEditorAction(ID.SAVE, "Save", "GetModify")
self.BindEditorAction(ID.SAVEAS, "SaveAs")
self.BindEditorAction(ID.UNDO, "Undo", "CanUndo")
self.BindEditorAction(ID.REDO, "Redo", "CanRedo")
self.BindEditorAction(ID.CUT, "Cut", "CanCut")
self.BindEditorAction(ID.COPY, "Copy", "CanCopy")
self.BindEditorAction(ID.PASTE, "Paste", "CanPaste")
self.BindEditorAction(ID.SELECTALL, "SelectAll")
self.BindEditorAction(ID.FIND, "Find")
self.BindEditorAction(ID.FIND_NEXT, "FindNext", "CanFindNext")
self.BindEditorAction(ID.FIND_PREV, "FindPrev", "CanFindPrev")
self.BindEditorAction(ID.GO_TO_LINE, "GoToLine")
self.BindEditorAction(ID.INDENT, "Indent")
self.BindEditorAction(ID.UNINDENT, "Unindent")
self.BindEditorAction(ID.COMMENT, "Comment")
self.BindEditorAction(ID.UNCOMMENT, "Uncomment")
self.BindEditorAction(ID.JOIN_LINES, "JoinLines", "HasSelection")
self.BindEditorAction(ID.SPLIT_LINES, "SplitLines", "HasSelection")
self.BindEditorAction(ID.SORT_LINES, "SortLines", "HasSelection")
self.BindEditorAction(ID.SORT_LINES_CASE_INSENSITIVE, "SortLinesCaseInsensitive", "HasSelection")
self.BindEditorAction(ID.SORT_LINES_NATURAL_ORDER, "SortLinesNaturalOrder", "HasSelection")
self.BindEditorAction(ID.UNIQUE_LINES, "UniqueLines", "HasSelection")
self.BindEditorAction(ID.REVERSE_LINES, "ReverseLines", "HasSelection")
self.BindEditorAction(ID.SHUFFLE_LINES, "ShuffleLines", "HasSelection")
self.BindEditorAction(ID.TABS_TO_SPACES, "TabsToSpaces", "HasSelection")
self.BindEditorAction(ID.REMOVE_TRAILING_SPACE, "RemoveTrailingSpace", "HasSelection")
self.BindEditorAction(ID.REMOVE_LEADING_SPACE, "RemoveLeadingSpace", "HasSelection")
self.BindEditorAction(ID.ALIGN_COLUMNS, "AlignColumns", "HasSelection")
self.BindEditorAction(ID.REMOVE_EXTRA_SPACE, "RemoveExtraSpace", "HasSelection")
self.BindEditorAction(ID.LOWER_CASE, "LowerCase", "HasSelection")
self.BindEditorAction(ID.UPPER_CASE, "UpperCase", "HasSelection")
self.BindEditorAction(ID.TITLE_CASE, "TitleCase", "HasSelection")
self.BindEditorAction(ID.SWAP_CASE, "SwapCase", "HasSelection")
self.BindEditorAction(ID.COPY_FILE_PATH, "CopyFilePath", "HasOpenFile")
self.BindEditorAction(ID.OPEN_CONTAINING_FOLDER, "OpenContainingFolder", "HasOpenFile")
self.BindEditorAction(ID.OPEN_IN_WEB_VIEW, "OpenPreview", "HasOpenFile")
self.BindEditorAction(ID.WEB_SEARCH, "WebSearch", "HasSelection")
self.Bind(wx.EVT_MENU, self.OnNewProject, id=ID.NEW_PROJECT)
self.Bind(wx.EVT_MENU, self.OnOpenProject, id=ID.OPEN_PROJECT)
self.Bind(wx.EVT_MENU, self.OnCloseProject, id=ID.CLOSE_PROJECT)
self.Bind(wx.EVT_MENU, self.OnEditProject, id=ID.EDIT_PROJECT)
self.Bind(wx.EVT_MENU, self.OnConfigureGlobalCommands, id=ID.CONFIGURE_GLOBAL_COMMANDS)
self.Bind(wx.EVT_MENU, self.OnConfigureProjectCommands, id=ID.CONFIGURE_PROJECT_COMMANDS)
self.Bind(wx.EVT_UPDATE_UI, self.OnUpdate_ConfigureProjectCommands, id=ID.CONFIGURE_PROJECT_COMMANDS)
self.Bind(wx.EVT_MENU_RANGE, self.OnSelectProject,
id=self.project_first_id, id2=self.project_last_id)
self.Bind(wx.EVT_MENU_RANGE, self.OnGlobalCommand,
id=self.global_command_first_id, id2=self.global_command_last_id)
self.Bind(wx.EVT_MENU_RANGE, self.OnProjectCommand,
id=self.project_command_first_id, id2=self.project_command_last_id)
self.Bind(wx.EVT_UPDATE_UI_RANGE, self.OnUpdateUI_GlobalCommand,
id=self.global_command_first_id, id2=self.global_command_last_id)
self.Bind(wx.EVT_UPDATE_UI_RANGE, self.OnUpdateUI_ProjectCommand,
id=self.project_command_first_id, id2=self.project_command_last_id)
self.Bind(wx.EVT_MENU, self.OnNewWindow, id=ID.NEW_WINDOW)
self.Bind(wx.EVT_MENU, self.OnFullScreen, id=ID.FULL_SCREEN)
self.Bind(wx.EVT_MENU, self.OnShowPaneFileBrowser, id=ID.SHOW_PANE_FILE_BROWSER)
self.Bind(wx.EVT_MENU, self.OnShowPaneTerminal, id=ID.SHOW_PANE_TERMINAL)
self.Bind(wx.EVT_MENU, self.OnShowPaneSearch, id=ID.SHOW_PANE_SEARCH)
self.Bind(wx.EVT_MENU, self.OnViewSettings, id=ID.VIEW_SETTINGS)
self.Bind(wx.EVT_MENU, self.OnReportBug, id=ID.REPORT_BUG)
self.Bind(wx.EVT_MENU, self.OnGetLatestVersion, id=ID.GET_LATEST_VERSION)
self.Bind(wx.EVT_MENU, self.OnAboutBox, id=ID.ABOUT)
self.Bind(wx.EVT_UPDATE_UI, self.UpdateUI_HasEditorTab, id=ID.CLOSE)
self.Bind(wx.EVT_UPDATE_UI, self.UpdateUI_ProjectIsOpen, id=ID.CLOSE_PROJECT)
self.Bind(wx.EVT_UPDATE_UI, self.UpdateUI_ProjectIsOpen, id=ID.EDIT_PROJECT)
self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI_FullScreen, id=ID.FULL_SCREEN)
self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI_ShowPaneFileBrowser, id=ID.SHOW_PANE_FILE_BROWSER)
self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI_ShowPaneTerminal, id=ID.SHOW_PANE_TERMINAL)
self.Bind(wx.EVT_UPDATE_UI, self.OnUpdateUI_ShowPaneSearch, id=ID.SHOW_PANE_SEARCH)
self.Startup(args)
@property
def views(self):
for i in xrange(self.notebook.GetPageCount()):
yield self.notebook.GetPage(i)
@property
def editors(self):
for x in self.views:
if isinstance(x, Editor):
yield x
@property
def previews(self):
for x in self.views:
if isinstance(x, Preview):
yield x
@property
def projects_sorted(self):
return sorted(self.project_info.iteritems(), key=lambda x: x[1]["name"].lower())
def GetMenuHooks(self):
global_commands = self.settings.get("commands", [])
project_commands = self.project.get("commands", [])
return {
"global_commands" : [
MenuItem(i + self.global_command_first_id, command["name"], command["accel"])
for i, command in enumerate(global_commands)
],
"project_commands" : [
MenuItem(i + self.project_command_first_id, command["name"], command["accel"])
for i, command in enumerate(project_commands)
],
"projects" : [
MenuItem(i + self.project_first_id, p["name"])
for i, (_, p) in enumerate(self.projects_sorted)
],
"recent_files" : [
MenuItem(i + self.recent_file_first_id, shorten_path(path))
for i, path in enumerate(self.recent_files)
]
}
def UpdateAcceleratorTable(self):
accel_table = wx.AcceleratorTable(menubar.GetAccelerators(self.GetMenuHooks()))
self.SetAcceleratorTable(accel_table)
def UpdateMenuBar(self):
self.UpdateAcceleratorTable()
with frozen_window(self):
old_menubar = self.GetMenuBar()
new_menubar = menubar.Create(self.GetMenuHooks())
self.SetMenuBar(new_menubar)
if old_menubar:
old_menubar.Destroy()
def OnClose(self, evt):
if not self.closed:
if hasattr(evt, "Veto"):
evt.Veto()
if not self.closing:
self.DoClose()
@managed("cm")
@coroutine
def DoClose(self):
self.closing = True
try:
if (yield self.SaveProject()):
self.fmon.stop()
if (yield self.SaveSettings()):
self.Hide()
self.closed = True
wx.CallAfter(self._DoShutdown)
return
self.Show()
self.fmon.start(update_paths=False)
finally:
self.closing = False
def _DoShutdown(self):
self.fmon.stop()
async.shutdown_scheduler()
self.tree.Destroy()
self.search.Destroy()
self.Destroy()
def MoveWindowToLeft(self, width=DEFAULT_WIDTH):
display_rect = wx.Display(wx.Display.GetFromWindow(self)).GetClientArea()
width = min(display_rect.width, width)
self.SetRect(wx.Rect(0, 0, width, display_rect.height))
def MoveWindowToRight(self, width=DEFAULT_WIDTH):
display_rect = wx.Display(wx.Display.GetFromWindow(self)).GetClientArea()
width = min(display_rect.width, width)
self.SetRect(wx.Rect(display_rect.width - width, display_rect.y, width, display_rect.height))
@managed("cm")
@queued_coroutine("cq")
def Startup(self, args):
try:
self.settings = (yield async_call(read_settings, self.settings_filename))
except Exception:
self.settings = {}
try:
backup_filename = self.settings_filename + ".bak"
if os.path.exists(self.settings_filename) and not os.path.exists(backup_filename):
shutil.copy2(self.settings_filename, backup_filename)
except OSError:
pass
try:
width = self.settings["window_rect"][2]
except Exception:
width = DEFAULT_WIDTH
window_start_mode = self.settings.get("window_start_mode", "previous")
if window_start_mode == "previous":
if "window_rect" in self.settings:
try:
self.SetRect(wx.Rect(*self.settings["window_rect"]))
except Exception:
self.MoveWindowToRight()
else:
self.MoveWindowToRight()
elif window_start_mode == "left":
self.MoveWindowToLeft(self.settings.get("window_start_width", width))
else:
self.MoveWindowToRight(self.settings.get("window_start_width", width))
self.editor_font = get_font_from_settings(self.settings)
self.recent_files = LruQueue(self.settings.get("recent_files", []), MAX_RECENT_FILES)
for project_path in self.settings.get("projects", ()):
try:
project = (yield async_call(read_settings, make_project_filename(project_path)))
project.setdefault("name", os.path.basename(project_path))
self.project_info[project_path] = project
except Exception:
pass
if "dialogs" in self.settings:
dialogs.load_state(self.settings["dialogs"])
if "find_details" in self.settings:
self.find_details.LoadPerspective(self.settings["find_details"])
if "search_details" in self.settings:
self.search_details.LoadPerspective(self.settings["search_details"])
success = True
if args.project:
success = (yield self.OpenProject(args.project))
else:
last_project = self.settings.get("last_project")
if last_project:
success = (yield self.OpenProject(last_project))
else:
yield self.OpenDefaultProject()
if not success:
yield self.OpenDefaultProject()
for filename in args.filenames:
self.OpenEditor(filename)
if window_start_mode == "previous":
window_state = self.settings.get("window_state", "normal")
if window_state == "fullscreen":
wx.CallAfter(self.OnFullScreen, None)
elif window_state == "maximized":
wx.CallAfter(self.Maximize)
yield self.SaveSettings()
@managed("cm")
@coroutine
def SaveSettings(self):
if not self.save_settings:
yield True
try:
self.settings["projects"] = sorted(self.project_info)
self.settings["last_project"] = self.project_root
self.settings["recent_files"] = list(self.recent_files)
self.settings["dialogs"] = dialogs.save_state()
self.settings["find_details"] = self.find_details.SavePerspective()
self.settings["search_details"] = self.search_details.SavePerspective()
self.settings["window_rect"] = self.Rect.Get()
self.settings["window_state"] = "fullscreen" if self.IsFullScreen() else "maximized" if self.IsMaximized() else "normal"
yield async_call(write_settings, self.settings_filename, self.settings)
yield True
except Exception as e:
dialogs.error(self, "Error saving settings:\n\n%s" % e)
yield False
@managed("cm")
@coroutine
def SaveSession(self):
session = {}
session["dirtree"] = self.tree.SavePerspective()
if self.notebook.GetPageCount() > 0:
session["notebook"] = self.notebook.SavePerspective()
session["editors"] = views = []
session["selection"] = self.notebook.GetSelection()
for view in self.views:
if view.path and view.modified:
if not (yield view.TryClose()):
yield False
views.append(view.SavePerspective())
yield async_call(write_settings, self.session_filename, session)
yield True
@managed("cm")
@coroutine
def SaveProject(self):
self.fmon.stop()
try:
if self.session_filename:
try:
if not (yield self.SaveSession()):
yield False
except Exception as e:
dialogs.error(self, "Error saving session:\n\n%s" % e)
yield False
try:
if self.project_filename:
yield async_call(write_settings, self.project_filename, self.project)
except Exception as e:
dialogs.error(self, "Error saving project:\n\n%s" % e)
yield False
yield True
finally:
self.fmon.start(update_paths=False)
@managed("cm")
@coroutine
def LoadSession(self):
session = (yield async_call(read_settings, self.session_filename))
with frozen_window(self.notebook):
errors = []
try:
views = []
seen_paths = set()
for p in session.get("editors", ()):
view_type = p.get("view_type")
view_types = dict(editor=self.NewEditor, preview=self.NewPreview)
view = view_types.get(view_type, self.NewEditor)()
if "path" in p and view_type == "editor":
path = p["path"] = self.GetFullPath(p["path"])
if path in seen_paths:
views.append((view, None))
continue
seen_paths.add(path)
future = view.LoadPerspective(p)
views.append((view, future))
if "dirtree" in session:
self.tree.LoadPerspective(session["dirtree"])
to_remove = []
for i, (view, future) in reversed(list(enumerate(views))):
if future is None:
to_remove.append(i)
else:
try:
yield future
except Exception as e:
to_remove.append(i)
if not (isinstance(e, IOError) and e.errno == errno.ENOENT):
errors.append(e)
errors.reverse()
if "notebook" in session:
self.notebook.LoadPerspective(session["notebook"])
if "selection" in session:
selection = session["selection"]
if 0 <= selection < self.notebook.GetPageCount():
self.notebook.SetSelection(selection)
self.notebook.GetPage(selection).SetFocus()
# to_remove is already in reverse order
for i in to_remove:
self.notebook.DeletePage(i)
finally:
if errors:
self.Show()
dialogs.error(self, "Errors loading session:\n\n%s" %
("\n\n".join(str(e) for e in errors)))
def DeleteAllPages(self):
with frozen_window(self.notebook):
for i in xrange(self.notebook.GetPageCount()-1, -1, -1):
self.notebook.DeletePage(i)
def StartFileMonitor(self):
self.updated_paths.clear()
self.deleted_paths.clear()
self.fmon.start()
def UpdateTitle(self):
self.SetTitle("Devo [%s]" % self.project["name"] if self.project_filename else "Devo")
def SetProject(self, project, project_root):
project_root = os.path.realpath(project_root)
self.project = project
self.project_root = project_root
self.project_filename = make_project_filename(project_root)
self.session_filename = make_session_filename(project_root)
self.search_details.path = project_root
project.setdefault("name", os.path.basename(project_root))
self.project_info[project_root] = project
self.DeleteAllPages()
self.tree.SetTopLevel([DirNode(self.project_root)])
self.UpdateMenuBar()
self.UpdateTitle()
self.StartFileMonitor()
@managed("cm")
@coroutine
def OpenNewProject(self, project, project_root):
if not fileutil.can_use_directory(project_root):
dialogs.error(self, "Error: Insufficient permissions to use %s" % project_root)
else:
if (yield self.SaveProject()):
if os.path.exists(make_project_filename(project_root)):
yield self.OpenProject(project_root, update=project)
else:
self.SetProject(project, project_root)
yield self.SaveProject()
yield self.SaveSettings()
def _ShowLoadProjectError(self, exn, filename, ask_remove=True):
self.Show()
if isinstance(exn, IOError) and exn.errno == errno.ENOENT:
if ask_remove:
return dialogs.yes_no(self,
"Project file not found:\n\n%s\n\nDo you want to remove this project from the project list?" % filename)
else:
dialogs.error(self, "Project file not found:\n\n%s" % filename)
return False
else:
dialogs.error(self, "Error loading project:\n\n%s" % traceback.format_exc())
return False
@managed("cm")
@coroutine
def OpenProject(self, project_root, update={}):
project_root = os.path.realpath(project_root)
project_filename = make_project_filename(project_root)
if not fileutil.can_use_directory(project_root):
dialogs.error(self, "Error: Insufficient permissions to use %s" % project_root)
yield False
if not fileutil.can_use_file(project_filename):
dialogs.error(self, "Error: Insufficient permissions to use %s" % project_filename)
yield False
newly_added = project_root not in self.project_info
if (yield self.SaveProject()):
try:
project = (yield async_call(read_settings, project_filename))
project.update(update)
self.SetProject(project, project_root)
try:
yield self.LoadSession()
except IOError:
pass
if newly_added:
yield self.SaveSettings()
self.Show()
yield True
except Exception as e:
if project_root in self.project_info:
if self._ShowLoadProjectError(e, project_root):
del self.project_info[project_root]
yield self.SaveSettings()
self.UpdateMenuBar()
else:
self._ShowLoadProjectError(e, project_root, ask_remove=False)
yield False
finally:
self.StartFileMonitor()
@managed("cm")
@coroutine
def OpenDefaultProject(self):
if (yield self.SaveProject()):
self.project = {}
self.project_root = ""
self.project_filename = ""
self.session_filename = os.path.join(self.config_dir, "session")
self.DeleteAllPages()
self.tree.SetTopLevel()
try:
yield self.LoadSession()
except Exception:
pass
finally:
self.Show()
self.UpdateMenuBar()
self.UpdateTitle()
self.StartFileMonitor()
def OnPaneClose(self, evt):
window = evt.GetPane().window
if window is self.search:
self.search.stop()
self.ClearHighlight(MARKER_FIND)
elif window is self.terminal:
self.ClearHighlight(MARKER_ERROR)
def OnPageClose(self, evt):
evt.Veto()
editor = self.notebook.GetPage(evt.GetSelection())
self.ClosePage(editor)
def ForgetEditor(self, editor):
if editor is self.editor_focus:
self.editor_focus = None
for marker_type, editor_highlight in enumerate(self.editor_highlight):
if editor is editor_highlight:
self.editor_highlight[marker_type] = None
@managed("cm")
@coroutine
def ClosePage(self, editor):
if (yield editor.TryClose()):
try:
with frozen_window(self.notebook):
self.notebook.DeletePage(self.notebook.GetPageIndex(editor))
except Exception:
pass
else:
self.ForgetEditor(editor)
if self.notebook.GetPageCount() == 0:
self.SetStatusText("", 0)
self.SetStatusText("", 1)
self.SetStatusText("", 2)
def AddPage(self, win, index=None):
if index is None:
index = self.notebook.GetSelection() + 1
self.notebook.InsertPage(index, win, win.title, select=True)
win.sig_title_changed.bind(self.OnPageTitleChanged)
win.sig_status_changed.bind(self.OnPageStatusChanged)
win.SetFocus()
def OnPageChanged(self, evt):
editor = self.notebook.GetPage(evt.GetSelection())
editor.SetFocus()
self.SetStatusText(editor.status_text, 0)
self.SetStatusText(editor.status_text_path, 1)
self.SetStatusText(editor.status_text_syntax, 2)
def OnPageTitleChanged(self, win):
i = self.notebook.GetPageIndex(win)
if i != wx.NOT_FOUND:
self.notebook.SetPageText(i, win.title)
def OnPageStatusChanged(self, win):
if win is self.notebook.GetCurrentPage():
self.SetStatusText(win.status_text, 0)
self.SetStatusText(win.status_text_path, 1)
self.SetStatusText(win.status_text_syntax, 2)
def OnTabAreaDClick(self, evt):
self.NewEditor(index=self.notebook.GetPageCount())
def NewEditor(self, index=None, path=""):
if path:
editor = self.FindEditor(path)
if editor:
self.ActivateView(editor)
return editor
with frozen_window(self.notebook):
editor = Editor(self.notebook, self.env, path=path)
self.AddPage(editor, index=index)
return editor
def NewPreview(self, index=None, url="", show_browser_ui=True):
with frozen_window(self.notebook):
preview = Preview(self.notebook, self.env, url=url, show_browser_ui=show_browser_ui)
self.AddPage(preview, index=index)
return preview
if sys.platform == "win32":
def _FindPath(self, path, views):
for view in views:
if view.path.lower() == path.lower():
return view
else:
def _FindPath(self, path, views):
for view in views:
if view.path == path:
return view
def FindEditor(self, path):
return self._FindPath(path, self.editors)
def FindPreview(self, path):
return self._FindPath(path, self.previews)
def GetCurrentEditorTab(self):
sel = self.notebook.GetSelection()
if sel != wx.NOT_FOUND:
return self.notebook.GetPage(sel)
def GetFullPath(self, path):
return os.path.realpath(os.path.join(self.project_root, path))
def AddRecentFile(self, path):
self.recent_files.add(self.GetFullPath(path))
self.UpdateMenuBar()
def SetEditorLineAndMarker(self, editor, line, marker_type):
if line is not None:
editor.SetCurrentLine(line - 1)
if marker_type is not None:
self.SetHighlightedEditor(editor, line, marker_type)
def ActivateView(self, view):
i = self.notebook.GetPageIndex(view)
if i != wx.NOT_FOUND:
self.notebook.SetSelection(i)
view.SetFocus()
def OpenPreview(self, path):
try:
import wx.html2
except Exception as e:
dialogs.error(self, "Web View is not available:\n\n%s" % e)
else:
path = self.GetFullPath(path)
preview = self.FindPreview(path)
if preview:
self.ActivateView(preview)
else:
self.NewPreview(url="file://" + path)
@managed("cm")
@queued_coroutine("cq")
def OpenEditor(self, path, line=None, marker_type=None):
path = self.GetFullPath(path)
editor = self.FindEditor(path)
if editor:
self.SetEditorLineAndMarker(editor, line, marker_type)
self.ActivateView(editor)
yield True
try:
if not os.path.exists(path):
dialogs.error(self, "File does not exist:\n\n%s" % path)
yield False
if not (yield async_call(is_text_file, path)):
if not dialogs.ask_open_binary(self, path):
yield False
except EnvironmentError:
yield False
editor = Editor(self.notebook, self.env, path)
if not (yield editor.TryLoadFile(path)):
editor.Destroy()
yield False
with frozen_window(self.notebook):
self.AddPage(editor)
self.AddRecentFile(path)
self.SetEditorLineAndMarker(editor, line, marker_type)
editor.SetFocus()
yield True
def OpenEditorWithText(self, text):
editor = self.NewEditor()
editor.SetText(text)
return editor
def OpenStaticEditor(self, title, text):
editor = self.NewEditor()
editor.SetStatic(title, text)
def OnNewFile(self, evt):
self.NewEditor()
def OnOpenFile(self, evt):
dir_path = self.project_root
editor = self.GetCurrentEditorTab()
if editor:
dir_path = os.path.dirname(editor.path)
path = dialogs.get_file_to_open(self, path=dir_path, context="open")
if path:
self.OpenEditor(path)
def OnCloseFile(self, evt):
editor = self.GetCurrentEditorTab()
if editor:
self.ClosePage(editor)
@coroutine
def OnRecentFile(self, evt):
index = evt.GetId() - self.recent_file_first_id
if 0 <= index < len(self.recent_files):
path = self.recent_files.access(index)
if not (yield self.OpenEditor(path)):
self.recent_files.remove(0)
self.UpdateMenuBar()
def OnDropFiles(self, x, y, filenames):
for filename in filenames:
self.OpenEditor(filename)
return True
def GetNewProject(self, path=""):
dlg = NewProjectDialog(self, path=path)
try:
if dlg.ShowModal() == wx.ID_OK:
project_root = dlg.GetRoot()
project = {"name": dlg.GetName()}
return project, project_root
finally:
dlg.Destroy()
return None, None
def OnNewProject(self, evt):
project, project_root = self.GetNewProject()
if project:
self.OpenNewProject(project, project_root)
def OnOpenProject(self, evt):
project_root = dialogs.get_directory(self, "Select Project Directory")
if project_root:
if os.path.exists(make_project_filename(project_root)):
self.OpenProject(project_root)
else:
project, project_root = self.GetNewProject(project_root)
if project:
self.OpenNewProject(project, project_root)
def OnCloseProject(self, evt):
if self.project_filename:
self.OpenDefaultProject()
def OnEditProject(self, evt):
if self.project_filename:
dlg = EditProjectDialog(self, self.project)
try:
if dlg.ShowModal() == wx.ID_OK:
dlg.UpdateProject(self.project)
self.UpdateMenuBar()
self.UpdateTitle()
self.SaveProject()
finally:
dlg.Destroy()
def ShowPane(self, window, title=None):
pane = self.manager.GetPane(window)
if pane:
if title is not None:
pane.Caption(title)
if not pane.IsShown():
pane.Show()
self.manager.Update()
elif title is not None:
self.manager.Update()
def HidePane(self, window):
pane = self.manager.GetPane(window)
if pane and pane.IsShown():
pane.Hide()
self.manager.Update()
def GetCurrentSelection(self):
if self.editor_focus:
return self.editor_focus.GetSelectedText().strip().split("\n", 1)[0]
return ""
def ClearHighlight(self, marker_type):
if self.editor_highlight[marker_type]:
self.editor_highlight[marker_type].ClearHighlight(marker_type)
self.editor_highlight[marker_type] = None
self.search.ClearHighlight(marker_type)
self.terminal.ClearHighlight(marker_type)
def SetHighlightedEditor(self, editor, line, marker_type):
self.ClearHighlight(marker_type)
self.editor_highlight[marker_type] = editor
editor.SetHighlightedLine(line - 1, marker_type)
def SetHighlightedFile(self, path, line, marker_type):
editor = self.FindEditor(self.GetFullPath(path))
if editor:
self.SetHighlightedEditor(editor, line, marker_type)
def Search(self, find=None, path=None):
if find is not None:
self.search_details.find = find
else: