forked from debreate/debreate
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
1141 lines (830 loc) · 40.9 KB
/
main.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
# -*- coding: utf-8 -*-
## \package main
# MIT licensing
# See: docs/LICENSE.txt
import os, subprocess, webbrowser, wx
from urllib2 import HTTPError
from urllib2 import URLError
from command_line import parsed_args_s
from dbr.config import ConfCode
from dbr.config import GetDefaultConfigValue
from dbr.config import ReadConfig
from dbr.config import WriteConfig
from dbr.event import EVT_CHANGE_PAGE
from dbr.functions import GetCurrentVersion
from dbr.functions import UsingDevelopmentVersion
from dbr.help import HelpDialog
from dbr.icon import Icon
from dbr.language import GT
from dbr.log import DebugEnabled
from dbr.log import Logger
from globals import ident
from globals.application import APP_homepage
from globals.application import APP_project_gh
from globals.application import APP_project_sf
from globals.application import AUTHOR_email
from globals.application import AUTHOR_name
from globals.application import VERSION_string
from globals.application import VERSION_tuple
from globals.bitmaps import ICON_CLOCK
from globals.bitmaps import ICON_GLOBE
from globals.bitmaps import ICON_LOGO
from globals.bitmaps import LOGO
from globals.compression import CompressionHandler
from globals.compression import DEFAULT_COMPRESSION_ID
from globals.compression import compression_formats
from globals.compression import compression_mimetypes
from globals.errorcodes import dbrerrno
from globals.execute import GetExecutable
from globals.fileio import ReadFile
from globals.ident import genid
from globals.ident import pgid
from globals.ident import refid
from globals.mime import GetFileMimeType
from globals.moduleaccess import ModuleAccessCtrl
from globals.paths import PATH_app
from globals.paths import PATH_local
from globals.project import ID_PROJ_A
from globals.project import ID_PROJ_L
from globals.project import ID_PROJ_T
from globals.project import ID_PROJ_Z
from globals.project import PROJECT_ext
from globals.stage import CreateStage
from globals.stage import RemoveStage
from globals.strings import GS
from startup.tests import GetTestList
from ui.about import AboutDialog
from ui.dialog import ConfirmSaveDialog
from ui.dialog import ConfirmationDialog
from ui.dialog import DetailedMessageDialog
from ui.dialog import GetDialogWildcards
from ui.dialog import GetFileOpenDialog
from ui.dialog import GetFileSaveDialog
from ui.dialog import ShowDialog
from ui.dialog import ShowErrorDialog
from ui.distcache import DistNamesCacheDialog
from ui.layout import BoxSizer
from ui.menu import MenuBar
from ui.quickbuild import QuickBuild
from ui.statusbar import StatusBar
from ui.wizard import Wizard
from wiz_bin.build import Panel as PageBuild
from wiz_bin.changelog import Panel as PageChangelog
from wiz_bin.control import Panel as PageControl
from wiz_bin.copyright import Panel as PageCopyright
from wiz_bin.depends import Panel as PageDepends
from wiz_bin.files import Panel as PageFiles
from wiz_bin.greeting import Panel as PageGreeting
from wiz_bin.launchers import Panel as PageLaunchers
from wiz_bin.manuals import Panel as PageMan
from wiz_bin.scripts import Panel as PageScripts
default_title = GT(u'Debreate - Debian Package Builder')
## TODO: Doxygen
class MainWindow(wx.Frame, ModuleAccessCtrl):
def __init__(self, pos, size):
wx.Frame.__init__(self, None, wx.ID_ANY, default_title, pos, size)
ModuleAccessCtrl.__init__(self, __name__)
# Make sure that this frame is set as the top window
if not wx.GetApp().GetTopWindow() == self:
Logger.Debug(__name__, GT(u'Setting MainWindow instance as top window'))
wx.GetApp().SetTopWindow(self)
testing = u'alpha' in GetTestList() or DebugEnabled()
if DebugEnabled():
self.SetTitle(u'{} ({})'.format(default_title, GT(u'debugging')))
self.SetMinSize(wx.Size(640, 400))
# ----- Set Titlebar Icon
self.SetIcon(Icon(LOGO))
# ----- Status Bar
StatusBar(self)
# *** File Menu *** #
self.menu_file = wx.Menu()
mitm_new = wx.MenuItem(self.menu_file, wx.ID_NEW, GT(u'New project'),
help=GT(u'Start a new project'))
mitm_open = wx.MenuItem(self.menu_file, wx.ID_OPEN, GT(u'Open'),
help=GT(u'Open a previously saved project'))
mitm_save = wx.MenuItem(self.menu_file, wx.ID_SAVE, GT(u'Save'),
help=GT(u'Save current project'))
mitm_saveas = wx.MenuItem(self.menu_file, wx.ID_SAVEAS, GT(u'Save as'),
help=GT(u'Save current project with a new filename'))
# Quick Build
mitm_quickbuild = wx.MenuItem(self.menu_file, ident.QBUILD, GT(u'Quick Build'),
GT(u'Build a package from an existing build tree'))
mitm_quickbuild.SetBitmap(ICON_CLOCK)
mitm_quit = wx.MenuItem(self.menu_file, wx.ID_EXIT, GT(u'Quit'),
help=GT(u'Exit Debreate'))
self.menu_file.AppendItem(mitm_new)
self.menu_file.AppendItem(mitm_open)
self.menu_file.AppendItem(mitm_save)
self.menu_file.AppendItem(mitm_saveas)
self.menu_file.AppendSeparator()
self.menu_file.AppendItem(mitm_quickbuild)
if testing:
mitm_alien = wx.MenuItem(self.menu_file, ident.ALIEN, GT(u'Convert packages'))
self.menu_file.AppendItem(mitm_alien)
self.menu_file.AppendSeparator()
self.menu_file.AppendItem(mitm_quit)
# *** Page Menu *** #
## This menu is filled from ui.wizard.Wizard.SetPages
self.menu_page = wx.Menu()
# *** Action Menu *** #
menu_action = wx.Menu()
mitm_build = wx.MenuItem(menu_action, genid.BUILD, GT(u'Build'),
GT(u'Start building .deb package'))
menu_action.AppendItem(mitm_build)
# ----- Options Menu
menu_opt = wx.Menu()
# Show/Hide tooltips
self.opt_tooltips = wx.MenuItem(menu_opt, ident.TOOLTIPS, GT(u'Show tooltips'),
GT(u'Show or hide tooltips'), kind=wx.ITEM_CHECK)
# A bug with wx 2.8 does not allow tooltips to be toggled off
if wx.MAJOR_VERSION > 2:
menu_opt.AppendItem(self.opt_tooltips)
if menu_opt.FindItemById(ident.TOOLTIPS):
show_tooltips = ReadConfig(u'tooltips')
if show_tooltips != ConfCode.KEY_NO_EXIST:
self.opt_tooltips.Check(show_tooltips)
else:
self.opt_tooltips.Check(GetDefaultConfigValue(u'tooltips'))
self.OnToggleToolTips()
# Project compression options
self.menu_compress = wx.Menu()
opt_z_none = wx.MenuItem(self.menu_compress, ident.ZIP_NONE,
GT(u'Uncompressed'), GT(u'Use uncompressed tarball for project save format'),
kind=wx.ITEM_RADIO)
opt_z_gz = wx.MenuItem(self.menu_compress, ident.ZIP_GZ,
GT(u'Gzip'), GT(u'Use compressed Gzip tarball for project save format'),
kind=wx.ITEM_RADIO)
opt_z_bz2 = wx.MenuItem(self.menu_compress, ident.ZIP_BZ2,
GT(u'Bzip2'), GT(u'Use compressed Bzip2 tarball for project save format'),
kind=wx.ITEM_RADIO)
opt_z_zip = wx.MenuItem(self.menu_compress, ident.ZIP_ZIP,
GT(u'Zip'), GT(u'Use compressed zip file for project save format'),
kind=wx.ITEM_RADIO)
opts_compress = [
opt_z_none,
opt_z_gz,
opt_z_bz2,
opt_z_zip,
]
if GetExecutable(u'tar') != None:
opt_z_xz = wx.MenuItem(self.menu_compress, ident.ZIP_XZ,
GT(u'XZ'), GT(u'Use compressed xz tarball for project save format'),
kind=wx.ITEM_RADIO)
opts_compress.insert(3, opt_z_xz)
for OPT in opts_compress:
self.menu_compress.AppendItem(OPT)
wx.EVT_MENU(self.menu_compress, OPT.GetId(), self.OnSetCompression)
# Default compression
self.menu_compress.Check(ident.ZIP_BZ2, True)
menu_opt.AppendSubMenu(self.menu_compress, GT(u'Project Compression'),
GT(u'Set the compression type for project save output'))
# *** Option Menu: open logs directory *** #
if GetExecutable(u'xdg-open'):
mitm_logs_open = wx.MenuItem(menu_opt, ident.OPENLOGS, GT(u'Open logs directory'))
menu_opt.AppendItem(mitm_logs_open)
wx.EVT_MENU(menu_opt, ident.OPENLOGS, self.OnLogDirOpen)
# *** OS distribution names cache *** #
opt_distname_cache = wx.MenuItem(menu_opt, ident.DIST, GT(u'Update dist names cache'),
GT(u'Creates/Updates list of distribution names for changelog page'))
menu_opt.AppendItem(opt_distname_cache)
# ----- Help Menu
menu_help = wx.Menu()
# ----- Version update
mitm_update = wx.MenuItem(menu_help, ident.UPDATE, GT(u'Check for update'),
GT(u'Check if a new version is available for download'))
mitm_update.SetBitmap(ICON_LOGO)
menu_help.AppendItem(mitm_update)
menu_help.AppendSeparator()
# Menu with links to the Debian Policy Manual webpages
self.menu_policy = wx.Menu()
policy_links = (
(refid.DPM, GT(u'Debian Policy Manual'),
u'https://www.debian.org/doc/debian-policy',),
(refid.DPMCtrl, GT(u'Control files'),
u'https://www.debian.org/doc/debian-policy/ch-controlfields.html',),
(refid.DPMLog, GT(u'Changelog'),
u'https://www.debian.org/doc/debian-policy/ch-source.html#s-dpkgchangelog',),
(refid.UPM, GT(u'Ubuntu Policy Manual'),
u'http://people.canonical.com/~cjwatson/ubuntu-policy/policy.html/',),
(refid.LINT_TAGS, GT(u'Lintian Tags Explanation'),
u'https://lintian.debian.org/tags-all.html',),
(refid.LINT_OVERRIDE, GT(u'Overriding Lintian Tags'),
u'https://lintian.debian.org/manual/section-2.4.html',),
(refid.LAUNCHERS, GT(u'Launchers / Desktop entries'),
u'https://www.freedesktop.org/wiki/Specifications/desktop-entry-spec/',),
# Unofficial links
None,
(refid.DEBSRC, GT(u'Building debs from Source'),
u'http://www.quietearth.us/articles/2006/08/16/Building-deb-package-from-source',), # This is here only temporarily for reference
(refid.MAN, GT(u'Writing manual pages'),
u'https://liw.fi/manpages/',),
)
for LINK in policy_links:
if not LINK:
self.menu_policy.AppendSeparator()
elif len(LINK) > 2:
link_id = LINK[0]
label = LINK[1]
url = LINK[2]
if len(LINK) > 3:
icon = LINK[3]
else:
icon = ICON_GLOBE
mitm = wx.MenuItem(self.menu_policy, link_id, label, url)
mitm.SetBitmap(icon)
self.menu_policy.AppendItem(mitm)
wx.EVT_MENU(self, link_id, self.OpenPolicyManual)
mitm_help = wx.MenuItem(menu_help, wx.ID_HELP, GT(u'Help'), GT(u'Open a usage document'))
mitm_about = wx.MenuItem(menu_help, wx.ID_ABOUT, GT(u'About'), GT(u'About Debreate'))
menu_help.AppendMenu(-1, GT(u'Reference'), self.menu_policy)
menu_help.AppendSeparator()
menu_help.AppendItem(mitm_help)
menu_help.AppendItem(mitm_about)
menubar = MenuBar(self)
menubar.Append(self.menu_file, GT(u'File'), wx.ID_FILE)
menubar.Append(self.menu_page, GT(u'Page'), ident.PAGE)
menubar.Append(menu_action, GT(u'Action'), ident.ACTION)
if menu_opt.GetMenuItemCount():
menubar.Append(menu_opt, GT(u'Options'), ident.OPTIONS)
menubar.Append(menu_help, GT(u'Help'), wx.ID_HELP)
self.Wizard = Wizard(self)
# Menu for debugging & running tests
if DebugEnabled():
self.menu_debug = wx.Menu()
menubar.Append(self.menu_debug, GT(u'Debug'), ident.DEBUG)
self.menu_debug.AppendItem(wx.MenuItem(self.menu_debug, ident.LOG, GT(u'Show log'),
GT(u'Toggle debug log window'), kind=wx.ITEM_CHECK))
if u'log-window' in parsed_args_s:
self.menu_debug.Check(ident.LOG, True)
self.log_window = None
# Window colors
self.menu_debug.AppendItem(
wx.MenuItem(self.menu_debug, ident.THEME, GT(u'Toggle window colors')))
wx.EVT_MENU(self, ident.THEME, self.OnToggleTheme)
# *** Current Project Status *** #
self.LoadedProject = None
self.ProjectDirty = False
self.dirty_mark = u' *'
self.menu_file.Enable(wx.ID_SAVE, self.ProjectDirty)
# *** Event Handling *** #
wx.EVT_MENU(self, wx.ID_NEW, self.OnProjectNew)
wx.EVT_MENU(self, wx.ID_OPEN, self.OnProjectOpen)
wx.EVT_MENU(self, wx.ID_SAVE, self.OnProjectSave)
wx.EVT_MENU(self, wx.ID_SAVEAS, self.OnProjectSaveAs)
wx.EVT_MENU(self, ident.QBUILD, self.OnQuickBuild)
wx.EVT_MENU(self, wx.ID_EXIT, self.OnQuit)
wx.EVT_MENU(self, ident.TOOLTIPS, self.OnToggleToolTips)
wx.EVT_MENU(self, ident.DIST, self.OnUpdateDistNamesCache)
wx.EVT_MENU(self, ident.UPDATE, self.OnCheckUpdate)
wx.EVT_MENU(self, wx.ID_HELP, self.OnHelp)
wx.EVT_MENU(self, wx.ID_ABOUT, self.OnAbout)
self.Bind(EVT_CHANGE_PAGE, self.OnWizardBtnPage)
# Custom close event shows a dialog box to confirm quit
wx.EVT_CLOSE(self, self.OnQuit)
# *** Layout *** #
lyt_main = BoxSizer(wx.VERTICAL)
lyt_main.Add(self.Wizard, 1, wx.EXPAND)
self.SetAutoLayout(True)
self.SetSizer(lyt_main)
self.Layout()
## TODO: Doxygen
def GetCompression(self):
for Z in self.menu_compress.GetMenuItems():
Z_ID = Z.GetId()
if self.menu_compress.IsChecked(Z_ID):
return compression_formats[Z_ID]
default_compression = GetDefaultConfigValue(u'compression')
Logger.Debug(__name__,
GT(u'Setting compression to default value: {}'.format(default_compression)))
return default_compression
## TODO: Doxygen
def GetCompressionId(self):
for Z in self.menu_compress.GetMenuItems():
Z_ID = Z.GetId()
if self.menu_compress.IsChecked(Z_ID):
return Z_ID
Logger.Warn(__name__, GT(u'Did not find compatible compression ID, using default'))
return DEFAULT_COMPRESSION_ID
## Retrieves the Wizard instance
#
# \return
# ui.wizard.Wizard
def GetWizard(self):
return self.Wizard
## Sets the pages in the ui.wizard.Wizard instance
def InitWizard(self):
pg_info = PageGreeting(self.Wizard)
pg_info.SetInfo()
PageControl(self.Wizard)
PageDepends(self.Wizard)
PageFiles(self.Wizard)
# TODO: finish manpage section
if u'alpha' in GetTestList() or DebugEnabled():
PageMan(self.Wizard)
PageScripts(self.Wizard)
PageChangelog(self.Wizard)
PageCopyright(self.Wizard)
PageLaunchers(self.Wizard)
pg_build = PageBuild(self.Wizard)
# Action menu events
wx.EVT_MENU(self, genid.BUILD, pg_build.OnBuild)
self.Wizard.InitPages()
## Opens a dialog box with information about the program
def OnAbout(self, event=None):
about = AboutDialog(self)
about.SetGraphic(u'{}/bitmaps/debreate64.png'.format(PATH_app))
about.SetVersion(VERSION_string)
about.SetDescription(GT(u'A package builder for Debian based systems'))
about.SetAuthor(AUTHOR_name)
about.SetWebsites((
(GT(u'Homepage'), APP_homepage),
(GT(u'GitHub Project'), APP_project_gh),
(GT(u'Sourceforge Project'), APP_project_sf),
))
about.AddJobs(
AUTHOR_name,
(
GT(u'Head Developer'),
GT(u'Packager'),
u'{} (es, it)'.format(GT(u'Translation')),
),
AUTHOR_email
)
about.AddJobs(
u'Hugo Posnic',
(
GT(u'Code Contributor'),
GT(u'Website Designer & Author'),
),
u'hugo.posnic@gmail.com'
)
about.AddJob(u'Lander Usategui San Juan', GT(u'General Contributor'), u'lander@erlerobotics.com')
about.AddTranslator(u'Karim Oulad Chalha', u'herr.linux88@gmail.com', u'ar', )
about.AddTranslator(u'Philippe Dalet', u'philippe.dalet@ac-toulouse.fr', u'fr')
about.AddTranslator(u'Zhmurkov Sergey', u'zhmsv@yandex.ru', u'ru')
about.SetChangelog()
about.SetLicense()
about.ShowModal()
about.Destroy()
## Checks for new release availability
def OnCheckUpdate(self, event=None):
update_test = u'update-fail' in GetTestList()
if UsingDevelopmentVersion() and not update_test:
DetailedMessageDialog(self, GT(u'Update'),
text=GT(u'Update checking is disabled in development versions')).ShowModal()
return
wx.SafeYield()
if update_test:
# Set a bad url to force error
current = GetCurrentVersion(u'http://dummyurl.blah/')
else:
current = GetCurrentVersion()
Logger.Debug(__name__, GT(u'URL request result: {}').format(current))
error_remote = GT(u'An error occurred attempting to contact remote website')
if isinstance(current, (URLError, HTTPError)):
current = GS(current)
ShowErrorDialog(error_remote, current)
elif isinstance(current, tuple) and current > VERSION_tuple:
current = u'{}.{}.{}'.format(current[0], current[1], current[2])
l1 = GT(u'Version {} is available!').format(current)
l2 = GT(u'Would you like to go to Debreate\'s website?')
if ConfirmationDialog(self, GT(u'Update'), u'{}\n\n{}'.format(l1, l2)).Confirmed():
wx.LaunchDefaultBrowser(APP_homepage)
elif isinstance(current, (unicode, str)):
ShowErrorDialog(error_remote, current)
else:
DetailedMessageDialog(self, GT(u'Debreate'), text=GT(u'Debreate is up to date!')).ShowModal()
## Action to take when 'Help' is selected from the help menu
#
# Opens a help dialog if using 'alpha' test. Otherwise, opens
# PDF usage document. If openening usage document fails, attempts
# to open web browser in remote usage page.
# TODO: Use dialog as main method
def OnHelp(self, event=None):
if u'alpha' in GetTestList():
HelpDialog(self).ShowModal()
else:
# First tries to open pdf help file. If fails tries to open html help file. If fails opens debreate usage webpage
wx.Yield()
status = subprocess.call([u'xdg-open', u'{}/docs/usage.pdf'.format(PATH_app)])
if status:
wx.Yield()
status = subprocess.call([u'xdg-open', u'{}/docs/usage'.format(PATH_app)])
if status:
wx.Yield()
webbrowser.open(u'http://debreate.sourceforge.net/usage')
## Opens the logs directory in the system's default file manager
def OnLogDirOpen(self, event=None):
Logger.Debug(__name__, GT(u'Opening log directory ...'))
subprocess.check_output([GetExecutable(u'xdg-open'), u'{}/logs'.format(PATH_local)], stderr=subprocess.STDOUT)
## Changes wizard page from menu
def OnMenuChangePage(self, event=None):
page_id = None
if event:
page_id = event.GetId()
Logger.Debug(__name__, GT(u'Page ID from menu event: {}').format(page_id))
else:
for M in self.menu_page.GetMenuItems():
if M.IsChecked():
page_id = M.GetId()
Logger.Debug(__name__, GT(u'Page ID from menu item: {}').format(page_id))
break
if page_id == None:
Logger.Error(__name__, GT(u'Could not get page ID'))
return
self.Wizard.ShowPage(page_id)
## TODO: Doxygen
def OnQuickBuild(self, event=None):
QB = QuickBuild(self)
QB.ShowModal()
QB.Destroy()
## Shows a dialog to confirm quit and write window settings to config file
def OnQuit(self, event=None):
if ConfirmationDialog(self, GT(u'Quit?'),
text=GT(u'You will lose any unsaved information')).Confirmed():
maximized = self.IsMaximized()
# Get window attributes and save to config file
# Save default window settings if maximized
# FIXME: Better solution?
if maximized:
WriteConfig(u'size', GetDefaultConfigValue(u'size'))
WriteConfig(u'position', GetDefaultConfigValue(u'position'))
WriteConfig(u'center', GetDefaultConfigValue(u'center'))
WriteConfig(u'maximize', True)
else:
WriteConfig(u'position', self.GetPositionTuple())
WriteConfig(u'size', self.GetSizeTuple())
WriteConfig(u'center', False)
WriteConfig(u'maximize', False)
config_wdir = ReadConfig(u'workingdir')
current_wdir = os.getcwd()
# Workaround for issues with some dialogs not writing to config
if config_wdir != current_wdir:
WriteConfig(u'workingdir', current_wdir)
self.Destroy()
## Handles events from fields that are essential to project
#
# \return
# \b \e True if 'dirty' status was changed
def OnProjectChanged(self, event=None):
changed = False
if not self.ProjectDirty:
changed = self.ProjectSetDirty()
if DebugEnabled():
Logger.Debug(__name__, u'MainWindow.OnProjectChanged: {}'.format(changed), newline=True)
print(u' Object: {}'.format(event.GetEventObject()))
return changed
## Clears current project & restores fields to defaults
#
# \return
# \b \e True if project state is reset to default
def OnProjectNew(self, event=None):
Logger.Debug(__name__, GT(u'Project loaded before OnProjectNew: {}').format(self.ProjectIsLoaded()))
return self.ProjectClose()
## TODO: Doxygen
def OnProjectOpen(self, event=None):
return self.ProjectOpen()
## TODO: Doxygen
def OnProjectSave(self, event=None):
# Open a file save dialog for new projects
# FIXME: Necessary?
if not self.ProjectIsLoaded():
self.OnProjectSaveAs(event)
return
# 'Save' menu item is enabled
Logger.Debug(__name__, GT(u'Project loaded; Saving without showing dialog'))
# Saving over currently loaded project
self.ProjectSave(self.LoadedProject)
## TODO: Doxygen
def OnProjectSaveAs(self, event=None):
self.ProjectSaveAs()
## Writes compression value to config in real time
def OnSetCompression(self, event=None):
if event:
event_id = event.GetId()
Logger.Debug(__name__, GT(u'OnSetCompression; Event ID: {}').format(event_id))
Logger.Debug(__name__, GT(u'OnSetCompression; Compression from event ID: {}').format(compression_formats[event_id]))
if event_id in compression_formats:
WriteConfig(u'compression', compression_formats[event_id])
return
Logger.Warn(__name__,
GT(u'OnSetCompression; Could not write to config, ID not found in compression formats: {}').format(event_id))
## TODO: Doxygen
def OnToggleLogWindow(self, event=None):
Logger.Debug(__name__, GT(u'Toggling log window'))
if event != None:
self.ShowLogWindow(self.menu_debug.IsChecked(ident.DEBUG))
return
self.menu_debug.Check(ident.DEBUG, self.log_window.IsShown())
## TODO: Doxygen
def OnToggleTheme(self, event=None):
self.ToggleTheme(self)
## Shows or hides tooltips
def OnToggleToolTips(self, event=None):
enabled = self.opt_tooltips.IsChecked()
wx.ToolTip.Enable(enabled)
WriteConfig(u'tooltips', enabled)
## Opens a dialog for creating/updating list of distribution names cache file
def OnUpdateDistNamesCache(self, event=None):
DistNamesCacheDialog().ShowModal()
## Updates the page menu to reflect current page
def OnWizardBtnPage(self, event=None):
ID = self.Wizard.GetCurrentPageId()
Logger.Debug(__name__, GT(u'Event: EVT_CHANGE_PAGE, Page ID: {}').format(ID))
if not self.menu_page.IsChecked(ID):
self.menu_page.Check(ID, True)
## Opens web links from the help menu
def OpenPolicyManual(self, event=None):
if isinstance(event, wx.CommandEvent):
event_id = event.GetId()
elif isinstance(event, int):
event_id = event
else:
Logger.Error(__name__,
u'Cannot open policy manual link with object type {}'.format(type(event)))
return
url = self.menu_policy.GetHelpString(event_id)
webbrowser.open(url)
## Closes currently open project & resets pages to default
#
# \return
# \b \e True if the project was closed, \b \e False if should not continue
def ProjectClose(self):
if not self.ProjectIsDirty():
self.Wizard.ResetPagesInfo()
self.LoadedProject = None
# Everything okay to continue
return True
msg_l1 = GT(u'{} is unsaved, any changes will be lost').format(self.LoadedProject)
confirmed = ConfirmSaveDialog(self, GT(u'Unsaved Changes'),
text=GT(u'{}\n\n{}'.format(msg_l1, GT(u'Continue?')))).ShowModal()
if confirmed == wx.ID_SAVE:
if self.LoadedProject:
Logger.Debug(__name__, u'Saving modified project ...')
self.ProjectSave(self.LoadedProject)
else:
Logger.Debug(__name__, u'Saving new project ...')
# Open file save dialog for new project
if self.ProjectSaveAs() != dbrerrno.SUCCESS:
return False
elif confirmed != wx.ID_OK:
return False
self.Wizard.ResetPagesInfo()
self.LoadedProject = None
self.ProjectSetDirty(False)
return not self.ProjectIsLoaded()
## Retrieves filename of loaded project
def ProjectGetLoaded(self):
return self.LoadedProject
## Checks if current project is dirty
def ProjectIsDirty(self):
return self.ProjectDirty
## Checks if a project is loaded
def ProjectIsLoaded(self):
return self.LoadedProject != None
## Tests project type & calls correct method to read project file
#
# Opens a file dialog if not project file is specified.
# \param project_file
# \b \e unicode|str : Path to project file
def ProjectOpen(self, project_file=None):
Logger.Debug(__name__, u'Opening project: {}'.format(project_file))
# Need to show file open dialog because no project file was specified
if not project_file:
wc_z = GetDialogWildcards(ID_PROJ_Z)
wc_l = GetDialogWildcards(ID_PROJ_L)
wc_a = GetDialogWildcards(ID_PROJ_A)
wc_t = GetDialogWildcards(ID_PROJ_T)
wildcards = (
wc_a[0], wc_a[1],
wc_z[0], wc_z[1],
wc_t[0], wc_t[1],
wc_l[0], wc_l[1],
)
open_dialog = GetFileOpenDialog(self, GT(u'Open Debreate Project'), wildcards)
if not ShowDialog(open_dialog):
return dbrerrno.ECNCLD
# Get the path and set the saved project
project_file = open_dialog.GetPath()
# Failsafe check that file exists
if not os.path.isfile(project_file):
err_l1 = GT(u'Cannot open project:')
err_details = GT(u'File does not exist')
ShowErrorDialog(u'{} {}'.format(err_l1, project_file), err_details)
return dbrerrno.ENOENT
# Check for unsaved changes & reset project to defaults
if not self.ProjectClose():
return dbrerrno.ECNCLD
mime_type = GetFileMimeType(project_file)
Logger.Debug(__name__, GT(u'Project mime type: {}').format(mime_type))
opened = None
if mime_type == u'text/plain':
p_text = ReadFile(project_file)
filename = os.path.split(project_file)[1]
# Legacy projects should return None since we can't save in that format
opened = self.ProjectOpenLegacy(p_text, filename)
else:
opened = self.ProjectOpenArchive(project_file, mime_type)
Logger.Debug(__name__, GT(u'Project loaded before OnProjectOpen: {}').format(self.ProjectIsLoaded()))
if opened == dbrerrno.SUCCESS:
self.LoadedProject = project_file
# Set project 'unmodified' for newly opened project
self.ProjectSetDirty(False)
Logger.Debug(__name__, GT(u'Project loaded after OnOpenPreject: {}').format(self.ProjectIsLoaded()))
if DebugEnabled() and self.ProjectIsLoaded():
Logger.Debug(__name__, GT(u'Loaded project: {}').format(self.LoadedProject))
return opened
## TODO: Doxygen
def ProjectOpenArchive(self, filename, file_type):
Logger.Debug(__name__, GT(u'Compressed project archive detected'))
if file_type not in compression_mimetypes:
Logger.Error(__name__, GT(u'Cannot open project with compression mime type "{}"'.format(file_type)))
return dbrerrno.EBADFT
compression_id = compression_mimetypes[file_type]
z_format = compression_formats[compression_id]
if z_format in (u'tar', u'zip'):
z_format = u'r'
else:
z_format = u'r:{}'.format(z_format)
Logger.Debug(__name__, GT(u'Opening compressed project with "{}" format').format(z_format))
stage = CreateStage()
p_archive = CompressionHandler(compression_id)
ret_code = p_archive.Uncompress(filename, stage)
if isinstance(ret_code, tuple) and ret_code[0]:
ShowErrorDialog(u'{}: {}'.format(GT(u'Project load error'), ret_code[1]),
ret_code[0], parent=self)
return dbrerrno.EBADFT
self.Wizard.ImportPagesInfo(stage)
RemoveStage(stage)
# Mark project as loaded
return dbrerrno.SUCCESS
## TODO: Doxygen
def ProjectOpenLegacy(self, data, filename):
Logger.Debug(__name__, GT(u'Legacy project format (text) detected'))
def ProjectError():
wx.MessageDialog(self, GT(u'Not a valid Debreate project'), GT(u'Error'),
style=wx.OK|wx.ICON_ERROR).ShowModal()
if data == wx.EmptyString:
ProjectError()
return dbrerrno.EBADFT
lines = data.split(u'\n')
app = lines[0].split(u'-')[0].split(u'[')[1]
if app != u'DEBREATE':
ProjectError()
return dbrerrno.EBADFT
# *** Get Control Data *** #
control_data = data.split(u'<<CTRL>>\n')[1].split(u'\n<</CTRL>>')[0]
depends_data = self.Wizard.GetPage(pgid.CONTROL).Set(control_data)
self.Wizard.GetPage(pgid.DEPENDS).Set(depends_data)
# *** Get Files Data *** #
files_data = data.split(u'<<FILES>>\n')[1].split(u'\n<</FILES>>')[0]
self.Wizard.GetPage(pgid.FILES).Set(files_data)
# *** Get Scripts Data *** #
scripts_data = data.split(u'<<SCRIPTS>>\n')[1].split(u'\n<</SCRIPTS>>')[0]
self.Wizard.GetPage(pgid.SCRIPTS).Set(scripts_data)
# *** Get Changelog Data *** #
clog_data = data.split(u'<<CHANGELOG>>\n')[1].split(u'\n<</CHANGELOG>>')[0]
self.Wizard.GetPage(pgid.CHANGELOG).Set(clog_data)
# *** Get Copyright Data *** #
try:
cpright_data = data.split(u'<<COPYRIGHT>>\n')[1].split(u'\n<</COPYRIGHT')[0]
self.Wizard.GetPage(pgid.COPYRIGHT).Set(cpright_data)
except IndexError:
pass
# *** Get Menu Data *** #
m_data = data.split(u'<<MENU>>\n')[1].split(u'\n<</MENU>>')[0]
self.Wizard.GetPage(pgid.LAUNCHERS).Set(m_data)
# Get Build Data
build_data = data.split(u'<<BUILD>>\n')[1].split(u'\n<</BUILD')[0]
self.Wizard.GetPage(pgid.BUILD).Set(build_data)
self.ProjectSetDirty(False)
# Legacy projects should return None since we can't save in that format
return None
## Saves project in archive format
#
# Supported uncompressed formats are unix tarball.
# Supported compressed formats are Gzip & Bzip2
# tarballs.
# Proposed formats are xz compressed tarball &
# zip compressed file.
# \param target_path
# Absolute output filename
def ProjectSave(self, target_path):
Logger.Debug(__name__, GT(u'Saving in new project format'))
Logger.Debug(__name__, GT(u'Saving to file {}').format(target_path))
stage = CreateStage()
if not os.path.exists(stage) or stage == dbrerrno.EACCES:
ShowErrorDialog(u'{}: {}'.format(GT(u'Could not create staging directory'), stage),
parent=self)
return dbrerrno.EACCES
Logger.Debug(__name__, GT(u'Temp dir created: {}').format(stage))
working_path = os.path.dirname(target_path)
output_filename = os.path.basename(target_path)
Logger.Debug(
__name__,
u'Save project\n\tWorking path: {}\n\tFilename: {}\n\tTemp directory: {}'.format(working_path,
output_filename, stage)
)
export_pages = (
pgid.CONTROL,
pgid.FILES,
pgid.SCRIPTS,
pgid.CHANGELOG,
pgid.COPYRIGHT,
pgid.LAUNCHERS,