generated from relic-se/Fruit_Jam_Application
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcode.py
More file actions
1181 lines (993 loc) · 39.9 KB
/
code.py
File metadata and controls
1181 lines (993 loc) · 39.9 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
# SPDX-FileCopyrightText: 2025 Cooper Dalrymple (@relic-se)
#
# SPDX-License-Identifier: GPLv3
# load included modules if we aren't installed on the root path
if len(__file__.split("/")[:-1]) > 1:
lib_path = "/".join(__file__.split("/")[:-1]) + "/lib"
try:
import os
os.stat(lib_path)
except:
pass
else:
import sys
sys.path.append(lib_path)
import atexit
import displayio
import gc
import math
import os
import sys
import supervisor
from terminalio import FONT
import time
import json
from adafruit_anchored_group import AnchoredGroup
from adafruit_anchored_tilegrid import AnchoredTileGrid
from adafruit_button import Button
from adafruit_display_text.label import Label
from adafruit_display_text.text_box import TextBox
from adafruit_displayio_layout.layouts.grid_layout import GridLayout
import adafruit_fruitjam
import adafruit_fruitjam.network
import adafruit_fruitjam.peripherals
import adafruit_imageload
from adafruit_portalbase.network import HttpError
import adafruit_usb_host_mouse
from zipfile import ZipFile, BadZipFile
try:
import typing
except ImportError:
pass
# program constants
APPLICATIONS_DIR = "apps"
SCREENSAVERS_DIR = "screensavers"
CACHE_DIR = ".cache"
SCREENSAVERS_CATEGORY = "Screensavers"
APPLICATIONS_PATH = "applications.json" # used for testing
APPLICATIONS_URL = "https://raw.githubusercontent.com/relic-se/Fruit_Jam_Library/refs/heads/main/database/applications.json"
METADATA_URL = "https://raw.githubusercontent.com/{:s}/refs/heads/main/metadata.json"
REPO_URL = "https://api.github.com/repos/{:s}"
ICON_URL = "https://raw.githubusercontent.com/{:s}/{:s}/{:s}"
RELEASE_URL = "https://api.github.com/repos/{:s}/releases/latest"
BRANCH_DOWNLOAD_URL = "https://github.com/{:s}/archive/refs/heads/{:s}.zip"
MAJOR_VERSION = int(os.uname().release.split(".")[0])
VERSION_NAME = "CircuitPython {:d}.x".format(MAJOR_VERSION)
# prepare system
fj = adafruit_fruitjam.FruitJam() # setup peripherals and networking
def reset(timeout:int = 0) -> None:
if timeout > 0:
time.sleep(timeout)
fj.peripherals.deinit()
supervisor.reload()
SD_INSTALLED = fj.sd_check()
if not SD_INSTALLED:
print("SD card not mounted. Using internal flash storage.")
# file operations
def exists(path: str) -> bool:
try:
os.stat(path)
except:
return False
else:
return True
def mkdir(path: str, isfile: bool = False) -> bool:
parts = path.strip("/").split("/")
if isfile:
parts = parts[:-1]
for i in range(len(parts)):
dirpath = "/" + "/".join(parts[:i+1])
if not exists(dirpath):
os.mkdir(dirpath)
def rmtree(dirpath: str) -> None:
for name in os.listdir(dirpath):
filepath = dirpath + "/" + name
st_mode = os.stat(filepath)[0]
if st_mode & 0x8000:
os.remove(filepath)
elif st_mode & 0x4000:
rmtree(filepath)
os.rmdir(dirpath)
def extractall(zf: ZipFile, destination: str, source: str = "") -> None:
for srcinfo in zf.infolist():
if not srcinfo.filename.endswith("/") and srcinfo.filename.startswith(source + "/"):
destpath = destination + "/" + srcinfo.filename[len(source) + 1:]
mkdir(destpath, True)
with open(destpath, "wb") as destfile:
with zf.open(srcinfo.filename) as srcfile:
destfile.write(srcfile.read())
def get_path(path: str|list) -> str:
return "/" + "/".join(filter(lambda x: x, ["sd" if SD_INSTALLED else ""] + (path.split("/") if isinstance(path, str) else path)))
def get_application_directory(category: str = None) -> str:
if category is None:
category = selected_category
return SCREENSAVERS_DIR if category == SCREENSAVERS_CATEGORY else APPLICATIONS_DIR
def get_application_path(name: str, category: str = None) -> str:
return get_path([get_application_directory(category), name])
def get_application_file(name: str, category: str = None) -> str:
if category is None:
category = selected_category
return get_application_path(name, category) if category != SCREENSAVERS_CATEGORY else None
def is_application_installed(name: str, category: str = None) -> bool:
return exists(get_application_path(name, category))
# create necessary directories on sd card if they don't already exist
for dirname in (APPLICATIONS_DIR, SCREENSAVERS_DIR, CACHE_DIR):
mkdir(get_path(dirname))
# file download + caching
def _download_file(url: str, extension: str, name: str|None = None, cache: bool = True) -> str:
if not extension.startswith("."):
extension = "." + extension
if name is None:
name = url.split("/")[-1][:-len(extension)]
elif name.endswith(extension):
name = name[:-len(extension)]
path = get_path([CACHE_DIR, name + extension])
# remove file from cache if it exists and we're refreshing
if not cache and exists(path):
os.remove(path)
# download file if it doesn't already exist
if not cache or not exists(path):
fj.network.connect() # ensure we're connected to wifi
fj.network.wget(url, path)
# TODO: Cache duration
return path
def download_image(url: str, name: str|None = None, cache: bool = True) -> str:
return _download_file(
url=url,
extension=".bmp",
name=name,
cache=cache,
)
def download_json(url: str, name: str|None = None, cache: bool = True) -> str:
path = _download_file(
url=url,
extension=".json",
name=name,
cache=cache,
)
with open(path, "r") as f:
data = json.loads(f.read())
return data
def download_zip(url: str, name: str|None = None, cache: bool = True) -> str:
return _download_file(
url=url,
extension=".zip",
name=name,
cache=cache,
)
# get Fruit Jam OS config if available
try:
import launcher_config
config = launcher_config.LauncherConfig()
except ImportError:
config = None
bg_palette = displayio.Palette(1)
bg_palette[0] = config.palette_bg if config is not None else 0x222222
fg_palette = displayio.Palette(1)
fg_palette[0] = config.palette_fg if config is not None else 0xffffff
# setup display
try:
adafruit_fruitjam.peripherals.request_display_config() # user display configuration
except ValueError: # invalid user config or no user config provided
adafruit_fruitjam.peripherals.request_display_config(720, 400) # default display size
display = supervisor.runtime.display
# load images
default_icon_bmp, default_icon_palette = adafruit_imageload.load("bitmaps/default_icon.bmp")
default_icon_palette.make_transparent(0)
installed_bmp, installed_palette = adafruit_imageload.load("bitmaps/installed.bmp")
installed_palette.make_transparent(1)
installed_palette[0] = config.palette_bg if config is not None else 0x222222
installed_palette[2] = config.palette_fg if config is not None else 0xffffff
left_bmp, left_palette = adafruit_imageload.load("bitmaps/arrow_left.bmp")
left_palette.make_transparent(0)
right_bmp, right_palette = adafruit_imageload.load("bitmaps/arrow_right.bmp")
right_palette.make_transparent(0)
left_palette[2] = right_palette[2] = (config.palette_arrow if config is not None else 0x004abe)
exit_bmp, exit_palette = adafruit_imageload.load("bitmaps/exit.bmp")
exit_palette.make_transparent(0)
exit_palette[1] = config.palette_fg if config is not None else 0xffffff
# display constants
SCALE = 2 if display.width > 360 else 1
DISPLAY_WIDTH = display.width // SCALE
DISPLAY_HEIGHT = display.height // SCALE
TITLE_HEIGHT = 16
STATUS_HEIGHT = 16
STATUS_PADDING = 4
HELP_MARGIN = 1
MENU_HEIGHT = 24
MENU_GAP = 8
PAGE_COLUMNS = SCALE
PAGE_ROWS = 3
PAGE_SIZE = PAGE_COLUMNS * PAGE_ROWS
ARROW_MARGIN = 2
GRID_MARGIN = 8 * SCALE
GRID_WIDTH = display.width - GRID_MARGIN * 2 - (ARROW_MARGIN + left_bmp.width) * SCALE * 2
GRID_HEIGHT = display.height - TITLE_HEIGHT * SCALE - MENU_HEIGHT - GRID_MARGIN * 2 - STATUS_HEIGHT
ITEM_WIDTH = GRID_WIDTH // PAGE_COLUMNS
ITEM_HEIGHT = GRID_HEIGHT // PAGE_ROWS
DIALOG_MARGIN = 16 * SCALE
DIALOG_BORDER = SCALE
DIALOG_WIDTH = display.width - DIALOG_MARGIN * 2 - (ARROW_MARGIN + left_bmp.width) * SCALE * 2
DIALOG_HEIGHT = display.height - TITLE_HEIGHT * SCALE - DIALOG_MARGIN * 2 - STATUS_HEIGHT
DIALOG_BUTTON_WIDTH = DIALOG_WIDTH // SCALE // 4
BUTTON_PROPS = {
"height": MENU_HEIGHT,
"label_font": FONT,
"style": Button.ROUNDRECT,
"fill_color": (config.palette_bg if config is not None else 0x222222),
"label_color": (config.palette_fg if config is not None else 0xffffff),
"outline_color": (config.palette_fg if config is not None else 0xffffff),
"selected_fill": (config.palette_fg if config is not None else 0xffffff),
"selected_label": (config.palette_bg if config is not None else 0x222222),
"selected_outline": (config.palette_fg if config is not None else 0xffffff),
}
class ActionButton(Button):
def __init__(self, action: typing.Callable = None, **kwargs):
self._action = action
super().__init__(**kwargs)
def click(self) -> None:
if self._action is not None:
self.selected = True
self._action()
class TileGridButton(Button):
def __init__(self, bitmap: displayio.Bitmap = None, pixel_shader: displayio.PixelShader = None, pixel_shader_index: int = 0, **kwargs):
super().__init__(**kwargs)
self._pixel_shader_index = pixel_shader_index
self._tilegrid = AnchoredTileGrid(
bitmap=bitmap,
pixel_shader=pixel_shader,
)
self._tilegrid.anchor_point = (0.5, 0.5)
self._tilegrid.anchored_position = (self.width // 2, self.height // 2)
self._tilegrid.pixel_shader[pixel_shader_index] = self.label_color
self.append(self._tilegrid)
@property
def selected(self) -> bool:
return self._selected
@selected.setter
def selected(self, value: bool) -> None:
super().selected = value
self._tilegrid.pixel_shader[self._pixel_shader_index] = self.selected_label if value else self.label_color
# create groups
root_group = displayio.Group()
display.root_group = root_group
bg_tg = displayio.TileGrid(
bitmap=displayio.Bitmap(display.width, display.height, 1),
pixel_shader=bg_palette,
)
root_group.append(bg_tg)
# add title
title_group = displayio.Group(scale=SCALE)
root_group.append(title_group)
title_label = Label(
font=FONT,
text="Fruit Jam Library",
color=(config.palette_fg if config is not None else 0xffffff),
anchor_point=(0.5, 0.5),
anchored_position=(DISPLAY_WIDTH // 2, TITLE_HEIGHT // 2),
)
title_group.append(title_label)
# add status bar
status_group = displayio.Group()
root_group.append(status_group)
status_bg_tg = displayio.TileGrid(
bitmap=displayio.Bitmap(display.width, STATUS_HEIGHT, 1),
pixel_shader=fg_palette,
y=display.height - STATUS_HEIGHT,
)
status_group.append(status_bg_tg)
status_label = Label(
font=FONT,
text="Loading...",
color=(config.palette_bg if config is not None else 0x222222),
anchor_point=(0, 0.5),
anchored_position=(STATUS_PADDING, display.height - STATUS_HEIGHT // 2)
)
status_group.append(status_label)
page_label = Label(
font=FONT,
text="0/0",
color=(config.palette_bg if config is not None else 0x222222),
anchor_point=(1, 0.5),
anchored_position=(display.width - STATUS_PADDING, display.height - STATUS_HEIGHT // 2)
)
status_group.append(page_label)
# add keyboard navigation help
help_label = Label(
font=FONT,
text="[Arrow]: Move [Enter]: Select [1-9]: Category",
color=(config.palette_fg if config is not None else 0xffffff),
anchor_point=(0, 1.0),
anchored_position=(STATUS_PADDING, display.height - STATUS_HEIGHT - HELP_MARGIN)
)
root_group.append(help_label)
def log(msg: str) -> None:
status_label.text = msg
print(msg)
# use local or download applications database
try:
with open(APPLICATIONS_PATH, "r") as f:
applications = json.load(f)
if not isinstance(applications, dict):
raise ValueError("Invalid format")
except (OSError, ValueError, AttributeError) as e:
log("Unable to read local applications database. {:s}".format(str(e)))
try:
applications = json.loads(fj.fetch(
APPLICATIONS_URL,
force_content_type=adafruit_fruitjam.network.CONTENT_JSON,
timeout=10,
))
if type(applications) is int:
raise ValueError("{:d} response".format(applications))
except (OSError, ValueError, AttributeError) as e:
log("Unable to fetch applications database! {:s}".format(str(e)))
reset(3)
categories = sorted(applications.keys())
selected_category = None
# setup menu
category_group = displayio.Group()
root_group.append(category_group)
MENU_WIDTH = (display.width - MENU_GAP * (len(categories) + 1)) // len(categories)
for index, category in enumerate(categories):
category_button = Button(
x=(MENU_WIDTH + MENU_GAP) * index + MENU_GAP,
y=TITLE_HEIGHT * SCALE,
width=MENU_WIDTH,
label=category,
**BUTTON_PROPS,
)
category_group.append(category_button)
# setup items
item_grid = GridLayout(
x=(display.width - GRID_WIDTH) // 2,
y=TITLE_HEIGHT * SCALE + MENU_HEIGHT + GRID_MARGIN,
width=GRID_WIDTH,
height=GRID_HEIGHT,
grid_size=(PAGE_COLUMNS, PAGE_ROWS),
divider_lines=False,
)
root_group.append(item_grid)
for index in range(PAGE_SIZE):
item_group = AnchoredGroup()
item_group.hidden = True
item_icon = displayio.TileGrid(
bitmap=default_icon_bmp,
pixel_shader=default_icon_palette,
x=(ITEM_HEIGHT - default_icon_bmp.height) // 2,
y=(ITEM_HEIGHT - default_icon_bmp.height) // 2,
)
item_group.append(item_icon)
item_installed = displayio.TileGrid(
bitmap=installed_bmp,
pixel_shader=installed_palette,
x=item_icon.x + 2, y=item_icon.y + 2,
)
item_group.append(item_installed)
item_title = Label(
font=FONT,
text="[title]",
color=(config.palette_fg if config is not None else 0xffffff),
anchor_point=(0, 0),
anchored_position=(ITEM_HEIGHT, (ITEM_HEIGHT - item_icon.tile_height) // 2),
scale=SCALE,
)
item_group.append(item_title)
item_author = Label(
font=FONT,
text="[author]",
color=(config.palette_fg if config is not None else 0xffffff),
anchor_point=(0, 0),
anchored_position=(ITEM_HEIGHT, item_title.y + item_title.height),
)
item_group.append(item_author)
item_description = TextBox(
font=FONT,
text="[description]",
width=ITEM_WIDTH - ITEM_HEIGHT,
height=item_icon.tile_height - item_title.height - item_author.height,
align=TextBox.ALIGN_LEFT,
color=(config.palette_fg if config is not None else 0xffffff),
anchor_point=(0, 0),
anchored_position=(ITEM_HEIGHT, item_author.y + item_author.height),
)
item_group.append(item_description)
item_grid.add_content(
cell_content=item_group,
grid_position=(index % PAGE_COLUMNS, index // PAGE_COLUMNS),
cell_size=(1, 1),
)
# setup arrows
original_arrow_btn_color = left_palette[2]
arrow_group = displayio.Group(scale=SCALE)
root_group.append(arrow_group)
left_arrow = AnchoredTileGrid(
bitmap=left_bmp,
pixel_shader=left_palette,
)
left_arrow.anchor_point = (0, 0.5)
left_arrow.anchored_position = (0, (DISPLAY_HEIGHT // 2) - 2)
arrow_group.append(left_arrow)
right_arrow = AnchoredTileGrid(
bitmap=right_bmp,
pixel_shader=right_palette,
)
right_arrow.anchor_point = (1.0, 0.5)
right_arrow.anchored_position = (DISPLAY_WIDTH, (DISPLAY_HEIGHT // 2) - 2)
arrow_group.append(right_arrow)
# setup exit icon
exit_button = TileGridButton(
bitmap=exit_bmp,
pixel_shader=exit_palette,
pixel_shader_index=1,
x=0,
y=0,
width=TITLE_HEIGHT,
height=TITLE_HEIGHT,
fill_color=(config.palette_bg if config is not None else 0x222222),
label_color=(config.palette_fg if config is not None else 0xffffff),
outline_color=(config.palette_bg if config is not None else 0x222222),
selected_fill=(config.palette_fg if config is not None else 0xffffff),
selected_label=(config.palette_bg if config is not None else 0x222222),
selected_outline=(config.palette_fg if config is not None else 0xffffff),
)
arrow_group.append(exit_button)
# setup dialog
dialog_group = displayio.Group()
dialog_group.hidden = True
root_group.append(dialog_group)
dialog_border = displayio.TileGrid(
bitmap=displayio.Bitmap(DIALOG_WIDTH, DIALOG_HEIGHT, 1),
pixel_shader=fg_palette,
x=(display.width - DIALOG_WIDTH) // 2,
y=TITLE_HEIGHT * SCALE + DIALOG_MARGIN,
)
dialog_group.append(dialog_border)
dialog_bg = displayio.TileGrid(
bitmap=displayio.Bitmap(DIALOG_WIDTH - DIALOG_BORDER * 2, DIALOG_HEIGHT - DIALOG_BORDER * 2, 1),
pixel_shader=bg_palette,
x=dialog_border.x + DIALOG_BORDER,
y=dialog_border.y + DIALOG_BORDER,
)
dialog_group.append(dialog_bg)
dialog_content = TextBox(
font=FONT,
text="[content]",
width=DIALOG_WIDTH - DIALOG_BORDER * 2 - DIALOG_MARGIN * 2,
height=DIALOG_HEIGHT - DIALOG_BORDER * 2 - DIALOG_MARGIN * 3 - MENU_HEIGHT,
align=TextBox.ALIGN_CENTER,
color=(config.palette_fg if config is not None else 0xffffff),
x=dialog_bg.x + DIALOG_MARGIN,
y=dialog_bg.y + DIALOG_MARGIN,
)
dialog_group.append(dialog_content)
dialog_buttons = displayio.Group(scale=SCALE)
dialog_buttons.hidden = True
root_group.append(dialog_buttons)
def show_dialog(content: str, actions: list = None) -> None:
# update content
dialog_content.text = content
# create buttons
if actions is not None:
button_width = min(
DIALOG_BUTTON_WIDTH,
(DIALOG_WIDTH - (DIALOG_BORDER // SCALE + DIALOG_MARGIN // SCALE) * 2 - MENU_GAP * (len(actions) - 1)) // len(actions)
)
buttons_width = (button_width + MENU_GAP) * len(actions) - MENU_GAP
for index, (label, action) in enumerate(actions):
dialog_buttons.append(ActionButton(
action=action,
label=label,
x=(DISPLAY_WIDTH - buttons_width) // 2 + (button_width + MENU_GAP) * index,
y=DISPLAY_HEIGHT - (STATUS_HEIGHT + DIALOG_MARGIN * 2 + DIALOG_BORDER) // SCALE - MENU_HEIGHT,
width=button_width,
**BUTTON_PROPS,
))
dialog_buttons[0].selected = True # initial selection
# hide other UI elements
category_group.hidden = True
item_grid.hidden = True
arrow_group.hidden = True
# show dialog
dialog_group.hidden = False
dialog_buttons.hidden = False
def hide_dialog() -> None:
# clear text
dialog_content.text = ""
# remove buttons
while len(dialog_buttons):
dialog_buttons.pop()
# hide dialog
dialog_group.hidden = True
dialog_buttons.hidden = True
# show other UI elements
category_group.hidden = False
item_grid.hidden = False
arrow_group.hidden = False
# item navigation
def select_category(name: str) -> None:
global selected_category
if name not in categories or name == selected_category:
return
selected_category = name
# update button states
for category_button in category_group:
category_button.selected = category_button.label == name
# hide all items
for index in range(PAGE_SIZE):
item_grid.get_content((index % PAGE_COLUMNS, index // PAGE_COLUMNS)).hidden = True
# load first page of items
show_page()
current_page = 0
def show_page(page: int = 0) -> None:
global selected_category, current_page
# determine indices
start = page * PAGE_SIZE
end = min((page + 1) * PAGE_SIZE, len(applications[selected_category]))
if start < 0 or start >= len(applications[selected_category]):
return
# hide all items
for index in range(PAGE_SIZE):
item_grid.get_content((index % PAGE_COLUMNS, index // PAGE_COLUMNS)).hidden = True
# update page label
current_page = page
total_pages = math.ceil(len(applications[selected_category]) / PAGE_SIZE)
page_label.text = "{:d}/{:d}".format(page + 1, total_pages)
# toggle arrows
left_arrow.hidden = not page
right_arrow.hidden = page + 1 == total_pages
# display default details
for index in range(start, end):
item_group = item_grid.get_content((index % PAGE_COLUMNS, (index // PAGE_COLUMNS) % PAGE_ROWS))
item_icon, item_installed, item_title, item_author, item_description = item_group
full_name = applications[selected_category][index]
repo_owner, repo_name = full_name.split("/")
# format title from repository name
title = repo_name.replace("-", " ").replace("_", " ").strip()
title = " ".join(map(lambda word: word[0].upper() + word[1:].lower(), title.split(" ")))
if title.startswith("Fruit Jam "):
title = title[len("Fruit Jam "):].strip()
if selected_category == SCREENSAVERS_CATEGORY and title.startswith("Screensaver "):
title = title[len("Screensaver "):].strip()
elif title.startswith("Application "):
title = title[len("Application "):].strip()
# set default details
item_icon.bitmap = default_icon_bmp
item_icon.pixel_shader = default_icon_palette
item_installed.hidden = not is_application_installed(repo_name)
item_title.text = title
item_author.text = repo_owner
item_description.text = "Loading..."
item_group.hidden = False
# read external application data
for index in range(start, end):
item_group = item_grid.get_content((index % PAGE_COLUMNS, (index // PAGE_COLUMNS) % PAGE_ROWS))
item_icon, item_installed, item_title, item_author, item_description = item_group
full_name = applications[selected_category][index]
log("Reading repository data from {:s}".format(full_name))
# get repository info
try:
repository = download_json(
url=REPO_URL.format(full_name),
name=full_name.replace("/", "_"),
)
except (OSError, ValueError, HttpError) as e:
item_description.text = ""
log("Unable to read repository data from {:s}! {:s}".format(full_name, str(e)))
time.sleep(1)
continue
else:
item_author.text = repository["owner"]["login"]
item_description.text = repository["description"]
# read metadata from repository
log("Reading metadata from {:s}".format(full_name))
try:
metadata = download_json(
url=METADATA_URL.format(full_name),
name=full_name.replace("/", "_") + "_metadata",
)
except (OSError, ValueError, HttpError) as e:
log("Unable to read metadata from {:s}! {:s}".format(full_name, str(e)))
else:
item_title.text = metadata["title"]
if "description" in metadata:
item_description.text = metadata["description"]
if "icon" in metadata:
log("Downloading icon from {:s}".format(full_name))
try:
icon_path = download_image(
ICON_URL.format(full_name, repository["default_branch"], metadata["icon"]),
repository["name"] + "_" + metadata["icon"],
)
except (OSError, ValueError, HttpError) as e:
log("Unable to download icon image from {:s}! {:s}".format(full_name, str(e)))
else:
icon_bmp, icon_palette = adafruit_imageload.load(icon_path)
item_icon.bitmap = icon_bmp
item_icon.pixel_shader = icon_palette
# cleanup before loading next item
gc.collect()
log("Page loaded!")
def next_page() -> None:
global current_page
show_page(current_page + 1)
def previous_page() -> None:
global current_page
show_page(current_page - 1)
def refresh_page() -> None:
global current_page
show_page(current_page)
# select first category and show page items
select_category(categories[0])
# application download
def download_application(full_name: str = None) -> bool:
global selected_application
if full_name is None:
if selected_application is None:
return False
full_name = selected_application
repo_owner, repo_name = full_name.split("/")
path = get_application_path(repo_name)
is_screensaver = selected_category == SCREENSAVERS_CATEGORY
application_type = "screensaver" if is_screensaver else "application"
module_filename = "__init__.py" if is_screensaver else "code.py"
if is_application_installed(repo_name):
log("Selected {:s}, {:s}, is already installed!".format(application_type, repo_name))
return False
# get repository release info
log("Reading release data from {:s}".format(full_name))
try:
release = download_json(
url=RELEASE_URL.format(full_name),
name=full_name.replace("/", "_") + "_release",
cache=False,
)
except (OSError, ValueError, HttpError) as e:
log("Unable to read release data from {:s}! {:s}".format(full_name, str(e)))
# get default branch
log("Attempting to locate default branch archive...")
try:
repository = download_json(
url=REPO_URL.format(full_name),
name=full_name.replace("/", "_"),
cache=False,
)
except (OSError, ValueError, HttpError) as e:
log("Unable to read repository data from {:s}! {:s}".format(full_name, str(e)))
return False
branch_name = repository["default_branch"]
download_url = BRANCH_DOWNLOAD_URL.format(full_name, branch_name)
else:
# locate release download
download_url = release["zipball_url"] if "zipball_url" in release else ""
if "assets" in release and len(assets := list(filter(lambda x: x["name"].endswith(".zip"), release["assets"]))):
download_url = assets[0]["browser_download_url"]
if not download_url:
log("Unable to locate release assets for {:s}!", full_name)
return False
# download project bundle
log("Downloading release assets...")
try:
zip_path = download_zip(download_url, repo_name, cache=False)
except (OSError, ValueError, HttpError) as e:
log("Failed to download release assets for {:s}! {:s}".format(full_name, str(e)))
return False
# read archived file
log("Installing {:s}...".format(application_type))
result = False
try:
with ZipFile(zip_path, "r") as zf:
# determine correct inner path based on CP version
for dirpath in (repo_name + "/" + VERSION_NAME, VERSION_NAME, repo_name, "", None):
if dirpath is not None:
try:
zf.getinfo((dirpath + "/" + module_filename).strip("/"))
except KeyError:
pass
else:
break
if dirpath is None:
# try searching for module
for info in zf.infolist():
if info.filename.split("/")[-1] == module_filename:
dirpath = info.filename[:-len(module_filename)].strip("/")
break
if dirpath is None:
# try finding top-level directory with .py files
min_parts = -1
for info in zf.infolist():
if info.filename.endswith(".py"):
parts = info.filename.split("/")[:-1]
if min_parts < 0 or min_parts > len(parts):
min_parts = len(parts)
dirpath = "/".join(parts).strip("/")
# make sure we found module
if dirpath is None:
log("Could not locate {:s} files within release!".format(application_type))
else:
# extract files
extractall(zf, path, dirpath)
log("Successfully installed {:s}!".format(full_name))
result = True
except (BadZipFile, OSError, MemoryError) as e:
log("Unable to extract and install {:s}! {:s}".format(application_type, str(e)))
# remove zip file
os.remove(zip_path)
return result
def remove_application(full_name: str = None) -> bool:
global selected_application
if full_name is None:
if selected_application is None:
return False
full_name = selected_application
repo_owner, repo_name = full_name.split("/")
path = get_application_path(repo_name)
application_type = "screensaver" if selected_category == SCREENSAVERS_CATEGORY else "application"
if not is_application_installed(repo_name):
return False
log("Deleting {:s}...".format(path))
try:
rmtree(path)
except OSError as e:
log("Failed to delete {:s}: {:s}".format(path, str(e)))
return False
else:
log("Successfully deleted {:s}!".format(application_type))
return True
def open_application(full_name: str = None) -> None:
global selected_application, current_page
if full_name is None:
if selected_application is None:
return False
full_name = selected_application
repo_owner, repo_name = selected_application.split("/")
filepath = get_application_file(repo_name)
if filepath is not None and is_application_installed(repo_name) and exists(filepath):
log("Opening {:s}...".format(repo_name))
supervisor.set_next_code_file(
filepath,
sticky_on_reload=False,
reload_on_error=True,
working_directory="/".join(filepath.split("/")[:-1])
)
supervisor.reload()
else:
log("Unable to open {:s}!".format(repo_name))
selected_application = None
def select_application(index: int|tuple) -> None:
global selected_category, current_page, selected_application
if isinstance(index, tuple):
index = index[1] * PAGE_COLUMNS + index[0]
index += current_page * PAGE_SIZE
if index < 0 or index >= len(applications[selected_category]):
return
selected_application = applications[selected_category][index]
repo_owner, repo_name = selected_application.split("/")
is_screensaver = selected_category == SCREENSAVERS_CATEGORY
application_type = "screensaver" if is_screensaver else "application"
# hide other UI elements
category_group.hidden = True
item_grid.hidden = True
arrow_group.hidden = True
# populate dialog info
item_group = item_grid.get_content((index % PAGE_COLUMNS, (index // PAGE_COLUMNS) % PAGE_ROWS))
item_icon, item_installed, item_title, item_author, item_description = item_group
path = get_application_path(repo_name)
if item_installed.hidden:
show_dialog(
content="Would you like to download and install \"{:s}\" by {:s} to your SD card at {:s}?".format(
item_title.text,
item_author.text,
path
),
actions=[
("Cancel", deselect_application),
("Download", toggle_application),
],
)
else:
show_dialog(
content="The {:s}, \"{:s}\", is already installed. Would you like to remove it from your SD card at {:s}? Any save data within /saves will be retained.".format(
application_type,
item_title.text,
path
),
actions=list(filter(lambda x: x, [
("Cancel", deselect_application),
("Remove", toggle_application),
("Update", update_application),
("Open", open_application) if not is_screensaver else None,
])),
)
dialog_group.hidden = False
dialog_buttons.hidden = False
def deselect_application() -> None:
global selected_application
# invalidate selection
selected_application = None
# hide dialog and show other UI elements
hide_dialog()
def toggle_application(full_name: str = None) -> bool:
global selected_application, current_page
if full_name is None:
if selected_application is None:
return False
full_name = selected_application
repo_owner, repo_name = selected_application.split("/")
if not is_application_installed(repo_name):
result = download_application(full_name)
else:
result = remove_application(full_name)
# hide dialog and update installed state
deselect_application()
refresh_page()
return result
def update_application(full_name: str = None) -> bool:
global selected_application, current_page
if full_name is None:
if selected_application is None:
return False
full_name = selected_application
repo_owner, repo_name = selected_application.split("/")
result = False
if is_application_installed(repo_name):
if remove_application(full_name):
result = download_application(full_name)