-
-
Notifications
You must be signed in to change notification settings - Fork 40
Expand file tree
/
Copy pathbuskill_gui.py
More file actions
executable file
·1487 lines (1150 loc) · 50.8 KB
/
Copy pathbuskill_gui.py
File metadata and controls
executable file
·1487 lines (1150 loc) · 50.8 KB
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
"""
::
File: buskill_gui.py
Authors: Michael Altfield <michael@buskill.in>
Created: 2020-06-23
Updated: 2026-06-02
Version: 0.6
This is the code to launch the BusKill GUI app
For more info, see: https://buskill.in/
"""
################################################################################
# IMPORTS #
################################################################################
import packages.buskill
from packages.garden.navigationdrawer import NavigationDrawer
from packages.garden.progressspinner import ProgressSpinner
from buskill_version import BUSKILL_VERSION
import os, sys, re, webbrowser, json, operator, importlib
import multiprocessing, threading
from multiprocessing import util
import logging
logger = logging.getLogger( __name__ )
util.get_logger().setLevel(util.DEBUG)
multiprocessing.log_to_stderr().setLevel( logging.DEBUG )
#from multiprocessing import get_context
import kivy
from kivy.app import App
from kivy.properties import ObjectProperty, StringProperty
from kivy.clock import Clock
from kivy.metrics import dp
from kivy.compat import string_types, text_type
from kivy.animation import Animation
from kivy.core.text import LabelBase
from kivy.core.text import Label as CoreLabel
from kivy.core.clipboard import Clipboard
from kivy.core.window import Window
Window.size = ( 300, 500 )
# grey background color
Window.clearcolor = [ 0.188, 0.188, 0.188, 1 ]
from kivy.config import Config
from kivy.config import ConfigParser
from kivy.uix.widget import Widget
from kivy.uix.label import Label
from kivy.uix.button import Button
from kivy.uix.gridlayout import GridLayout
from kivy.uix.boxlayout import BoxLayout
from kivy.uix.floatlayout import FloatLayout
from kivy.uix.modalview import ModalView
from kivy.uix.popup import Popup
from kivy.uix.togglebutton import ToggleButton
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.actionbar import ActionView
from kivy.uix.settings import Settings, SettingSpacer
from kivy.properties import ObjectProperty, StringProperty, ListProperty, BooleanProperty, NumericProperty, DictProperty
from kivy.uix.recycleview import RecycleView
################################################################################
# SETTINGS #
################################################################################
# n/a
################################################################################
# FUNCTIONS #
################################################################################
# TODO: figure out why dialog's Label fonts aren't being updated
# TODO: update this to also update RecycleView's data dicts
def update_font_recursive(widget):
# is widget actually a list of widgets?
if type(widget) == type(list()) \
or isinstance(widget, kivy.properties.ObservableList):
# they sent us a list of widgets; call ourselves for each
for w in widget:
update_font_recursive(w)
if hasattr(widget, 'dialog'):
update_font_recursive(widget.dialog)
if isinstance(widget, Label):
default_font = Config.get('kivy', 'default_font')
# is this value actually a list?
if type(default_font) == type(list()):
font_name = default_font[0]
font_path = default_font[1]
else:
# the default_font setting is not a list; it's probably a string that
# represents a list
try:
# hack to convert a string of a list to an actual list
# * https://stackoverflow.com/a/35461204/1174102
default_font = json.loads(default_font.replace('\'', '"'))
font_name = default_font[0]
font_path = default_font[1]
except Exception as e:
pass
widget.font_name = font_path
elif hasattr(widget, 'children'):
for child in widget.children:
update_font_recursive(child)
################################################################################
# CLASSES #
################################################################################
class MainWindow(Screen):
toggle_btn = ObjectProperty(None)
status = ObjectProperty(None)
menu = ObjectProperty(None)
actionview = ObjectProperty(None)
actionbar = ObjectProperty(None)
dialog = None
def __init__(self, **kwargs):
# check to see if this is an old version that was already upgraded
# as soon as we've loaded
Clock.schedule_once(self.handle_upgrades, 1)
super(MainWindow, self).__init__(**kwargs)
def on_pre_enter( self, *args ):
msg = "DEBUG: User switched to 'MainWindow' screen"
print( msg ); logger.debug( msg )
# set the bk object to the BusKillApp's bk object
# note we can't set this in __init__() because that's too early. the
# 'root_app' instance field is manually set by the BusKillApp object
# after this Screen instances is created but before it's added with
# add_widget()
self.bk = self.root_app.bk
# called to close the app
def close( self, *args ):
sys.exit(0)
def toggle_menu(self):
self.nav_drawer.toggle_state()
def toggle_buskill(self):
try:
# attempt to tell the buskill object to arm/disarm
self.bk.toggle()
except Exception as e:
# buskill failed to arm/disarm; tell the user
msg = "Unable to toggle buskill state"
# for some reason 'e' is sometimes undefined, but we can get the
# exception thrown by the child process from its 'exception'
# instance field
if e:
msg += "\n\nException: " +str(e)
if self.bk.usb_handler.exception[0]:
msg += "\n\nException: " +str(self.bk.usb_handler.exception[0])
print( msg )
self.dialog = DialogConfirmation(
title = '[font=mdicons][size=30]\ue002[/size][/font] Error',
body = msg,
button='',
continue_function = None
)
self.dialog.b_cancel.text = "OK"
self.dialog.open()
return False
if self.bk.is_armed:
self.toggle_btn.text = 'Disarm'
self.status.text = "BusKill is armed\n"
self.status.text += "with '" +str(self.bk.trigger)+ "' trigger."
self.toggle_btn.background_color = self.color_red
# set the actionview of every actionbar of every screen to red
for screen in BusKillApp.manager.screens:
for child in screen.actionbar.children:
if type(child) == ActionView:
child.background_color = self.color_red
# check for messages from the usb_handler child process
Clock.schedule_interval( self.bk.check_usb_handler, 0.01 )
else:
self.toggle_btn.text = 'Arm'
self.status.text = "BusKill is disarmed.\n"
self.toggle_btn.background_color = self.color_primary
# set the actionview of every actionbar of every screen back to the
# app's primary color
for screen in BusKillApp.manager.screens:
for child in screen.actionbar.children:
if type(child) == ActionView:
child.background_color = self.color_primary
# stop checking for messages from the usb_handler child process
Clock.unschedule( self.bk.check_usb_handler )
def switchToScreen( self, screen ):
BusKillApp.manager.current = screen
def handle_upgrades( self, dt ):
if self.bk.UPGRADED_TO:
# the buskill app has already been updated; let's prompt the user to
# restart to *that* version instead of this outdated version
self.upgrade4_restart_prompt()
# TODO: fix the restart on Windows so that the recursive delete after
# upgrade works and doesn't require a manual restart. See also:
# * packages/buskill/__init__()'s UPGRADED_FROM['DELETE_FAILED']
# * buskill_gui.py's upgrade5_restart()
elif self.bk.UPGRADED_FROM and self.bk.UPGRADED_FROM['DELETE_FAILED']:
# the buskill app was just updated, but it failed to delete the old
# version. when this happens, we need the user to manually restart
# close the dialog if it's already opened
if self.dialog != None:
self.dialog.dismiss()
# open a new dialog that tells the user the error that occurred
new_version_exe = bk.EXE_PATH
msg = "To complete the update, this app must be manually restarted. Click to restart, then manually execute the new version at the following location.\n\n" + str(new_version_exe)
self.dialog = DialogConfirmation(
title = '[font=mdicons][size=30]\ue923[/size][/font] Restart Required',
body = msg,
button = "",
continue_function=None
)
self.dialog.b_cancel.text = "Exit Now"
self.dialog.b_cancel.on_release = self.close
self.dialog.auto_dismiss = False
self.dialog.open()
def about_ref_press(self, ref):
if ref == 'gui_help':
return self.webbrowser_open_url( bk.url_documentation_gui )
elif ref == 'contribute':
return self.webbrowser_open_url( bk.url_documentation_contribute )
return self.webbrowser_open_url( bk.url_website )
def webbrowser_open_url(self, url ):
msg = "DEBUG: Opening URL in webbrowser = " +str(url)
print( msg ); logger.debug( msg )
webbrowser.open( url )
def about(self):
# first close the navigation drawer
self.nav_drawer.toggle_state()
msg = "For latest news about BusKill, see our website at [ref=website][u]https://buskill.in[/u][/ref]\n\n"
msg+= "For help, see our documentation at [ref=gui_help][u]https://docs.buskill.in[/u][/ref]\n\n"
msg+= "Want to help? See [ref=contribute][u]contributing[/u][/ref]"
self.dialog = DialogConfirmation(
title='BusKill ' +str(BUSKILL_VERSION['VERSION']),
body = msg,
button = "",
continue_function = None,
)
self.dialog.b_cancel.text = "OK"
self.dialog.l_body.on_ref_press = self.about_ref_press
self.dialog.open()
def upgrade1(self):
# first close the navigation drawer
self.nav_drawer.toggle_state()
# check to see if an upgrade was already done
if self.bk.UPGRADED_TO and self.bk.UPGRADED_TO['EXE_PATH'] != '1':
# a newer version has already been installed; skip upgrade() step and
# just prompt the user to restart to the newer version
msg = "DEBUG: Detected upgrade already installed " +str(self.bk.UPGRADED_TO)
print( msg ); logger.debug( msg )
self.upgrade4_restart_prompt()
return
msg = "Checking for updates requires internet access.\n\n"
msg+= "Would you like to check for updates now?"
self.dialog = DialogConfirmation(
title='Check for Updates?',
body = msg,
button='Check Updates',
continue_function=self.upgrade2,
)
self.dialog.open()
def upgrade2(self):
# close the dialog if it's already opened
if self.dialog != None:
self.dialog.dismiss()
# open a new dialog with a spinning progress circle that tells the user
# to wait for upgrade() to finish
msg = "Please wait while we check for updates and download the latest version of BusKill."
self.dialog = DialogConfirmation(
title='Updating BusKill',
body = msg,
button = "",
continue_function=None,
)
self.dialog.b_cancel.on_release = self.upgrade_cancel
self.dialog.auto_dismiss = False
progress_spinner = ProgressSpinner(
color = self.color_primary,
)
self.dialog.dialog_contents.add_widget( progress_spinner, 2 )
self.dialog.dialog_contents.add_widget( Label( text='' ), 2 )
self.dialog.size_hint = (0.9,0.9)
self.dialog.open()
# TODO: split this upgrade function into update() and upgrade() and
# make the status somehow accessible from here so we can put it in a modal
# Call the upgrade_bg() function which executes the upgrade() function in
# an asynchronous process so it doesn't block the UI
self.bk.upgrade_bg()
# Register the upgrade3_tick() function as a callback to be executed
# every second, and we'll use that to update the UI with a status
# message from the upgrade() process and check to see if it the upgrade
# finished running
Clock.schedule_interval(self.upgrade3_tick, 1)
# cancel the upgrade()
def upgrade_cancel( self ):
Clock.unschedule( self.upgrade3_tick )
print( self.bk.upgrade_bg_terminate() )
# this is the callback function that will be executed every one second
# while buskill's upgrade() method is running
def upgrade3_tick( self, dt ):
print( "called upgrade3_tick()" )
# update the dialog
self.dialog.l_body.text = self.bk.get_upgrade_status()
# did the upgrade process finish?
if self.bk.upgrade_is_finished():
# the call to upgrade() finished.
Clock.unschedule( self.upgrade3_tick )
try:
self.upgrade_result = self.bk.get_upgrade_result()
except Exception as e:
# if the upgrade failed for some reason, alert the user
# close the dialog if it's already opened
if self.dialog != None:
self.dialog.dismiss()
# open a new dialog that tells the user the error that occurred
self.dialog = DialogConfirmation(
title = '[font=mdicons][size=30]\ue002[/size][/font] Update Failed!',
body = str(e),
button = "",
continue_function=None
)
self.dialog.b_cancel.text = "OK"
self.dialog.open()
return
# cleanup the pool used to launch upgrade() asynchronously asap
# self.upgrade_pool.close()
# self.upgrade_pool.join()
# 1 = poll was successful; we're on the latest version
if self.upgrade_result == '1':
# close the dialog if it's already opened
if self.dialog != None:
self.dialog.dismiss()
# open a new dialog that tells the user that they're already
# running the latest version
self.dialog = DialogConfirmation(
title = '[font=mdicons][size=30]\ue92f[/size][/font] Update BusKill',
body = "You're currently using the latest version",
button = "",
continue_function=None
)
self.dialog.b_cancel.text = "OK"
self.dialog.open()
return
# if we made it this far, it means that the we successfully finished
# downloading and installing the latest possible version, and the
# result is the path to that new executable
self.upgrade4_restart_prompt()
def upgrade4_restart_prompt( self ):
# close the dialog if it's already opened
if self.dialog != None:
self.dialog.dismiss()
# open a new dialog that tells the user that the upgrade() was a
# success and gets confirmation from the user to restart the app
msg = "BusKill was updated successfully. Please restart this app to continue."
self.dialog = DialogConfirmation(
title = '[font=mdicons][size=30]\ue92f[/size][/font] Update Successful',
body = msg,
button='Restart Now',
continue_function = self.upgrade5_restart,
)
self.dialog.open()
def upgrade5_restart( self ):
if self.bk.UPGRADED_TO:
new_version_exe = self.bk.UPGRADED_TO['EXE_PATH']
else:
new_version_exe = self.upgrade_result
msg = "DEBUG: Exiting and launching " +str(new_version_exe)
print( msg ); logger.debug( msg )
# TODO: fix the restart on Windows so that the recursive delete after
# upgrade works and doesn't require a manual restart. See also:
# * packages/buskill/__init__()'s UPGRADED_FROM['DELETE_FAILED']
# * buskill_gui.py's handle_upgrades()
try:
# TODO: remove me (after fixing Windows restart fail)
msg = 'os.environ|' +str(os.environ)+ "|\n"
msg+= "DEBUG: os.environ['PATH']:|" +str(os.environ['PATH'])+ "|\n"
print( msg ); logger.debug( msg )
# cleanup env; remove references to now-old version
oldVersionPaths = [
#os.path.split( sys.argv[0] )[0],
sys.argv[0].split( os.sep )[-2],
os.path.split( self.bk.APP_DIR )[1]
]
# TODO: remove me (after fixing Windows restart fail)
msg = 'DEBUG: removing oldVersionPaths from PATH (' +str(oldVersionPaths)+ ')'
print( msg ); logger.debug( msg )
os.environ['PATH'] = os.pathsep.join( [ path for path in os.environ['PATH'].split(os.pathsep) if not re.match( ".*(" +"|".join(oldVersionPaths)+ ").*", path) ] )
if 'SSL_CERT_FILE' in os.environ:
del os.environ['SSL_CERT_FILE']
# TODO: remove me (after fixing Windows restart fail)
msg = 'os.environ|' +str(os.environ)+ "|\n"
msg+= "DEBUG: os.environ['PATH']:|" +str(os.environ['PATH'])+ "|\n"
print( msg ); logger.debug( msg )
# replace this process with the newer version
self.bk.close()
os.execv( new_version_exe, [new_version_exe] )
except Exception as e:
msg = "DEBUG: Restart failed (" +str(e) + ")"
print( msg ); logger.debug( msg )
# close the dialog if it's already opened
if self.dialog != None:
self.dialog.dismiss()
# open a new dialog that tells the user the error that occurred
msg = "Sorry, we were unable to restart the BusKill App. Please execute it manually at the following location.\n\n" + str(new_version_exe)
self.dialog = DialogConfirmation(
title = '[font=mdicons][size=30]\ue002[/size][/font] Restart Error',
body = msg,
button = "",
continue_function=None
)
self.dialog.b_cancel.text = "OK"
self.dialog.open()
class DialogConfirmation(ModalView):
title = StringProperty(None)
body = StringProperty(None)
button = StringProperty(None)
continue_function = ObjectProperty(None)
b_continue = ObjectProperty(None)
def __init__(self, **kwargs):
self._parent = None
super(ModalView, self).__init__(**kwargs)
if self.button == "":
self.b_continue.parent.remove_widget( self.b_continue )
else:
self.b_continue.text = self.button
class CriticalError(BoxLayout):
msg = ObjectProperty(None)
def showError( self, msg ):
self.msg.text = msg
def fileBugReport( self ):
# TODO: make this a redirect on buskill.in so old versions aren't tied
# to github.com
webbrowser.open( 'https://docs.buskill.in/buskill-app/en/stable/support.html' )
###################
# SETTINGS SCREEN #
###################
# We heavily use (and expand on) the built-in Kivy Settings modules in BusKill
# * https://kivy-fork.readthedocs.io/en/latest/api-kivy.uix.settings.html
#
# Kivy's Settings module does the heavy lifting of populating the GUI Screen
# with Settings and Options that are defined in a json file, and then -- when
# the user changes the options for a setting -- writing those changes to a Kivy
# Config object, which writes them to disk in a .ini file.
#
# Note that a "Setting" is a key and an "Option" is a possible value for the
# Setting.
#
# The json file tells the GUI what Settings and Options to display, but does not
# store state. The user's chosen configuration of those settings is stored to
# the Config .ini file.
#
# See also https://github.com/BusKill/buskill-app/issues/16
# We define our own BusKillOptionItem, which is an OptionItem that will be used
# by the BusKillSettingComplexOptions class below
class BusKillOptionItem(FloatLayout):
radio_button_icon = StringProperty('C')
icon = StringProperty('')
title = StringProperty('')
desc = StringProperty('')
confirmation = StringProperty('')
value = ObjectProperty('')
option_human = StringProperty('')
parent_option = ObjectProperty()
screen = ObjectProperty()
def __init__(self, **kwargs):
#print( "called BusKillOptionItem.__init__()" )
super(BusKillOptionItem, self).__init__(**kwargs)
# hack to call another init function, but only *after* all the
# Kivy Properties are fully initialized
# * https://stackoverflow.com/questions/49935190/kivy-how-to-initialize-the-viewclass-of-the-recycleview-dynamically
Clock.schedule_once(self.init2,0)
# this is called when all the kivy properties have been set and the object
# is ready
# * https://stackoverflow.com/questions/49935190/kivy-how-to-initialize-the-viewclass-of-the-recycleview-dynamically
def init2(self, dt):
#print( "called init2() for |"+ str(self.value)+ "|" )
# the "main" screen
self.main_screen = BusKillApp.manager.get_screen('main')
# we steal (reuse) the instance field referencing the "modal dialog" from
# the "main" screen
self.dialog = self.main_screen.dialog
# loop through all the OptionItems in the RecycleView data and update
# the radio button icon to be "checked" or "unchecked" as needed
self.screen.update_data()
# this is called when the user clicks on this OptionItem (eg choosing the
# 'soft-shutdown' trigger)
def on_touch_up( self, touch ):
# skip this touch event if it wasn't *this* widget that was touched
# * https://kivy.org/doc/stable/guide/inputs.html#touch-event-basics
if not self.collide_point(*touch.pos):
return
# skip this touch event if it was actually a scroll event
# * https://stackoverflow.com/questions/78183125/scrolling-causes-click-on-touch-up-event-on-widgets-in-kivy-recycleview
if touch.button != "left":
return
# skip this touch event if they touched on an option that's already the
# enabled option
if self.parent_option.value == self.value:
msg="DEBUG: Option already equals '" +str(self.value)+ "'. Returning."
print( msg ); logger.debug( msg )
return
# does this option have a warning to prompt the user to confirm their
# selection before proceeding?
if self.confirmation == "":
# this option is safe; no confirmation is necessary
self.enable_option()
else:
# this option can be dangerous; confirm with user before continuing
self.dialog = DialogConfirmation(
title = '[font=mdicons][size=31]\ue002[/size][/font] Warning',
body = self.confirmation,
button='Continue',
continue_function=self.enable_option
)
self.dialog.b_cancel.text = "Cancel"
self.dialog.open()
# called when the user has chosen to change the setting to this option
def enable_option( self ):
if self.dialog != None:
self.dialog.dismiss()
# write change to disk in our persistent buskill .ini Config file
key = str(self.parent_option.key)
value = str(self.value)
msg="DEBUG: User changed config of '" +str(key)+ "' to '" +str(value)+ "'"
print( msg ); logger.debug( msg )
Config.set(self.parent_option.section, key, value)
Config.write()
# change the text of the option's value on the main Settings Screen
self.parent_option.value = self.value
# also handle the case where there's a human-readable value to set
if type(self.value) == type(list()):
self.parent_option.value_human = self.value[0]
# loop through all the OptionItems in the RecycleView data and update
# the radio button icon to be "checked" or "unchecked" as needed
self.screen.update_data()
# was the font what was just updated by the user?
if key == 'default_font':
# the user changed the font; now we need to change the widgets' font
# update fonts on all labels everywhere
update_font_recursive(BusKillApp.manager.screens)
# We define our own BusKillSettingItem, which is a SettingItem that will be used
# by the BusKillSettingComplexOptions class below. Note that we don't have code
# here because the difference between the SettingItem and our BusKillSettingItem
# is what's defined in the buskill.kv file. that's to say, it's all visual
class BusKillSettingItem(kivy.uix.settings.SettingItem):
pass
# Our BusKill app has this concept of a SettingItem that has "ComplexOptions"
#
# The closeset built-in Kivy SettingsItem type is a SettingOptions
# * https://kivy-fork.readthedocs.io/en/latest/api-kivy.uix.settings.html#kivy.uix.settings.SettingOptions
#
# SettingOptions just opens a simple modal that allows the user to choose one of
# many different options for the setting. But for setting a BusKill trigger,
# we wanted a whole new screen so that we could have more space to tell the user
# what each trigger does, and also have a help button on the screen to describe
# what a trigger means. Also, the whole "New Screen for an Option" is more
# in-line with Material Design.
# * https://m1.material.io/patterns/settings.html#settings-usage
#
# These are the reasons we create a special BusKillSettingComplexOptions class
class BusKillSettingComplexOptions(BusKillSettingItem):
# each of these properties directly cooresponds to the key in the json
# dictionary that's loaded with add_json_panel. the json file is what defines
# all of our settings that will be displayed on the Settings Screen
# icon defines the icon that's displayed on the Settings Screen for this
# setting
icon = ObjectProperty(None)
# value_human defines the human-readable value that's displayed on the
# Settings Screen for this setting
value_human = StringProperty(None)
# options is a parallel array of short names for different options for this
# setting (eg 'lock-screen')
options = ListProperty([])
# options_human is a parallel array of short human-readable values for
# different options for this setting (eg 'Lock Screen')
options_human = ListProperty([])
# options_long is a parallel array of short human-readable descriptions for
# different options for this setting (eg 'BusKill will lock your screen')
options_long = ListProperty([])
# options_icons is a parallel array of icons for different options for this
# setting. Note that this is distinct from the icon for the setting. the
# 'icon' variable defined above is for the setting (eg 'trigger') while the
# items in options_icons defines the icons for the options (possible values)
# for that setting (eg 'lock-screen' or 'soft-shutdown')
options_icons = ListProperty([])
# confirmation is a parallel array of "confirmation messages" for the
# different options for this setting. If a confirmation is set, then the user
# will be presented with a popup message asking if they want to proceed
# before the app will actually let them choose this option for this setting.
# this is useful, for example, before they choose a possibly-dangerous option
# (eg 'hard-shutdown'). If this is set to an empty string, then no
# confirmation is presented to the user when they select this option
confirmation = ListProperty([])
def __init__(self, **kwargs):
super(BusKillSettingComplexOptions, self).__init__(**kwargs)
# hack to call another init function, but only *after* all the
# Kivy Properties are fully initialized
# * https://stackoverflow.com/questions/49935190/kivy-how-to-initialize-the-viewclass-of-the-recycleview-dynamically
Clock.schedule_once(self.init2,0)
# this is called when all the kivy properties have been set and the object
# is ready
def init2(self, dt):
# is this value actually a list?
try:
# this value is a list, which means the first item in the list is our
# human-readable value to use in the GUI
# hack to convert a string of a list to an actual list
# * https://stackoverflow.com/a/35461204/1174102
value_as_list = json.loads(self.value.replace('\'', '"'))
self.value_human = value_as_list[0]
except Exception as e:
pass
def on_panel(self, instance, value):
if value is None:
return
self.fbind('on_release', self._choose_settings_screen)
def _choose_settings_screen(self, instance):
# create a new screen just for choosing the value of this setting, and
# name this new screen "setting_<key>"
screen_name = 'setting_' +self.key
# did we already create this sub-screen?
if not BusKillApp.manager.has_screen( screen_name ):
# there is no sub-screen for this Complex Option yet; create it
# create new screen for picking the value for this ComplexOption
setting_screen = ComplexOptionsScreen(
name = screen_name
)
# define the help message that should appear when the user clicks the
# help ActionButton on the top-right of the screen
setting_screen.set_help_msg( self.desc )
# set the color of the actionbar in this screen equal to whatever our
# setting's screen actionbar is set to (eg blue or red)
setting_screen.actionview.background_color = BusKillApp.manager.current_screen.actionview.background_color
# make the text in the actionbar match the 'title' for the setting as
# it's defined in the settings json file
setting_screen.set_actionbar_title( self.title )
# loop through all possible values for this ComplexOption, zipping out
# data from parallel arrays in the json file
for value, option_human, desc, confirmation, icon in zip(self.options, self.options_human, self.options_long, self.confirmation, self.options_icons):
# create an OptionItem for each of the possible values for this
# setting option, and add them to the new ComplexOption sub-screen
# via the ComplexOptionsScreen's Recycle View 'data' field
option_item = [{'title': self.key, 'value': value, 'option_human': option_human, 'radio_button_icon':'U', 'icon':icon, 'desc': desc, 'confirmation': confirmation, 'parent_option': self, 'screen': setting_screen }]
setting_screen.rv.data.extend(option_item)
# handle the "font" option
if self.key == 'default_font':
# first we must determine what fonts are available on this system
option_items = []
for font_path in BusKillApp.get_running_app().font_paths:
font_filename = os.path.basename( font_path )
font_human = font_filename
if font_filename.lower().endswith('.ttf') \
or font_filename.lower().endswith('.otf'):
font_human = font_filename[:-4]
option_items.append( {'title': 'default_font', 'value': [font_human, font_path, font_path, font_path], 'option_human': font_human, 'radio_button_icon': 'U', 'icon':'\ue167', 'desc':'', 'parent_option': self, 'screen': setting_screen } )
option_items.sort(key=operator.itemgetter('value'))
setting_screen.rv.data.extend(option_items)
# add the new ComplexOption sub-screen to the Screen Manager
BusKillApp.manager.add_widget( setting_screen )
# change into the sub-screen now
BusKillApp.manager.transition.direction = 'left'
BusKillApp.manager.current = screen_name
# We define BusKillSettings (which extends the built-in kivy Settings) so that
# we can add a new type of Setting = 'commplex-options'). The 'complex-options'
# type becomes a new 'type' that can be defined in our settings json file
class BusKillSettings(kivy.uix.settings.Settings):
def __init__(self, *args, **kargs):
super(BusKillSettings, self).__init__(*args, **kargs)
super(BusKillSettings, self).register_type('complex-options', BusKillSettingComplexOptions)
def on_touch_down( self, touch ):
super(BusKillSettings, self).on_touch_down(touch)
# Kivy's SettingsWithNoMenu is their simpler settings widget that doesn't
# include a navigation bar between differnt pages of settings. We extend that
# type with BusKillSettingsWithNoMenu so that we can use our custom
# BusKillSettings class (defined above) with our new 'complex-options' type
class BusKillSettingsWithNoMenu(BusKillSettings):
def __init__(self, *args, **kwargs):
self.interface_cls = kivy.uix.settings.ContentPanel
super(BusKillSettingsWithNoMenu,self).__init__( *args, **kwargs )
def on_touch_down( self, touch ):
super(BusKillSettingsWithNoMenu, self).on_touch_down( touch )
# The ComplexOptionsScreen is a sub-screen to the Settings Screen. Kivy doesn't
# have sub-screens for defining options, but that's what's expected in Material
# Design. We needed more space, so we created ComplexOption-type Settings. And
# this is the Screen where the user transitions-to to choose the options for a
# ComplexOption
class ComplexOptionsScreen(Screen):
actionview = ObjectProperty(None)
settings_content = ObjectProperty(None)
actionbar_title = ObjectProperty(None)
help_msg = ObjectProperty(None)
def set_help_msg(self, new_help_msg ):
self.help_msg = new_help_msg
def set_actionbar_title(self, new_title):
self.actionbar_title = new_title
def on_pre_enter(self, *args):
msg = "DEBUG: User switched to '" \
+str(BusKillApp.manager.current_screen.name)+ "' screen"
print( msg ); logger.debug( msg )
# the "main" screen
self.main_screen = BusKillApp.manager.get_screen('main')
# close the navigation drawer on the main screen
self.main_screen.nav_drawer.toggle_state()
# we steal (reuse) the instance field referencing the "modal dialog" from
# the "main" screen
self.dialog = self.main_screen.dialog
def show_help( self ):
self.dialog = DialogConfirmation(
title = '[font=mdicons][size=30]\ue88f[/size][/font] ' \
+ str(self.actionbar_title),
body = str(self.help_msg),
button = "",
continue_function=None
)
self.dialog.b_cancel.text = "OK"
self.dialog.open()
# update all of data dict in this Screen's RecycleView so that all of the
# widgets get updated on changes (eg the "radio button" icon)
def update_data(self):
# GET INFO
this_value = None
set_value = None
# get all of the widgets on this screen
widgets = [widget for widget in self.walk()]
# loop through all of the widgets until we get our first OptionItem
for widget in widgets:
# is this widget a BusKillOptionItem object?
if isinstance( widget, BusKillOptionItem ):
# get the title for this option (eg "trigger")
title = widget.title
# get the value that the user has actually set this option to
set_value = Config.get(widget.parent_option.section, title)
break
# UPDATE DATA
# loop through every dict of OptionItem data in the Recycle View's list
# of dicts
for n in range(0,len(self.rv.data)):
# get the value for this specific OptionItem
this_value = self.rv.data[n]['value']
if str(this_value) == str(set_value):
# this is the currently-set option
# set the radio button icon to "selected"
self.rv.data[n]['radio_button_icon'] = '[font=mdicons][size=18sp]\ue837[/size][/font] '
else:
# this is not the currently-set option
# set the radio button icon to "unselected"
self.rv.data[n]['radio_button_icon'] = '[font=mdicons][size=18sp]\ue836[/size][/font] '
# update RecycleView data in next frame
# * https://stackoverflow.com/questions/49935190/kivy-how-to-initialize-the-viewclass-of-the-recycleview-dynamically
Clock.schedule_once(self.rv.refresh_from_data,0)
# This is our main Screen when the user clicks "Settings" in the nav drawer
class BusKillSettingsScreen(Screen):
actionview = ObjectProperty(None)
def on_pre_enter(self, *args):
msg = "DEBUG: User switched to 'Settings' screen"
print( msg ); logger.debug( msg )
# set the bk object to the BusKillApp's bk object
# note we can't set this in __init__() because that's too early. the
# 'root_app' instance field is manually set by the BusKillApp object
# after this Screen instances is created but before it's added with
# add_widget()
self.bk = self.root_app.bk
# the "main" screen
self.main_screen = BusKillApp.manager.get_screen('main')
# close the navigation drawer on the main screen
self.main_screen.nav_drawer.toggle_state()
# we steal (reuse) the instance field referencing the "modal dialog" from
# the "main" screen
self.dialog = self.main_screen.dialog
# is the contents of 'settings_content' empty?
if self.settings_content.children == []:
# we haven't added the settings widget yet; add it now
# kivy's Settings module is designed to use many different kinds of
# "menus" (sidebars) for navigating different sections of the settings.
# while this is powerful, it conflicts with the Material Design spec,
# so we don't use it. Instead we use BusKillSettingsWithNoMenu, which
# inherets kivy's SettingsWithNoMenu and we add sub-screens for
# "ComplexOptions";
s = BusKillSettingsWithNoMenu()
s.root_app = self.root_app
# create a new Kivy SettingsPanel using Config (our buskill.ini config
# file) and a set of options to be drawn in the GUI as defined-by
# the 'settings_buskill.json' file
s.add_json_panel( 'buskill', Config, os.path.join(self.bk.SRC_DIR, 'packages', 'buskill', 'settings_buskill.json') )
# our BusKillSettingsWithNoMenu object's first child is an "interface"
# the add_json_panel() call above auto-pouplated that interface with
# a bunch of "ComplexOptions". Let's add those to the screen's contents
self.settings_content.add_widget( s )
# called when the user leaves the Settings screen
def on_pre_leave(self):