/
WxFixBoot.py
executable file
·3398 lines (2622 loc) · 149 KB
/
WxFixBoot.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 python3
# -*- coding: utf-8 -*-
# WxFixBoot
# Copyright (C) 2013-2020 Hamish McIntyre-Bhatty
# WxFixBoot is free software: you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 3 or,
# at your option, any later version.
#
# WxFixBoot is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with WxFixBoot. If not, see <http://www.gnu.org/licenses/>.
# pylint: disable=logging-not-lazy
#
# Reason (logging-not-lazy): This is a more readable way of logging.
"""
This is WxFixBoot's main executable. Execute the file to start the program.
This file also contains most of the GUI-related code, with small portions
being offloaded into Tools/dialogtools.py and Tools/notebookfunctions.py.
"""
#Import other modules
from distutils.version import LooseVersion
import traceback
import threading
import sys
import getopt
import logging
import os
import time
import plistlib
import ast
import requests
import getdevinfo
import getdevinfo.linux
import wx
import wx.html
import wx.lib.statbmp
import wx.lib.stattext
import wx.adv
from wx.adv import AboutDialogInfo as wxAboutDialogInfo #pylint: disable=no-name-in-module
from wx.adv import AboutBox as wxAboutBox #pylint: disable=no-name-in-module
#Define the version number and the release date as global variables.
VERSION = "3.1.0"
RELEASEDATE = "2/12/2020"
RELEASE_TYPE = "Development"
#Define other global variables.
SESSION_ENDING = False
APPICON = None
OUTPUT_LOG = None
OPERATIONS = None
NUMBER_OF_OPERATIONS = None
STOP_PROGRESSTEXT_HANDLER_THREAD = None
def usage():
"""Prints usage information to the command line"""
print("\nUsage: WxFixBoot.py [OPTION]\n")
print(" -h, --help: Show this help message")
print(" -q, --quiet: Show only warning, error and critical messages ")
print(" in the log file. Very unhelpful for debugging, ")
print(" and not recommended.")
print(" -v, --verbose: Enable logging of info messages, as well as ")
print(" warnings, errors and critical errors.")
print(" Not the best for debugging, but acceptable if ")
print(" there is little disk space.")
print(" -d, --debug: Log lots of boring debug messages, as well as ")
print(" information, warnings, errors and critical ")
print(" errors. Usually used for diagnostic purposes.")
print(" The default, as it's very helpful if problems ")
print(" are encountered, and the user needs help\n")
print("WxFixBoot "+VERSION+" is released under the GNU GPL Version 3")
print("Copyright (C) Hamish McIntyre-Bhatty 2013-2020")
if __name__ == "__main__":
#Set up according to cmdline options.
try:
OPTIONS = getopt.getopt(sys.argv[1:], "hqvd", ("help", "quiet", "verbose", "debug"))[0]
except getopt.GetoptError as err:
#Invalid option. Show the help message and then exit.
#Show the error.
print(str(err))
usage()
sys.exit(2)
#Check if we're running on Parted Magic.
PARTED_MAGIC = ("PartedMagic" in os.uname()[1])
#Set up logging.
logger = logging.getLogger('WxFixBoot')
logging.basicConfig(filename='/tmp/wxfixboot.log',
format='%(asctime)s - %(name)s - %(levelname)s: %(message)s',
datefmt='%d/%m/%Y %I:%M:%S %p')
logger.setLevel(logging.DEBUG)
#Set restarting to false.
RESTARTING = False
#Determine the option(s) given, and change the level of logging based on cmdline options.
for OPTION, ARGUMENT in OPTIONS:
if OPTION in ("-q", "--quiet"):
logger.setLevel(logging.WARNING)
elif OPTION in ("-v", "--verbose"):
logger.setLevel(logging.INFO)
elif OPTION in ("-d", "--debug"):
logger.setLevel(logging.DEBUG)
elif OPTION in ("-h", "--help"):
usage()
sys.exit()
else:
assert False, "unhandled option"
#Import custom-made modules
#NB: This is done here so the logger is already set up - logging levels can be set properly in
#submodules.
import Tools #pylint: disable=wrong-import-position
from Tools.dictionaries import * #pylint: disable=wrong-import-position
import Tools.coretools as CoreTools #pylint: disable=wrong-import-position
import Tools.dialogtools as DialogTools #pylint: disable=wrong-import-position
import Tools.StartupTools.main as MainStartupTools #pylint: disable=wrong-import-position
import Tools.BackendTools.essentials as EssentialBackendTools #pylint: disable=wrong-import-position
import Tools.BackendTools.main as MainBackendTools #pylint: disable=wrong-import-position
import Tools.notebookfunctions as NoteBookSharedFunctions #pylint: disable=wrong-import-position
#Begin Disk Information Handler thread.
class GetDiskInformation(threading.Thread):
"""
Used to get disk information without blocking the GUI thread.
Calls parent.receive_diskinfo when info has ben retrieved.
"""
def __init__(self, parent):
"""Initialize and start the thread."""
self.parent = parent
threading.Thread.__init__(self)
self.start()
def run(self):
"""Get Disk Information and return it as a list with embedded lists"""
#Use a module I've written to collect data about connected Disks, and return it.
wx.CallAfter(self.parent.receive_diskinfo, self.get_info())
def get_info(self): #pylint: disable=no-self-use
"""Get disk information as a privileged user"""
output = CoreTools.start_process(exec_cmds=sys.executable+" "+"/usr/share/wxfixboot"
+"/Tools/run_getdevinfo.py",
return_output=True,
privileged=True)[1]
#Success! Now use ast to convert the returned string to a dictionary.
try:
return ast.literal_eval(output)
except (SyntaxError, ValueError, TypeError) as error:
#If this fails for some reason, just return an empty dictionary.
logger.error("GetDiskInformation().get_info(): Error: "+str(error))
return {}
#End Disk Information Handler thread.
#Begin Starter Class
class WxFixBoot(wx.App):
"""
This class is used to start the GUI.
"""
def OnInit(self): #pylint: disable=invalid-name,no-self-use
"""Starts InitialWindow()"""
InitialWindow().Show()
return True
#End Starter Class
#Begin Initialization Panel.
class InitialPanel(wx.Panel): #pylint: disable=too-few-public-methods
"""
This is the panel shown when the GUI is initialising and collecting data.
"""
def __init__(self, parent):
"""Initialises the panel"""
wx.Panel.__init__(self, parent=parent)
self.SetBackgroundStyle(wx.BG_STYLE_CUSTOM)
self.frame = parent
self.Bind(wx.EVT_PAINT, self.on_erase_background)
def on_erase_background(self, event): #pylint: disable=unused-argument
"""Redraw the background image when needed"""
_dc = wx.ClientDC(self)
_dc.SetClippingRegion(self.GetUpdateRegion().GetBox())
_dc.Clear()
splash = wx.Bitmap("/usr/share/wxfixboot/images/splash.png")
_dc.DrawBitmap(splash, 0, 0)
#End Initialization Panel.
#Begin Initialization Frame.
class InitialWindow(wx.Frame): #pylint: disable=too-many-ancestors
"""
This is the splash screen that displays on startup with the progress bar and text
displaying startup progress.
"""
def __init__(self):
"""Initialises InitialWindow"""
wx.Frame.__init__(self, parent=None, title="WxFixBoot",
size=(600, 420), style=wx.SIMPLE_BORDER)
self.panel = InitialPanel(self)
#Disabled to work around bug in wxPython/wxWidgets:
#https://discuss.wxpython.org/t/wx-frame-style-wx-simple-border-doesnt-work-on-wxpython-4-1-0/35028/7
#self.SetClientSize(wx.Size(600, 420))
#Fix crashes when wxfixboot is restarted.
wx.GetApp().SetTopWindow(self)
if RESTARTING is False:
print("WxFixBoot Version "+VERSION+" Starting...")
logger.info("WxFixBoot Version "+VERSION+" Starting...")
else:
print("WxFixBoot Version "+VERSION+" Restarting...")
logger.info("WxFixBoot Version "+VERSION+" Restarting...")
logger.info("Release date: "+RELEASEDATE)
logger.info("Running on Python version: "+str(sys.version_info)+"...")
logger.info("Running on wxPython version: "+wx.version()+"...")
#Set the frame's icon.
global APPICON
APPICON = wx.Icon("/usr/share/wxfixboot/images/logo.png", wx.BITMAP_TYPE_PNG)
wx.Frame.SetIcon(self, APPICON)
#Create the progress bar and text.
self.create_progress_bar_and_text()
#Setup sizers.
self.setup_sizers()
#Start the Initalization Thread, which performs all necessary startup
#scripts and checks, and let it know this is the first start.
logger.debug("Starting InitThread()...")
ProgressTextHandlerThread()
InitThread()
def create_progress_bar_and_text(self):
"""Create a progressbar and some progress text"""
self.progress_bar = wx.Gauge(self.panel, -1, 100)
self.progress_bar.SetValue(0)
self.progress_bar.Show()
#Create the progress text.
self.progress_text = wx.StaticText(self.panel, -1, "Initialising...")
#Set foreground colour to make sure text is visible when a dark theme is in use.
self.progress_text.SetForegroundColour(wx.Colour(61, 61, 61))
def setup_sizers(self):
"""Setup sizers for InitialWindow"""
main_sizer = wx.BoxSizer(wx.VERTICAL)
main_sizer.Add((50, 50), 10, wx.EXPAND)
main_sizer.Add(self.progress_text, 1, wx.CENTER|wx.BOTTOM|wx.LEFT|wx.RIGHT, 10)
main_sizer.Add(self.progress_bar, 1, wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, 10)
#Get the sizer set up for the frame.
self.panel.SetSizer(main_sizer)
main_sizer.SetMinSize(wx.Size(600, 420))
self.SetMinSize(wx.Size(600, 420))
self.SetMaxSize(wx.Size(600, 420))
def update_progress_bar(self, value):
"""Update the progress bar with the given value"""
self.progress_bar.SetValue(int(value))
if int(value) == 100:
global STOP_PROGRESSTEXT_HANDLER_THREAD
STOP_PROGRESSTEXT_HANDLER_THREAD = True
self.finished_startup()
def update_progress_text(self, message):
"""Call the text handler thread to distract the user"""
self.progress_text.SetLabel(message)
self.panel.Layout()
def set_progress_text(self, message):
"""Update the progress text with the given string"""
self.progress_text.SetLabel(message)
self.panel.Layout()
def finished_startup(self, event=None): #pylint: disable=unused-argument
"""Starts MainWindow, called when StartupScripts are finished"""
logger.info("Closing Initial Window and Starting Main Window...")
#Show the user some important information
DialogTools.show_msg_dlg(kind="info", message="Please make sure you have a working "
+ "internet connection before performing any "
+ "bootloader operations. Thank you.")
main_gui = MainWindow()
APP.SetTopWindow(main_gui)
self.Destroy()
#Start MainFrame.
main_gui.Show(True)
#End Initialization Frame.
#Begin Progress Text Handler Thread.
class ProgressTextHandlerThread(threading.Thread):
"""
A separate thread to handle the text on the splash screen to indicate the program
is still running during slow startup routines.
"""
def __init__(self):
"""Start the Thread"""
threading.Thread.__init__(self)
self.parent_window = wx.GetApp().TopWindow
global STOP_PROGRESSTEXT_HANDLER_THREAD
STOP_PROGRESSTEXT_HANDLER_THREAD = False
self.start()
def run(self):
"""Distract the user with some text effects on the Initial Window.
For 10 seconds of the same message, make dots build up to 3 dots and back after the text.
After 10 seconds of same message, state that WxFixBoot is still starting up,
and to be patient."""
half_second_counter = 0
message = ""
while True:
if STOP_PROGRESSTEXT_HANDLER_THREAD:
break
if half_second_counter == 20:
message = message.replace(".", "") \
+ ". This may take a few minutes. Please be patient."
wx.CallAfter(self.parent_window.set_progress_text, message)
time.sleep(0.5)
half_second_counter += 1
else:
last_message = message
message = self.parent_window.progress_text.GetLabel()
if message == last_message:
half_second_counter += 1
if message[-3:] == "...":
message = message[0:-3]
message = message+"."
wx.CallAfter(self.parent_window.set_progress_text, message)
time.sleep(0.5)
#End Progress Text Handler Thread.
#Begin Initialization Thread.
class InitThread(threading.Thread):
"""
This is the thread that does all of the heavy lifting and information collection
during startup, while the splash screen is displayed.
"""
def __init__(self):
"""Start the thread."""
#Initialize the thread.
threading.Thread.__init__(self)
self.parent_window = wx.GetApp().TopWindow
self.disk_info_collected = False
#Start the thread.
self.start()
def run(self):
"""Handle errors in the main thread code"""
logger.debug("InitThread(): Starting...")
#Handle any unexpected errors.
try:
self.main_code()
except Exception:
logger.critical("Unexpected error \n\n"
+ str(traceback.format_exc())
+ "\n\n while starting WxFixBoot. "
+ "Warning user and exiting.")
CoreTools.emergency_exit("There was an unexpected error: \n\n"
+ str(traceback.format_exc())
+ "\n\nWhile starting up!")
def receive_diskinfo(self, info):
"""Receive disk info"""
DISK_INFO.update(info)
self.disk_info_collected = True
def main_code(self):
"""Create the temporary mount point folder and set some default settings."""
global SYSTEM_INFO
global SETTINGS
global DISK_INFO
global OS_INFO
#Let CoreTools know we're starting up.
Tools.coretools.STARTUP = True
#Set variables used for checking whether bootloader operations have been disabled.
SYSTEM_INFO["DisableBootloaderOperations"] = False
SYSTEM_INFO["DisableBootloaderOperationsBecause"] = []
#Initialise a variable for later.
SYSTEM_INFO["PreviousOSChoice"] = ""
#Set initial settings for MainWindow.
SETTINGS["QuickFSCheck"] = False
SETTINGS["BadSectorCheck"] = False
SETTINGS["FullVerbosity"] = False
SETTINGS["MakeSystemSummary"] = True
SETTINGS["SaveOutput"] = True
#Remove the temporary directory if it exists.
if os.path.isdir("/mnt/wxfixboot/mountpoints"):
#Check nothing is using it first.
for line in CoreTools.start_process("mount", return_output=True)[1].split("\n"):
if "/mnt/wxfixboot/mountpoints" in line:
#Unmount this filesystem if possible.
filesystem = line.split(" on ")[0]
if CoreTools.unmount(filesystem) != 0:
#If it can't be mounted, do an emergency exit.
CoreTools.emergency_exit("There are mounted filesystems in "
+ "/mnt/wxfixboot/mountpoints, WxFixBoot's "
+ "temporary mountpoints directory! Please "
+ "unmount any filesystems there and try "
+ "again.")
CoreTools.start_process("rm -rvf --one-file-system /mnt/wxfixboot/mountpoints", privileged=True)
CoreTools.start_process("mkdir /mnt/wxfixboot/mountpoints", privileged=True)
CoreTools.start_process("chmod a+rw -R /mnt/wxfixboot", privileged=True)
#Check for dependencies
logger.info("InitThread(): Checking For Dependencies...")
wx.CallAfter(self.parent_window.update_progress_text, "Checking For Dependencies...")
MainStartupTools.check_depends()
wx.CallAfter(self.parent_window.update_progress_bar, "2")
logger.info("InitThread(): Done Checking For Dependencies!")
#Check if we're on a Live Disk.
logger.info("InitThread(): Checking For Live Disk...")
wx.CallAfter(self.parent_window.update_progress_text, "Checking For Live Disk...")
MainStartupTools.check_for_live_disk()
wx.CallAfter(self.parent_window.update_progress_bar, "10")
logger.info("InitThread(): Done Checking For Live Disk!")
#Check filesystems.
logger.info("InitThread(): Checking Filesystems...")
wx.CallAfter(self.parent_window.update_progress_text, "Checking Filesystems...")
MainStartupTools.check_filesystems()
wx.CallAfter(self.parent_window.update_progress_bar, "15")
logger.info("InitThread(): Filesystems Checked!")
#Get device info.
logger.info("InitThread(): Getting Device Information...")
wx.CallAfter(self.parent_window.update_progress_text, "Getting Device Information...")
GetDiskInformation(self)
while not self.disk_info_collected:
time.sleep(0.5)
wx.CallAfter(self.parent_window.update_progress_bar, "60")
logger.info("InitThread(): Finished Getting Device Information...")
#Mount all filesystems.
logger.info("InitThread(): Mounting Core Filesystems...")
wx.CallAfter(self.parent_window.update_progress_text, "Mounting Core Filesystems...")
MainStartupTools.mount_core_filesystems()
wx.CallAfter(self.parent_window.update_progress_bar, "63")
logger.info("InitThread(): Done Mounting Core Filsystems!")
#Get a list of OSs.
logger.info("InitThread(): Finding OSs...")
wx.CallAfter(self.parent_window.update_progress_text, "Finding Operating Systems...")
temp_os_info, temp_system_info = MainStartupTools.get_oss()
OS_INFO.update(temp_os_info)
SYSTEM_INFO.update(temp_system_info)
wx.CallAfter(self.parent_window.update_progress_bar, "65")
logger.info("InitThread(): Done Finding OSs...")
#Get the firmware type.
logger.info("InitThread(): Determining Firmware Type...")
wx.CallAfter(self.parent_window.update_progress_text, "Determining Firmware Type...")
MainStartupTools.get_firmware_type()
wx.CallAfter(self.parent_window.update_progress_bar, "70")
logger.info("InitThread(): Determined Firmware Type as: "+SYSTEM_INFO["FirmwareType"])
#New bootloader info getting function.
logger.info("InitThread(): Finding all Bootloaders and getting their settings...")
wx.CallAfter(self.parent_window.update_progress_text, "Finding Bootloaders...")
MainStartupTools.get_bootloaders()
wx.CallAfter(self.parent_window.update_progress_bar, "80")
logger.info("InitThread(): Done!")
#Check if any modifyable Linux installations were found.
if not SYSTEM_INFO["ModifyableOSs"]:
logger.critical("InitThread(): No modifyable Linux installations found! If you think "
+ "this is incorrect, please file a bug or ask a question on "
+ "WxFixBoot's launchpad page. Exiting...")
#Exit.
CoreTools.emergency_exit("You don't appear to have any modifyable Linux installations "
+ "on your hard disks. If you think this is incorrect, "
+ "please file a bug or ask a question on WxFixBoot's "
+ "launchpad page at https://www.launchpad.net/wxfixboot")
#Perform final check.
logger.info("InitThread(): Doing Final Check for error situations...")
wx.CallAfter(self.parent_window.update_progress_text, "Checking Everything...")
MainStartupTools.final_check()
wx.CallAfter(self.parent_window.update_progress_bar, "100")
logger.info("InitThread(): Done Final Check!")
#Let CoreTools know we're finished starting up.
Tools.coretools.STARTUP = False
wx.CallAfter(self.parent_window.update_progress_text, "Finished! Starting GUI...")
logger.info("InitThread(): Finished Determining Settings. Exiting InitThread()...")
#End Initalization Thread.
#Begin Main Window
class MainWindow(wx.Frame): #pylint: disable=too-many-ancestors, too-many-instance-attributes
"""
This is WxFixBoot's main window, where the main options can be selected, and you
can navigate to the Bootloader Options window.
"""
def __init__(self):
"""Initialise MainWindow"""
wx.Frame.__init__(self, None, title="WxFixBoot", size=(400, 300),
style=wx.DEFAULT_FRAME_STYLE)
self.panel = wx.Panel(self)
self.SetClientSize(wx.Size(400, 300))
#Set the frame's icon.
wx.Frame.SetIcon(self, APPICON)
#Create a Statusbar in the bottom of the window and set the text.
self.make_status_bar()
#Add text.
self.create_text()
#Create some buttons
self.create_buttons()
#Create some checkboxes
self.create_checkboxes()
#Create the menus.
self.create_menus()
#Set up checkboxes
self.refresh_main_window()
#Setup Sizers.
self.setup_sizers()
#Bind all events.
self.bind_events()
#Check for updates.
wx.CallLater(10000, self.check_for_updates, starting_up=True)
logger.debug("MainWindow().__init__(): Started. Waiting for events...")
def update_output_box(self, line, show_output):
"""Ignored, temporarily here for compatibility with coretools.start_process"""
pass
def make_status_bar(self):
"""Create the status bar"""
self.statusbar = self.CreateStatusBar()
self.statusbar.SetFieldsCount(2)
self.statusbar.SetStatusWidths([-1, 165])
self.statusbar.SetStatusText("Ready.", 0)
self.statusbar.SetStatusText("v"+VERSION+" ("+RELEASEDATE+")", 1)
def create_text(self):
"""Create the text"""
self.settings_text = wx.StaticText(self.panel, -1,
"Please set the basic settings here first.")
self.welcome_text = wx.StaticText(self.panel, -1, "Welcome to WxFixBoot!")
#Add an image.
img = wx.Image("/usr/share/pixmaps/wxfixboot.png", wx.BITMAP_TYPE_PNG)
self.logo = wx.StaticBitmap(self.panel, -1, wx.Bitmap(img))
def create_buttons(self):
"""Create the buttons"""
self.about_button = wx.Button(self.panel, wx.ID_ANY, "About")
self.exit_button = wx.Button(self.panel, wx.ID_ANY, "Quit")
self.bootloader_options_button = wx.Button(self.panel, -1, "Bootloader Options")
self.apply_operations_button = wx.Button(self.panel, wx.ID_ANY, "Apply All Operations")
def create_checkboxes(self):
"""Create the checkboxes"""
self.bad_sector_check_check_box = wx.CheckBox(self.panel, -1,
"Check All File Systems (thorough)")
self.check_filesystems_check_box = wx.CheckBox(self.panel, -1,
"Check All File Systems (quick)")
self.fullverbose_checkbox = wx.CheckBox(self.panel, -1, "Show diagnostic terminal output")
self.make_summary_check_box = wx.CheckBox(self.panel, -1, "Save System Report To File")
self.log_output_checkbox = wx.CheckBox(self.panel, -1, "Save terminal output in Report")
def create_menus(self):
"""Create the menus"""
filemenu = wx.Menu()
viewmenu = wx.Menu()
editmenu = wx.Menu()
helpmenu = wx.Menu()
#Adding Menu Items.
self.menu_updates = helpmenu.Append(wx.ID_ANY, "&Check for Updates",
"Check for updates to WxFixBoot")
self.menu_about = helpmenu.Append(wx.ID_ABOUT, "&About", "Information about this program")
self.menu_exit = filemenu.Append(wx.ID_EXIT, "&Exit", "Terminate this program")
self.menu_systeminfo = viewmenu.Append(wx.ID_ANY, "&System Information", "Information "
+ "about all detected disks, OSs, and Bootloaders")
self.menu_privacy_policy = viewmenu.Append(wx.ID_ANY, "&Privacy Policy",
"View WxFixBoot's privacy policy")
self.menu_bootloader_options = editmenu.Append(wx.ID_PREFERENCES, "&Bootloader Options",
"All Bootloader Options used to modify/fix "
+ "your system")
#Creating the menubar.
menubar = wx.MenuBar()
#Adding menus to the MenuBar
menubar.Append(filemenu, "&File")
menubar.Append(editmenu, "&Edit")
menubar.Append(viewmenu, "&View")
menubar.Append(helpmenu, "&Help")
#Adding the MenuBar to the Frame content.
self.SetMenuBar(menubar)
def on_checkbox(self, event=None): #pylint: disable=unused-argument
"""
Called when one of the checkboxes is checked/unchecked,
to make sure the options stay valid
"""
logger.debug("MainWindow().on_checkbox(): Checkboxes have been changed. "
+ "Making sure options are valid and don't conflict...")
#Bad Sector Check Choicebox
if self.bad_sector_check_check_box.IsChecked():
self.check_filesystems_check_box.Disable()
else:
self.check_filesystems_check_box.Enable()
#Quick Disk Check Choicebox
if self.check_filesystems_check_box.IsChecked():
self.bad_sector_check_check_box.Disable()
else:
self.bad_sector_check_check_box.Enable()
#Log output, and Make Summary checkboxes.
if self.make_summary_check_box.IsChecked():
self.log_output_checkbox.Enable()
self.log_output_checkbox.SetValue(True)
else:
self.log_output_checkbox.SetValue(False)
self.log_output_checkbox.Disable()
logger.debug("MainWindow().on_checkbox(): Done. Calling self.save_main_options()...")
self.save_main_options()
def bootloader_options(self, event=None): #pylint: disable=unused-argument
"""Show the Bootloader Options Window"""
#Safeguard program reliability (and continuity) by saving the settings first.
logger.debug("MainWindow().bootloader_options(): Calling self.save_main_options()...")
self.save_main_options()
#Open the Bootloader Options window
logger.debug("MainWindow().bootloader_options(): Starting Bootloader Settings Window...")
self.Hide()
BootloaderOptionsWindow().Show()
def system_info(self, event=None): #pylint: disable=unused-argument,no-self-use
"""Start SystemInfoWindow"""
logger.debug("MainWindow().system_info(): Starting System Info Window...")
SystemInfoWindow().Show()
def show_privacypolicy(self, event=None): #pylint: disable=unused-argument,no-self-use
"""Show PrivPolWindow"""
PrivPolWindow().Show()
def progress_window(self, event=None): #pylint: disable=unused-argument,no-self-use
"""Starts Progress Window"""
logger.debug("MainWindow().progress_window(): Starting Progress Window...")
self.save_main_options()
progress_frame = ProgressWindow()
APP.SetTopWindow(progress_frame)
progress_frame.Show(True)
self.Destroy()
def refresh_main_window(self):
"""Refresh the main window to reflect changes in the options, or after a restart."""
logger.debug("MainWindow().refresh_main_window(): Refreshing MainWindow...")
self.check_filesystems_check_box.SetValue(SETTINGS["QuickFSCheck"])
self.bad_sector_check_check_box.SetValue(SETTINGS["BadSectorCheck"])
self.fullverbose_checkbox.SetValue(SETTINGS["FullVerbosity"])
self.make_summary_check_box.SetValue(SETTINGS["MakeSystemSummary"])
self.log_output_checkbox.SetValue(SETTINGS["SaveOutput"])
#Enable and Disable Checkboxes as necessary
self.on_checkbox()
#Reveal MainWindow
self.Show()
def check_for_updates(self, event=None, starting_up=False): #pylint: disable=unused-argument
"""
Check for updates using the plist-formatted update file
on my website. If some startup, only display info to the
user if there was an update. Otherwise (aka requested by user),
always display the information.
"""
logger.info("MainWindow().check_for_updates(): Checking for updates...")
CoreTools.send_notification("Checking for updates...")
try:
#Do it the better way w/ requests.
updateinfo = \
requests.get("https://www.hamishmb.com/files/updateinfo/wxfixboot.plist",
timeout=5)
#Raise an error if our status code was bad.
updateinfo.raise_for_status()
updateinfo = updateinfo.text
except requests.exceptions.RequestException:
#Flag to user.
CoreTools.send_notification("Failed to check for updates!")
#Also send a message dialog.
if not starting_up:
DialogTools.show_msg_dlg(kind="error", message="Couldn't check for updates!\n"
+ "Are you connected to the internet?")
return
#Process the update info.
infotext = ""
update_recommended = False
updateinfo = plistlib.loads(updateinfo.encode())
#Determine the latest version for our kind of release.
if RELEASE_TYPE == "Stable":
#Compare your stable version to the current stable version.
versions = [VERSION, updateinfo["CurrentStableVersion"]]
elif RELEASE_TYPE == "Development":
#Compare your version to both dev and stable versions.
#This is in case a stable release has superseeded your dev release.
versions = [VERSION, updateinfo["CurrentStableVersion"],
updateinfo["CurrentDevVersion"]]
#Order the list so the last entry has the latest version number.
versions = sorted(versions, key=LooseVersion)
#Compare the versions.
if versions[-1] == VERSION and RELEASE_TYPE == "Stable":
#We have the latest stable version.
infotext += "You are running the latest version of WxFixBoot.\n"
elif versions[-1] == VERSION and RELEASE_TYPE == "Development":
#We have the latest dev version.
infotext += "You are running the latest development version of WxFixBoot.\n"
elif VERSION == updateinfo["CurrentStableVersion"] and RELEASE_TYPE == "Stable":
#We are running the latest stable version, but there is a dev version
#that is newer.
infotext += "You are running the latest version of WxFixBoot.\n"
elif VERSION == updateinfo["CurrentDevVersion"] and RELEASE_TYPE == "Development":
#We are running a development version, but it has been superseeded by a
#new stable release. We should update.
update_recommended = True
infotext += "You are running an old development version of WxFixBoot.\n"
infotext += "You should update to the newer, stable version "
infotext += updateinfo["CurrentStableVersion"]+".\n"
elif RELEASE_TYPE == "Development":
#We are running an old dev build. We should update.
update_recommended = True
infotext += "You are running an old development version of WxFixBoot.\n"
infotext += "You could update to the latest stable version "
infotext += updateinfo["CurrentStableVersion"]+",\n"
infotext += "or the latest development version "+updateinfo["CurrentDevVersion"]+".\n"
elif RELEASE_TYPE == "Stable":
#We are running an old stable build. We should update.
update_recommended = True
infotext += "You are running an old stable version of WxFixBoot.\n"
infotext += "You should update to the latest stable version "
infotext += updateinfo["CurrentStableVersion"]+".\n"
#Note if the release date doesn't match for the latest stable build.
if (RELEASE_TYPE == "Stable" and VERSION == updateinfo["CurrentStableVersion"]
and RELEASEDATE != updateinfo["CurrentStableReleaseDate"]):
infotext += "\nYour release date doesn't match that of the current stable version.\n"
infotext += "Are you running a git build?"
#Send a notification about the update status.
if update_recommended:
logger.warning("MainWindow().check_for_updates(): Update is recommended. "
"Sending notification...")
CoreTools.send_notification("Updates are available")
#Add info about where to download updates.
infotext += "\nThe latest version of WxFixBoot can be downloaded from:\n"
infotext += "https://www.hamishmb.com/html/downloads.php?program_name=WxFixBoot\n"
#Add info about new release.
infotext += "\nDetails of the new release:\n\n"
infotext += updateinfo["CurrentStableVersionDetails"]
#Note for pmagic users.
if PARTED_MAGIC:
infotext += "\nThere is probably a newer version of Parted Magic that "
infotext += "provides an update to this program."
else:
logger.warning("MainWindow().check_for_updates(): No update required."
" Sending notification...")
CoreTools.send_notification("Up to date")
#If asked by the user, or if there's an update and we aren't on pmagic,
#show the update status.
if not starting_up or (update_recommended and not PARTED_MAGIC):
logger.debug("MainWindow().check_for_updates(): Showing the user the update info...")
DialogTools.show_msg_dlg(kind="info", message=infotext)
def on_about(self, event=None): #pylint: disable=unused-argument
"""Shows the About Box"""
logger.debug("MainWindow().on_about(): Showing About Box...")
aboutbox = wxAboutDialogInfo()
aboutbox.Name = "WxFixBoot"
aboutbox.SetIcon(APPICON)
aboutbox.Version = VERSION
aboutbox.Copyright = "(C) 2013-2020 Hamish McIntyre-Bhatty"
aboutbox.Description = "Utility to fix the bootloader on a\ncomputer quickly " \
+ "\n\nPython version "+sys.version.split()[0] \
+ "\nwxPython version " + wx.version() \
+ "\nGetDevInfo version " + getdevinfo.getdevinfo.VERSION
aboutbox.WebSite = ("https://www.hamishmb.com", "My Website")
aboutbox.Developers = ["Hamish McIntyre-Bhatty"]
aboutbox.Artists = ["Bhuna https://www.instagram.com/bhuna42/"]
aboutbox.License = "WxFixBoot is free software: you can redistribute it and/or modify it" \
"\nunder the terms of the GNU General Public License version 3 or," \
"\nat your option, any later version.\n\nWxFixBoot is distributed " \
"in the hope that it will be useful,\nbut WITHOUT ANY WARRANTY; " \
"without even the implied warranty of\nMERCHANTABILITY or " \
"FITNESS FOR A PARTICULAR PURPOSE. See the\nGNU General Public " \
"License for more details.\n\nYou should have received a copy of " \
"the GNU General Public License\nalong with WxFixBoot. If not, " \
"see <http://www.gnu.org/licenses/>."
#Show the AboutBox.
wxAboutBox(aboutbox)
def setup_sizers(self):
"""Setup sizers for MainWindow"""
#Create the main sizer.
main_sizer = wx.BoxSizer(wx.VERTICAL)
#Create the check box and Logo sizer.
checkbox_and_logo_sizer = wx.BoxSizer(wx.HORIZONTAL)
#Create the check box sizer.
checkbox_sizer = wx.BoxSizer(wx.VERTICAL)
#Create the bottom button sizer.
bottom_button_sizer = wx.BoxSizer(wx.HORIZONTAL)
#Add items to the check box sizer.
checkbox_sizer.Add(self.bad_sector_check_check_box, 1, wx.BOTTOM, 10)
checkbox_sizer.Add(self.check_filesystems_check_box, 1, wx.BOTTOM, 10)
checkbox_sizer.Add(self.fullverbose_checkbox, 1, wx.BOTTOM, 10)
checkbox_sizer.Add(self.make_summary_check_box, 1, wx.BOTTOM, 10)
checkbox_sizer.Add(self.log_output_checkbox, 1, wx.BOTTOM, 10)
#Add items to the check box and logo sizer.
checkbox_and_logo_sizer.Add(checkbox_sizer, 2, wx.RIGHT, 10)
checkbox_and_logo_sizer.Add(self.logo, 1, wx.TOP|wx.LEFT, 10)
#Add items to the bottom button sizer.
bottom_button_sizer.Add(self.about_button, 1, wx.RIGHT|wx.EXPAND, 10)
bottom_button_sizer.Add(self.bootloader_options_button, 2, wx.RIGHT|wx.EXPAND, 10)
bottom_button_sizer.Add(self.exit_button, 1, wx.EXPAND)
#Add items to the main sizer.
main_sizer.Add(self.welcome_text, 10, wx.TOP|wx.BOTTOM|wx.CENTER, 10)
main_sizer.Add(self.settings_text, 10, wx.BOTTOM|wx.CENTER, 10)
main_sizer.Add(checkbox_and_logo_sizer, 36, wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, 5)
main_sizer.Add(self.apply_operations_button, 10, wx.BOTTOM|wx.CENTER, 10)
main_sizer.Add(bottom_button_sizer, 10, wx.BOTTOM|wx.LEFT|wx.RIGHT|wx.EXPAND, 10)
#Get the sizer set up for the frame.
self.panel.SetSizer(main_sizer)
main_sizer.SetMinSize(wx.Size(400, 300))
main_sizer.SetSizeHints(self)
def bind_events(self):
"""Bind all mainwindow events"""
self.Bind(wx.EVT_MENU, self.check_for_updates, self.menu_updates)
self.Bind(wx.EVT_MENU, self.on_about, self.menu_about)
self.Bind(wx.EVT_MENU, self.on_exit, self.menu_exit)
self.Bind(wx.EVT_CLOSE, self.on_exit)
self.Bind(wx.EVT_BUTTON, self.on_about, self.about_button)
self.Bind(wx.EVT_BUTTON, self.on_exit, self.exit_button)
self.Bind(wx.EVT_MENU, self.system_info, self.menu_systeminfo)
self.Bind(wx.EVT_MENU, self.show_privacypolicy, self.menu_privacy_policy)
self.Bind(wx.EVT_MENU, self.bootloader_options, self.menu_bootloader_options)
self.Bind(wx.EVT_BUTTON, self.bootloader_options, self.bootloader_options_button)
self.Bind(wx.EVT_BUTTON, self.progress_window, self.apply_operations_button)
#Checkboxes on the main window.
self.Bind(wx.EVT_CHECKBOX, self.on_checkbox, self.check_filesystems_check_box)
self.Bind(wx.EVT_CHECKBOX, self.on_checkbox, self.bad_sector_check_check_box)
self.Bind(wx.EVT_CHECKBOX, self.on_checkbox, self.make_summary_check_box)
def save_main_options(self):
"""Save all options"""
logger.debug("MainWindow().save_main_options(): Saving Options on MainWindow...")
#Bad Sector Check Choicebox
if self.bad_sector_check_check_box.IsChecked():
self.check_filesystems_check_box.Disable()
SETTINGS["BadSectorCheck"] = True
else:
self.check_filesystems_check_box.Enable()
SETTINGS["BadSectorCheck"] = False
#Quick Disk Check Choicebox
if self.check_filesystems_check_box.IsChecked():
self.bad_sector_check_check_box.Disable()
SETTINGS["QuickFSCheck"] = True
else:
self.bad_sector_check_check_box.Enable()