-
Notifications
You must be signed in to change notification settings - Fork 0
/
tftmenu.py
1673 lines (1591 loc) · 89.7 KB
/
tftmenu.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/python
##################################################################################
# IMPORTS
##################################################################################
import fcntl
import sys
import pygame.display
import pygame.freetype
#import tftpigame
import tfttemplates
from tftevdev import *
from tftbuttons import *
from tftutility import *
START_X_FILE = "/usr/bin/startx"
# Make sure application is running as root.
if not is_root():
logger.critical("Application must be run as root (with sudo)")
sys.exit(-1)
# Write out file with lock to ensure only one instance of application can run
lock_file = 'tftmenu.lock'
file_open = open(lock_file, 'w')
try:
fcntl.lockf(file_open, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
logger.critical("Only one instance of the application can run at a time.")
sys.exit(-1)
##################################################################################
# TFTMENUS DISPLAYS CLASS
##################################################################################
# Displays class responsible for the menu initialization and keeping track of
# current and last menus and states
##################################################################################
class Displays:
menus = {}
current = None
initial = None
last = None
shelled = None
started = False
screen = None
loop = True
loop_mode_shelled = False
display_type = None
initialized = False
splash_mute_level = None
libsdl_version = None
libsdl_build = None
event_device = None
##################################################################################
# DISPLAYS SHOW METHOD
##################################################################################
# Classmethod that shows any type of display by name or by object.
##################################################################################
@classmethod
def show(cls, item, data=None):
# If item to show is already a menu, then just render and set.
display = None
if isinstance(item, Display):
display = item
else:
if item in cls.menus:
display = cls.menus[item]
if display is not None:
if cls.current is None or display is not cls.current.last:
display.last = cls.current
if display.is_core:
Displays.last = display
display.render(data)
cls.current = display
else:
logger.warning("Unable to get valid display to show. Item: {0}, Data: {1}".format(item, data))
##################################################################################
# DISPLAYS SHOW METHOD
##################################################################################
# Classmethod that Shows a Splash screen enforcing any suppression flags that
# may be set.
##################################################################################
@classmethod
def show_splash(cls, splash_type, data=None):
if splash_type == SplashBuiltIn.Exit:
if not cls.splash_mute_level & SplashMuteLevel.Exit:
cls.show(SplashBuiltIn.Exit, data)
return True
elif splash_type == SplashBuiltIn.Info:
if not cls.splash_mute_level & SplashMuteLevel.Info:
cls.show(SplashBuiltIn.Info, data)
return True
elif splash_type == SplashBuiltIn.Warning:
if not cls.splash_mute_level & SplashMuteLevel.Warning:
cls.show(SplashBuiltIn.Warning, data)
return True
elif splash_type == SplashBuiltIn.Error:
if not cls.splash_mute_level & SplashMuteLevel.Error:
cls.show(SplashBuiltIn.Error, data)
return True
elif splash_type == SplashBuiltIn.Battery:
if not cls.splash_mute_level & SplashMuteLevel.Battery:
cls.show(SplashBuiltIn.Battery, data)
return True
else:
logger.warning("Splash type not found in built-in types. Splash Type: {0}".format(splash_type))
return False
logger.info("Item not shown due to splash mute level. Splash Type: {0}, Splash Mute Level: {1}".format(
splash_type, cls.splash_mute_level))
return False
##################################################################################
# DISPLAYS TIMEOUT_SLEEP METHOD
##################################################################################
# Callback method that occurs when the timeout is met on a non-Splash display.
# The screen is put to sleep when the timeout occurs.
##################################################################################
@classmethod
def timeout_sleep(cls):
# Turn out the backlight after timer expires
if Backlight.method != BacklightMethod.NoBacklight and not Backlight.is_screen_sleeping():
logger.debug("Timeout initiating Backlight Screen Sleep")
Backlight.screen_sleep()
##################################################################################
# DISPLAYS TIMEOUT_CLOSE METHOD
##################################################################################
# Callback method that occurs when the timeout on a Splash display occurs. The
# last core display is shown on timeout.
##################################################################################
@classmethod
def timeout_close(cls):
logger.debug("Timeout initiating Display Close")
cls.show(cls.get_last_core_display(cls.current))
##################################################################################
# DISPLAYS SHUTDOWN METHOD
##################################################################################
# Classmethod to shutdown the application. The method parameter indicates the
# type of shutdown. Normal indicates a standard exit from the program. Error
# indicates an unrecoverable error shutting down the program. Terminate when
# the OS or system indicates the application should shut down. Reboot and
# Shutdown are user initiated exits with a request to reboot or shutdown the
# system as well.
##################################################################################
@classmethod
def shutdown(cls, method, exit_splash=None, splash_data=None):
# method to shutdown application
logger.debug("Shutdown requested. Method: {0}, Exit Splash: {1}, Splash Data:{2}".
format(method, exit_splash, splash_data))
if cls.loop_mode_shelled:
logger.debug("Shutting down while in shelled mode.")
if Defaults.tft_type is not DISP22NT:
pygame.mouse.set_visible(False)
Displays.screen = pygame.display.set_mode(Defaults.tft_size)
if method == Shutdown.Terminate:
draw_true_rect(Displays.screen, Color.Black, 0, 0, Defaults.tft_width, Defaults.tft_height, 0)
pygame.display.flip()
if Backlight.method is not BacklightMethod.NoBacklight:
Backlight.screen_sleep()
else:
if exit_splash is not None:
not_muted = Displays.show_splash(exit_splash, splash_data)
else:
not_muted = Displays.show_splash(SplashBuiltIn.Exit)
if not not_muted:
Displays.show(SplashBuiltIn.Blank)
pygame.display.flip()
if Defaults.tft_type is DISP28C or Defaults.tft_type is DISP28CP:
cls.event_device.stop()
pygame.quit()
cls.started = False
if method is Shutdown.Shutdown:
subprocess.call(Command.Shutdown.split())
elif method is Shutdown.Reboot:
subprocess.call(Command.Reboot.split())
logger.debug("Exiting application.")
sys.exit(0)
##################################################################################
# DISPLAYS SHELL METHOD
##################################################################################
# Classmethod to show the TTY command line instead of the displays. This puts the
# tftmenu program into a state where it monitors only for the return from the
# shell indication (which is a long press on the screen.
##################################################################################
@classmethod
def shell(cls):
if Defaults.tft_type is DISP22NT:
logger.warning("Attempting shell on a non-touch display. Ignoring request.")
render_data = [SplashLine("WARNING", Defaults.default_splash_font_size_title),
SplashLine("Shell not permitted on non-touch display", wrap_text=True)]
cls.show_splash(SplashBuiltIn.Warning, render_data)
else:
logger.debug("Shelling to {0}".format(Screen.Tty))
cls.shelled = Displays.current
pygame.display.quit()
pygame.init()
# Set loop_mode_shelled which puts our event loop in shelled mode where
# only a long touch is detected
cls.loop_mode_shelled = True
##################################################################################
# DISPLAYS SHELL METHOD
##################################################################################
# Classmethod to start X on an HDMI or TFT display if X is installed on the system
##################################################################################
@classmethod
def start_x(cls, hdmi=False):
# Check if x is already running
if run_cmd(["pidof", "x"]) <= 0:
# if so, don't start it again and show warning
logger.warning("Attempting to start X, but x is already running.")
render_data = [SplashLine("WARNING", Defaults.default_splash_font_size_title),
SplashLine("X is already running.", wrap_text=True)]
cls.show_splash(SplashBuiltIn.Warning, render_data)
# Make sure StartX exists. It will not on Lite versions of Raspian
if os.path.isfile(START_X_FILE):
# Determine which FRAMEBUFFER to start it on.
if hdmi:
subprocess.call(Command.StartXHdmi)
else:
subprocess.call(Command.StartXTft)
return
else:
logger.warning("Attempting to start X but it could not be detected in default location: {0}"
.format(START_X_FILE))
render_data = [SplashLine("WARNING", Defaults.default_splash_font_size_title),
SplashLine("GUI is not installed on in expected location.", wrap_text=True)]
cls.show_splash(SplashBuiltIn.Warning, render_data)
##################################################################################
# DISPLAYS RESTORE METHOD
##################################################################################
# Classmethod used to restore the menu back from a shell.
##################################################################################
@classmethod
def restore(cls):
logger.debug("Restoring back from shell.")
send_wake_command()
if Defaults.tft_type is not DISP22NT:
pygame.mouse.set_visible(False)
Displays.screen = pygame.display.set_mode(Defaults.tft_size)
return_display = cls.get_last_core_display(Displays.shelled)
return_display.force_refresh = True
Displays.show(return_display)
cls.loop_mode_shelled = False
##################################################################################
# DISPLAYS SHELL METHOD
##################################################################################
# Callback method from a signal to shutdown the menu.
##################################################################################
@classmethod
def on_shutdown(cls, signum, frame):
logger.debug("Shutdown Signal Received. Signum:{0}, Frame:{1}".format(signum, frame))
cls.shutdown(Shutdown.Normal if signum is signal.SIGINT else Shutdown.Terminate)
##################################################################################
# GET_LAST_CORE_DISPLAY
##################################################################################
# This method iterates backwards from the current display to find the last display
# up the chain that is of class Display or Menu. This is used when closing a
# display or splash to ensure the close happens back to a core display type (not
# another splash or dialog) so that dialogs and splashes could be chained together
# and still "closed' back to a core display.
##################################################################################
@classmethod
def get_last_core_display(cls, start=None):
previous = cls.current.last if start is None else start
while previous is not None:
if previous.is_core:
logger.debug("Last Core Display detected normally. Display: {0}".format(previous))
return previous
# Avoid case where we get stuck in a loop
if previous.last == previous:
logger.debug("Last Core Display detected via loop prevention. Display: {0}".format(Displays.last))
return Displays.last
else:
previous = previous.last
return cls.initial
##################################################################################
# CHECK_LIB_SDL_VERSION
##################################################################################
# This method checks to see if libsdl1.2debian is installed and if the version is
# correct to enable touch on the Raspberry Pi.
##################################################################################
@classmethod
def check_lib_sdl_version(cls):
full_version = get_package_version(Package.PkgLibSdl)
if full_version is None:
return False
version_info = full_version.split("-")
lib_version = version_info[0].lstrip()
if len(version_info) > 1:
lib_build = version_info[1]
else:
lib_build = None
if lib_version == Package.LibSdlVersion and lib_build == Package.LibSdlBuild:
return True
cls.libsdl_build = lib_build
cls.libsdl_version = lib_version
return False
##################################################################################
# DISPLAYS INITIALIZE METHOD
##################################################################################
# Classmethod to initialize Displays class. Sets any defaults, the mute level of
# Splash displays and then the splash displays. Also initializes pygame and the
# touchscreen drivers.
@classmethod
def initialize(cls, tft_type, global_background_color=None, global_border_width=None, global_border_color=None,
global_font=None, global_font_size=None, global_font_color=None, global_font_h_padding=None,
global_font_v_padding=None, global_font_h_align=None, global_font_v_align=None,
splash_mute_level=SplashMuteLevel.NoMute, splash_timeout=Defaults.DEFAULT_SPLASH_TIMEOUT_MEDIUM):
# If a touch device is specified, make sure the LibSdl version is correct. If
# not, display a warning unless suppressed.
if tft_type is not DISP22NT:
cls.check_lib_sdl_version()
cls.splash_mute_level = splash_mute_level
# Set the defaults based on the resolution of the display. Fonts are scaled
# using the font resolutions setting which provides similar sized fonts for
# both the small and large displays.
logger.debug("Initializing Defaults")
Defaults.set_defaults(tft_type, global_background_color=global_background_color,
global_border_width=global_border_width, global_border_color=global_border_color,
global_font=global_font, global_font_size=global_font_size,
global_font_color=global_font_color, global_font_h_padding=global_font_h_padding,
global_font_v_padding=global_font_v_padding, global_font_h_align=global_font_h_align,
global_font_v_align=global_font_v_align)
cls.menus[SplashBuiltIn.Blank] = Splash(None, Color.Black, timeout=1)
logger.debug("Creating built-in Splash Displays. Splash Mule Level: {0}".format(cls.splash_mute_level))
if not cls.splash_mute_level & SplashMuteLevel.Exit:
# Create the internally used splash screens. First one is the exit screen splash
cls.menus[SplashBuiltIn.Exit] = Splash([
SplashLine("MENU CLOSING", Defaults.default_splash_font_size_title),
SplashLine("Please wait for a few seconds.", Defaults.default_splash_font_size)], Color.Green,
timeout=Defaults.DEFAULT_SPLASH_TIMEOUT_SHORT)
if not cls.splash_mute_level & SplashMuteLevel.Info:
# This creates the information screen splash used to pass non-critical information
cls.menus[SplashBuiltIn.Info] = Splash([
SplashLine("ATTENTION", Defaults.default_splash_font_size_title),
SplashLine("Unspecified Information", Defaults.default_splash_font_size)], Color.Blue,
timeout=splash_timeout)
if not cls.splash_mute_level & SplashMuteLevel.Warning:
# This creates the error screen splash used to indicate an warning
cls.menus[SplashBuiltIn.Warning] = Splash([
SplashLine("WARNING", Defaults.default_splash_font_size_title),
SplashLine("Unspecified Warning.", Defaults.default_splash_font_size)], Color.Orange,
timeout=splash_timeout)
if not cls.splash_mute_level & SplashMuteLevel.Warning and\
(cls.libsdl_version is not None or cls.libsdl_build is not None):
# This creates the error screen splash used to indicate a touch version dll warning
cls.menus[SplashBuiltIn.Touch] = Splash([
SplashLine("WARNING", Defaults.default_splash_font_size_title),
SplashLine("Touch may not work due to incompatible version {0}-{1} of libsdl1.2debian package.".format(
cls.libsdl_version, cls.libsdl_build),
Defaults.default_splash_font_size, wrap_text=True),
SplashLine("Run downgrade-sdl.sh to repair.", Defaults.default_splash_font_size,
font_color=Color.Black),
], Color.Orange,
timeout=10)
if not cls.splash_mute_level & SplashMuteLevel.Error:
# This creates the error screen splash used to indicate an error.
cls.menus[SplashBuiltIn.Error] = Splash([
SplashLine("ERROR", Defaults.default_splash_font_size_title),
SplashLine("Unspecified Error", Defaults.default_splash_font_size)], Color.Red,
timeout=splash_timeout)
if not cls.splash_mute_level & SplashMuteLevel.Battery:
# This creates the error screen splash used to indicate an low battery shutdown
cls.menus[SplashBuiltIn.Battery] = Splash([
SplashLine("LOW BATTERY", Defaults.default_splash_font_size_title, Color.Black),
SplashLine("System will shut down shortly.", Defaults.default_splash_font_size, Color.Black)],
Color.Yellow, timeout=Defaults.DEFAULT_SPLASH_TIMEOUT_LONG)
# Initialize touchscreen drivers
if Defaults.tft_type is not DISP22NT:
logger.debug("Initializing Touchscreen Drivers")
os.environ["SDL_FBDEV"] = Screen.FrameBuffDevTft
if Defaults.tft_type is DISP28C or Defaults.tft_type is DISP28CP:
os.environ["SDL_MOUSEDEV"] = Screen.NullInput
os.environ["SDL_MOUSEDRV"] = Screen.TouchDrvDummy
else:
os.environ["SDL_MOUSEDEV"] = Screen.TouchscreenInput
os.environ["SDL_MOUSEDRV"] = Screen.TouchDrvTslib
# Initialize pygame and hide mouse if not using a non-touch display
logger.debug("Initializing pygame")
pygame.init()
if Defaults.tft_type is DISP28C or Defaults.tft_type is DISP28CP:
cls.event_device = TftCapacitiveEvHandler()
cls.event_device.start(90)
if Defaults.tft_type is not DISP22NT:
pygame.mouse.set_visible(False)
logger.info("Initialization complete")
cls.initialized = True
##################################################################################
# DISPLAYS START METHOD
##################################################################################
# Classmethod called to start the menu Displays. The initial menu needs to be
# passed it, along with any settings for the backlight. The main execution loop
# then follows.
@classmethod
def start(cls, initial_menu, backlight_method=None, backlight_steps=None, backlight_default=None,
backlight_restore_last=False, backlight_state_sleep=False, backlight_auto=False, button_callback=None,
power_gpio=None, use_old_pwm=False, battery_gpio=None):
# Make sure start process has not already started.
if cls.started:
return
cls.started = True
button_down = 0
down_time = None
# Make sure initialization has been run
if not cls.initialized or Defaults.tft_type is None:
logger.error("Displays class not initialized.")
cls.started = False
raise NotInitializedException("Displays not initialized. Use initialize() method before start().")
# Add signals for shutdown from OS
signal.signal(signal.SIG_IGN, cls.on_shutdown)
signal.signal(signal.SIGINT, cls.on_shutdown)
signal.signal(signal.SIGTERM, cls.on_shutdown)
# Set display mode in pygame and set
cls.screen = pygame.display.set_mode(Defaults.tft_size)
try:
# Create TFTButtons
tft_buttons = GpioButtons(Defaults.tft_type, backlight_method=backlight_method,
backlight_steps=backlight_steps, backlight_default=backlight_default,
backlight_restore_last=backlight_restore_last, backlight_auto=backlight_auto,
backlight_state_sleep=backlight_state_sleep, use_old_pwm=use_old_pwm,
button_callback=button_callback, power_gpio=power_gpio, battery_gpio=battery_gpio)
# Show and set initial menu
Displays.initial = initial_menu
Displays.show(initial_menu)
if cls.libsdl_build is not None or cls.libsdl_version is not None:
if Defaults.tft_type is not DISP28CP and Defaults.tft_type is not DISP28C:
Displays.show(cls.menus[SplashBuiltIn.Touch])
##################################################################################
# Execution Wait Loop
##################################################################################
while cls.loop:
if Defaults.tft_type is DISP28C or Defaults.tft_type is DISP28CP:
cls.event_device.run()
if not cls.loop_mode_shelled:
# Scan touchscreen and keyboard events
for event in pygame.event.get():
# Mouse down or touch on screen
if event.type == MOUSEBUTTONDOWN:
Timer.reset()
if Backlight.method != BacklightMethod.NoBacklight and Backlight.is_screen_sleeping():
logger.debug("Button Down Ignored while screen is sleeping")
else:
pos = pygame.mouse.get_pos()
button_down = cls.current.process_down_button(cls.current.process_location(pos))
logger.debug("Button Down Event occurred in Button: {0}".format(button_down))
down_time = time.time()
# Mouse up or release on screen
elif event.type == MOUSEBUTTONUP:
Timer.reset()
if Backlight.method != BacklightMethod.NoBacklight and Backlight.is_screen_sleeping():
Backlight.screen_wake()
else:
# Need to send the screen wake on any mouse up or button press
# when Backlight.method == BacklightMethod.NoBacklight
if Backlight.method == BacklightMethod.NoBacklight:
logger.debug("Button Up waking screen while screen is sleeping")
Backlight.screen_wake()
pos = pygame.mouse.get_pos()
cls.current.process_up_button(button_down)
button_up = cls.current.process_location(pos)
logger.debug("Button Up Event occurred in Button: {0}".format(button_up))
# if the up button was the same as the down button, then process
# the button.
if button_up == button_down:
logger.debug("Button press occurred. Down Button: {0}, Up Button: {1}"
.format(button_down, button_up))
# Get the next menu and any associated data from the
# process_button method, then call Displays.show. If the
# menu is the same, it will not be re-rendered unless the
# force_render flag is set - this allows for the Splash and
# Dialog items to have changeable text
if time.time() - down_time > Times.RightClick or event.button == MouseButton.Right:
button_type = MouseButton.Right
else:
button_type = MouseButton.Left
next_menu, next_data = cls.current.process_button(button_up, button_type)
Displays.show(next_menu, next_data)
else:
logger.debug("Button press ignored. Down Button: {0}, Up Button: {1}"
.format(button_down, button_up))
# Reset the down button.
button_down = 0
elif event.type == KEYDOWN:
Timer.reset()
elif event.type == KEYUP:
Timer.reset()
if Backlight.method == BacklightMethod.NoBacklight or Backlight.is_screen_sleeping():
Backlight.screen_wake()
# Allow escape key to exit menu application
if event.key == K_ESCAPE:
logger.debug("Escape Key pressed")
cls.loop = False
else:
logger.debug("Ignored pygame event. Event: {0}".format(event.type))
# Check for expired timer. If so, execute all functions in the display's
# timeout_function.
if Timer.is_expired():
if cls.current.timeout_function is not None:
for timeout_function in cls.current.timeout_function:
timeout_function()
# If the display has a header attribute, call header update which will take
# care of refreshing the header if necessary
if hasattr(cls.current, Attributes.Header) and cls.current.header is not None:
cls.current.header.update(cls.current)
if hasattr(cls.current, Attributes.Footer) and cls.current.footer is not None:
cls.current.footer.update(cls.current)
cls.current.draw()
else:
for event in pygame.event.get():
# Mouse up or release on screen
if event.type == MOUSEBUTTONDOWN:
down_time = time.time()
if event.type == MOUSEBUTTONUP:
if time.time() - down_time > Times.RightClick or event.button == MouseButton.Right:
Displays.restore()
if tft_buttons.is_low_battery():
exit_splash = SplashBuiltIn.Battery
cls.shutdown(Shutdown.Shutdown, exit_splash)
# Sleep for a bit
time.sleep(Times.SleepLoop)
cls.shutdown(Shutdown.Normal)
# Catch Ctl-C Exit so error is not displayed
except KeyboardInterrupt:
# Keeps error from displaying when CTL-C is pressed
print(""),
except ShutdownInterrupt:
if Defaults.tft_type is DISP28C or Defaults.tft_type is DISP28CP:
cls.event_device.stop()
# Catch other Error
except Exception, ex:
# If we have an error,
exit_splash = SplashBuiltIn.Error
error_message = unicode(ex)
splash_data = [SplashLine("ERROR", Defaults.default_splash_font_size_title),
SplashLine(error_message, Defaults.default_splash_font_size, wrap_text=True)]
logger.error(error_message, exc_info=True)
cls.shutdown(Shutdown.Error, exit_splash, splash_data)
##################################################################################
# SHUTDOWNINTERUPT CLASS
##################################################################################
# Custom exception class used for killing threads.
##################################################################################
class ShutdownInterrupt(Exception):
pass
##################################################################################
# BASELINE LINE CLASS
##################################################################################
# Base class of all rendered text on the displays
##################################################################################
class BaseLine(object):
text = None
font_size = None
font_color = None
font = None
font_h_align = None
font_h_padding = None
font_style = None
font_v_align = None
font_v_padding = None
font_pad = None
##################################################################################
# BASELINE INIT METHOD
##################################################################################
# Initialize method of the BaseLine class. Unlike the other line classes, this
# one does not set any defaults.
##################################################################################
def __init__(self, text=None, font_size=None, font_color=None, font=None, font_style=None,
font_h_align=None, font_h_padding=None, font_v_align=None, font_v_padding=None, font_pad=False,
wrap_text=False):
self.text = text
self.font_size = font_size
self.font_color = font_color
self.font = font
self.font_style = font_style
self.font_h_align = font_h_align
self.font_h_padding = font_h_padding
self.font_v_align = font_v_align
self.font_v_padding = font_v_padding
self.font_pad = font_pad
self.wrap_text = wrap_text
##################################################################################
# BASELINE RENDER METHOD
##################################################################################
# Method to render the text of a BaseLine or derived object.
##################################################################################
def render(self, background_color=None):
if self.font is None:
self.font = pygame.freetype.Font(None, self.font_size, resolution=Defaults.default_font_resolution)
elif isinstance(self.font, pygame.freetype.Font):
self.font = pygame.freetype.Font(self.font.path, self.font_size,
resolution=Defaults.default_font_resolution)
else:
self.font = pygame.freetype.Font(self.font, self.font_size, resolution=Defaults.default_font_resolution)
self.font.style = self.font_style
self.font.pad = self.font_pad
if not self.wrap_text:
return self.font.render(self.text if self.text is not None else "", fgcolor=self.font_color)
else:
wrapped_text = ""
try:
wrapped_text = wrap_text_line(self.font, self.text if self.text is not None else "",
Defaults.tft_width - (self.font_h_padding * 2)
if not hasattr(Displays.current, "border_width")
else Defaults.tft_width - ((Displays.current.border_width +
self.font_h_padding) * 2))
except Exception, ex:
logger.error("Error occurred while attempting to wrap text. {0}".format(ex))
Displays.shutdown(Shutdown.Error, SplashBuiltIn.Error)
if len(wrapped_text[0]) is 1:
return self.font.render(wrapped_text[0][0] if wrapped_text[0][0] is not None else "",
fgcolor=self.font_color)
else:
surface_width = max(wrapped_text[2])
surface_height = sum(wrapped_text[1]) + (self.font_v_padding * (len(wrapped_text[0]) - 1))
text_surface = pygame.Surface((surface_width, surface_height))
if background_color is not None:
text_surface.fill(background_color)
text_top = 0
for index in range(0, len(wrapped_text[0])):
top = text_top
if self.font_h_align == TextHAlign.Left:
left = 0
elif self.font_h_align == TextHAlign.Right:
left = surface_width - 1 - int(wrapped_text[2][index])
else:
left = (surface_width / 2) - (int(wrapped_text[2][index]) / 2)
try:
self.font.render_to(text_surface, (left, top), wrapped_text[0][index], fgcolor=self.font_color)
except Exception, ex:
logger.error("Error occurred while attempting to render wrapped text. {0}".format(ex))
text_top += wrapped_text[1][index] + self.font_v_padding
return text_surface, text_surface.get_rect()
##################################################################################
# TFTMENU TEXT LINE CLASS
##################################################################################
# Text line class designed to be used for Display and Menu classes
##################################################################################
class TextLine(BaseLine):
##################################################################################
# TEXT LINE INIT METHOD
##################################################################################
# Initializes a Text Line item with the Text Line defaults
##################################################################################
def __init__(self, text=None, font_size=None, font_color=None, font=None, font_style=None,
font_h_align=None, font_h_padding=None, font_v_align=None, font_v_padding=None, font_pad=True,
wrap_text=False):
super(TextLine, self).__init__(text=text, font_size=font_size, font_color=font_color, font=font,
font_style=font_style, font_h_align=font_h_align, font_h_padding=font_h_padding,
font_v_align=font_v_align, font_v_padding=font_v_padding, font_pad=font_pad,
wrap_text=wrap_text)
if self.font is None:
self.font = Defaults.default_text_line_font
if self.font_color is None:
self.font_color = Defaults.default_text_line_font_color
if self.font_size is None:
self.font_size = Defaults.default_text_line_font_size
if self.font_style is None:
self.font_style = pygame.freetype.STYLE_NORMAL
if self.font_h_align is None:
self.font_h_align = Defaults.default_text_line_font_h_align
if self.font_v_align is None:
self.font_v_align = Defaults.default_text_line_font_v_align
if self.font_h_padding is None:
self.font_h_padding = Defaults.default_text_line_font_h_padding
if self.font_v_padding is None:
self.font_v_padding = Defaults.default_text_line_font_v_padding
##################################################################################
# TFTMENU SPLASH LINE CLASS
##################################################################################
# Splash line class designed to be used for Splash classes
##################################################################################
class SplashLine(BaseLine):
##################################################################################
# SPLASH LINE INIT METHOD
##################################################################################
# Initializes a Splash Line item with the Splash defaults
##################################################################################
def __init__(self, text=None, font_size=None, font_color=None, font=None, font_style=None,
font_h_align=None, font_h_padding=None, font_v_align=None, font_v_padding=None, font_pad=True,
wrap_text=False):
super(SplashLine, self).__init__(text=text, font_size=font_size, font_color=font_color, font=font,
font_style=font_style, font_h_align=font_h_align,
font_h_padding=font_h_padding, font_v_align=font_v_align,
font_v_padding=font_v_padding, font_pad=font_pad, wrap_text=wrap_text)
if self.font is None:
self.font = Defaults.default_splash_font
if self.font_color is None:
self.font_color = Defaults.default_splash_font_color
if self.font_size is None:
self.font_size = Defaults.default_splash_font_size
if self.font_style is None:
self.font_style = pygame.freetype.STYLE_NORMAL
if self.font_h_align is None:
self.font_h_align = Defaults.default_splash_font_h_align
if self.font_v_align is None:
self.font_v_align = Defaults.default_splash_font_v_align
if self.font_h_padding is None:
self.font_h_padding = Defaults.default_splash_font_h_padding
if self.font_v_padding is None:
self.font_v_padding = Defaults.default_splash_font_v_padding
##################################################################################
# TFTMENU DIALOG LINE CLASS
##################################################################################
# Dialog line class designed to be used for Dialog classes
##################################################################################
class DialogLine(BaseLine):
##################################################################################
# DIALOG LINE INIT METHOD
##################################################################################
# Initializes a Dialog Line item with the Dialog defaults
##################################################################################
def __init__(self, text=None, font_size=None, font_color=None, font=None, font_style=None,
font_h_align=None, font_h_padding=None, font_v_align=None, font_v_padding=None, font_pad=True,
wrap_text=False):
super(DialogLine, self).__init__(text=text, font_size=font_size, font_color=font_color, font=font,
font_style=font_style, font_h_align=font_h_align,
font_h_padding=font_h_padding, font_v_align=font_v_align,
font_v_padding=font_v_padding, font_pad=font_pad, wrap_text=wrap_text)
if self.font is None:
self.font = Defaults.default_dialog_font
if self.font_color is None:
self.font_color = Defaults.default_dialog_font_color
if self.font_size is None:
self.font_size = Defaults.default_dialog_font_size
if self.font_style is None:
self.font_style = pygame.freetype.STYLE_NORMAL
if self.font_h_align is None:
self.font_h_align = Defaults.default_dialog_font_h_align
if self.font_v_align is None:
self.font_v_align = Defaults.default_dialog_font_v_align
if self.font_h_padding is None:
self.font_h_padding = Defaults.default_dialog_font_h_padding
if self.font_v_padding is None:
self.font_v_padding = Defaults.default_dialog_font_v_padding
##################################################################################
# TFTMENU HEAD/FOOT LINE CLASS
##################################################################################
# Head/Foot line class designed to be used for Header and Footer classes within
# other displays.
##################################################################################
class HeadFootLine(BaseLine):
##################################################################################
# HEAD/FOOT LINE INIT METHOD
##################################################################################
# Initializes a Head/Foot Line item with the Head/Foot defaults
##################################################################################
def __init__(self, text=None, font_size=None, font_color=None, font=None, font_style=None,
font_h_align=None, font_h_padding=None, font_v_align=None, font_v_padding=None, font_pad=True,
wrap_text=False):
super(HeadFootLine, self).__init__(text=text, font_size=font_size, font_color=font_color, font=font,
font_style=font_style, font_h_align=font_h_align,
font_h_padding=font_h_padding, font_v_align=font_v_align,
font_v_padding=font_v_padding, font_pad=font_pad, wrap_text=wrap_text)
if self.font is None:
self.font = Defaults.default_headfoot_font
if self.font_color is None:
self.font_color = Defaults.default_headfoot_font_color
if self.font_size is None:
self.font_size = Defaults.default_headfoot_font_size
if self.font_style is None:
self.font_style = pygame.freetype.STYLE_NORMAL
if self.font_h_align is None:
self.font_h_align = Defaults.default_headfoot_font_h_align
if self.font_v_align is None:
self.font_v_align = Defaults.default_headfoot_font_v_align
if self.font_h_padding is None:
self.font_h_padding = Defaults.default_headfoot_font_h_padding
if self.font_v_padding is None:
self.font_v_padding = Defaults.default_headfoot_font_v_padding
##################################################################################
# TFTMENU BUTTON LINE CLASS
##################################################################################
# Button line class designed to be used for Button classes
##################################################################################
class ButtonLine(BaseLine):
##################################################################################
# BUTTON LINE INIT METHOD
##################################################################################
# Initializes a Button Line item with the Button defaults
##################################################################################
def __init__(self, text=None, font_size=None, font_color=None, font=None, font_style=None,
font_h_align=None, font_h_padding=None, font_v_align=None, font_v_padding=None, font_pad=True,
wrap_text=False):
super(ButtonLine, self).__init__(text=text, font_size=font_size, font_color=font_color, font=font,
font_style=font_style, font_h_align=font_h_align,
font_h_padding=font_h_padding, font_v_align=font_v_align,
font_v_padding=font_v_padding, font_pad=font_pad, wrap_text=wrap_text)
if self.font is None:
self.font = Defaults.default_button_font
if self.font_color is None:
self.font_color = Defaults.default_button_font_color
if self.font_size is None:
self.font_size = Defaults.default_button_font_size
if self.font_style is None:
self.font_style = pygame.freetype.STYLE_NORMAL
if self.font_h_align is None:
self.font_h_align = Defaults.default_button_font_h_align
if self.font_v_align is None:
self.font_v_align = Defaults.default_button_font_v_align
if self.font_h_padding is None:
self.font_h_padding = Defaults.default_button_font_h_padding
if self.font_v_padding is None:
self.font_v_padding = Defaults.default_button_font_v_padding
##################################################################################
# TFTMENU ACTION CLASS
##################################################################################
# Class to hold the information about a soft button action
##################################################################################
class Action(object):
action = None
data = None
render_data = None
##################################################################################
# ACTION INIT METHOD
##################################################################################
# Sets soft-Button Action properties to defaults.
##################################################################################
def __init__(self, action=DisplayAction.NoAction, data=None, render_data=None):
self.action = action
self.data = data
self.render_data = render_data
##################################################################################
# TFTMENU DISPLAY CLASS
##################################################################################
# Base Class for all displays in the menu system. The Display class is the base
# menu item that can be used for menus without a header and/or footer. It's main
# purpose is to display buttons. It is a core display.
##################################################################################
class Display(object):
background_color = None
border_color = None
border_width = 0
buttons = []
actions = []
timeout = 0
timeout_function = None
draw_callback = []
last = None
force_refresh = False
is_core = False
##################################################################################
# DISPLAY INIT METHOD
##################################################################################
# Initialize the Display class with defaults
##################################################################################
def __init__(self, background_color=Defaults.default_background_color,
border_color=Defaults.default_border_color, border_width=None,
buttons=None, actions=None, timeout=Defaults.default_timeout, timeout_function=None,
draw_callback=None):
self.background_color = background_color
self.border_color = border_color
self.border_width = border_width
self.buttons = array_single_none(buttons)
self.actions = array_single_none(actions)
self.timeout = timeout
self.timeout_function = merge(Displays.timeout_sleep, timeout_function)
if self.border_width is None:
self.border_width = Defaults.default_border_width
self.draw_callback = array_single_none(draw_callback)
self.is_core = True
##################################################################################
# DISPLAY RENDER METHOD
##################################################################################
# Method for rendering Display and Menu items. Set the screen to the background
# color, draws the border, renders any header of footer and finally renders the
# buttons and sets any screen timeout.
##################################################################################
def render(self, data=None):
# No need to render unless current display
if Displays.current == self and not self.force_refresh:
return
self.force_refresh = False
# Fill with background color
Displays.screen.fill(self.background_color)
# Draw Border
draw_true_rect(Displays.screen, self.border_color, 0, 0, Defaults.tft_width - 1, Defaults.tft_height - 1,
self.border_width)
# Draw Header
if hasattr(self, 'header'):
if self.header is not None:
self.header.render(self)
if hasattr(self, 'footer'):
if self.footer is not None:
self.footer.render(self)
# Draw Buttons
self.render_buttons()
# Update Screen
pygame.display.flip()
# Set Timeout
Timer.timeout(self.timeout)
Backlight.screen_wake()
##################################################################################
# DISPLAYS RENDER_BUTTONS METHOD
##################################################################################
# Method that loops through the buttons in class to be rendered and calls the
# Button render function for each.
##################################################################################
def render_buttons(self):
for button in self.buttons:
if button is not None:
button.render()
##################################################################################
# DISPLAYS PROCESS_LOCATION METHOD
##################################################################################
# Method that takes a pygame touch event and returns the button id that contained
# the touch hit.
##################################################################################
def process_location(self, position):
x = position[0]
y = position[1]
hit = 0
count = 0
for menuButton in self.buttons:
count += 1
if menuButton.x <= x <= menuButton.x + menuButton.width and\
(y >= menuButton.y and (y <= menuButton.y + menuButton.height)):
hit = count
break
return hit
##################################################################################
# DISPLAYS PROCESS_DOWN_BUTTON METHOD
##################################################################################
# Method that processes a button press by displaying the button in the button
# down state (filled in background).
##################################################################################
def process_down_button(self, button_index):
if button_index == 0:
return button_index
button = self.buttons[button_index - 1]
if button is not None:
if not (isinstance(Displays.current, Dialog) and Displays.current.dialog_type is DialogStyle.FullScreenOk):
button_rect = button.render(True)
if button_rect:
pygame.display.update(button_rect)
return button_index
else:
return 0
##################################################################################
# DISPLAYS PROCESS_UP_BUTTON METHOD
##################################################################################
# Method the processes a button up release by rendering the button back to the
# outline only state.
##################################################################################
def process_up_button(self, button_index):
if button_index == 0:
return
button = self.buttons[button_index - 1]
if button is not None:
button_rect = button.render()
if button_rect:
pygame.display.update(button_rect)
##################################################################################