-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjadiv_code_master.py
More file actions
1304 lines (1159 loc) · 50.3 KB
/
Copy pathjadiv_code_master.py
File metadata and controls
1304 lines (1159 loc) · 50.3 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
"""Jadiv Code Master – a desktop app store for jan-tdy applications.
Apps are discovered from GitHub: every jan-tdy repository that ships a
``codemaster-metadata.json`` file is read and its apps are listed in the store.
A single repository can publish several apps (see ``devcontrolenterpise``).
Features:
* Store – browse & install every published jan-tdy app
* Installed – launch / remove what you installed
* Updates – see which installed apps have a newer published version
* Manual – register jan-tdy apps you installed by hand + settings
* Code Runner – a small editor/runner kept from the classic Code Master
"""
import sys
import os
import json
import shutil
import subprocess
import hashlib
from pathlib import Path
import requests
from PyQt5.QtWidgets import (
QApplication, QMainWindow, QTabWidget, QVBoxLayout, QHBoxLayout, QWidget,
QPushButton, QTextEdit, QLineEdit, QLabel, QScrollArea, QFrame, QGridLayout,
QSizePolicy, QFileDialog, QMessageBox, QCheckBox, QFormLayout
)
from PyQt5.QtCore import Qt, QThread, pyqtSignal, QSize, QProcess
from PyQt5.QtGui import QPixmap, QColor, QPainter, QFont
APP_NAME = "Jadiv Code Master"
APP_VERSION = "0.2.2"
DEFAULT_USERNAME = "jan-tdy"
DEFAULT_BRANCH = "main"
METADATA_FILE = "codemaster-metadata.json"
CONFIG_DIR = Path.home() / ".config" / "codemaster"
DATA_DIR = Path.home() / ".local" / "share" / "codemaster"
APPS_DIR = DATA_DIR / "apps"
CONFIG_FILE = CONFIG_DIR / "config.json"
INSTALLED_FILE = CONFIG_DIR / "installed.json"
# Cache of the last scanned catalog, so apps show up instantly on next launch
# while a fresh scan runs in the background.
CACHE_DIR = DATA_DIR / "cache"
CATALOG_CACHE = CACHE_DIR / "catalog.json"
ICON_CACHE_DIR = CACHE_DIR / "icons"
# Desktop launchers Code Master creates for installed apps.
APPLICATIONS_DIR = Path(os.environ.get(
"XDG_DATA_HOME", Path.home() / ".local" / "share")) / "applications"
LAUNCHER_ICON_DIR = DATA_DIR / "launcher-icons"
# Maps a metadata category to freedesktop.org Categories= values.
DESKTOP_CATEGORIES = {
"Astronomy": "Science;Education;",
"Photography": "Graphics;Photography;",
"Education": "Education;",
"Developer Tools": "Development;",
"Developer": "Development;",
}
# Directory the running Code Master lives in (used for self-update).
SELF_DIR = Path(__file__).resolve().parent
ICON_SIZE = 64
# --------------------------------------------------------------------------- #
# Persistence helpers
# --------------------------------------------------------------------------- #
def _read_json(path, default):
try:
with open(path, "r", encoding="utf-8") as fh:
return json.load(fh)
except Exception:
return default
def _write_json(path, data):
# Write to a sibling temp file and atomically replace, so a crash mid-write
# can never leave a half-written (corrupt) config behind.
path.parent.mkdir(parents=True, exist_ok=True)
temp_path = path.with_suffix(".tmp")
try:
with open(temp_path, "w", encoding="utf-8") as fh:
json.dump(data, fh, indent=2, ensure_ascii=False)
temp_path.replace(path)
except Exception:
if temp_path.exists():
temp_path.unlink()
raise
def load_config():
cfg = _read_json(CONFIG_FILE, {})
cfg.setdefault("username", DEFAULT_USERNAME)
cfg.setdefault("branch", DEFAULT_BRANCH)
cfg.setdefault("token", "")
cfg.setdefault("manual_paths", [])
return cfg
def save_config(cfg):
_write_json(CONFIG_FILE, cfg)
def load_installed():
return _read_json(INSTALLED_FILE, {})
def save_installed(data):
_write_json(INSTALLED_FILE, data)
def _cache_icon_name(key):
return key.replace("/", "__").replace(" ", "_")
def save_catalog_cache(apps):
"""Persist the scanned catalog so it can be shown instantly next launch.
Icon bytes don't fit in JSON, so each icon is written to its own file and
referenced by name."""
try:
ICON_CACHE_DIR.mkdir(parents=True, exist_ok=True)
serial = []
for app in apps:
record = {k: v for k, v in app.items() if k != "icon_data"}
icon = app.get("icon_data")
if icon:
fname = _cache_icon_name(app["key"]) + ".img"
(ICON_CACHE_DIR / fname).write_bytes(icon)
record["icon_file"] = fname
else:
record["icon_file"] = None
serial.append(record)
_write_json(CATALOG_CACHE, {"apps": serial})
except Exception:
pass # caching is best-effort; never break a successful scan over it
def load_catalog_cache():
data = _read_json(CATALOG_CACHE, None)
if not data:
return []
apps = []
for record in data.get("apps", []):
app = dict(record)
icon_file = app.pop("icon_file", None)
app["icon_data"] = None
if icon_file:
path = ICON_CACHE_DIR / icon_file
if path.exists():
try:
app["icon_data"] = path.read_bytes()
except Exception:
pass
apps.append(app)
return apps
# --------------------------------------------------------------------------- #
# Icon helpers
# --------------------------------------------------------------------------- #
def pixmap_from_bytes(data, size=ICON_SIZE):
if not data:
return None
pm = QPixmap()
if pm.loadFromData(data):
return pm.scaled(size, size, Qt.KeepAspectRatio, Qt.SmoothTransformation)
try: # vector fallback (e.g. JadivCalc ships an SVG icon)
from PyQt5.QtSvg import QSvgRenderer
from PyQt5.QtCore import QByteArray
renderer = QSvgRenderer(QByteArray(data))
if renderer.isValid():
img = QPixmap(size, size)
img.fill(Qt.transparent)
painter = QPainter(img)
renderer.render(painter)
painter.end()
return img
except Exception:
pass
return None
def placeholder_pixmap(name, size=ICON_SIZE):
"""A coloured rounded tile with the app's initial – used when no icon."""
palette = ["#4f8cff", "#ff6b6b", "#1ec98b", "#ffa94d", "#9775fa", "#22b8cf"]
digest = int(hashlib.md5(name.encode("utf-8")).hexdigest(), 16)
color = QColor(palette[digest % len(palette)])
pm = QPixmap(size, size)
pm.fill(Qt.transparent)
painter = QPainter(pm)
painter.setRenderHint(QPainter.Antialiasing)
painter.setBrush(color)
painter.setPen(Qt.NoPen)
radius = size * 0.22
painter.drawRoundedRect(0, 0, size, size, radius, radius)
painter.setPen(QColor("white"))
font = QFont()
font.setPixelSize(int(size * 0.5))
font.setBold(True)
painter.setFont(font)
letter = (name.strip()[:1] or "?").upper()
painter.drawText(pm.rect(), Qt.AlignCenter, letter)
painter.end()
return pm
# --------------------------------------------------------------------------- #
# Background workers
# --------------------------------------------------------------------------- #
class CatalogLoader(QThread):
"""Discover every jan-tdy app published through codemaster-metadata.json."""
loaded = pyqtSignal(list)
failed = pyqtSignal(str)
status = pyqtSignal(str)
def __init__(self, username, branch, token=""):
super().__init__()
self.username = username
self.branch = branch
self.token = token
def _headers(self):
return {"Authorization": f"token {self.token}"} if self.token else {}
def _list_repos(self):
repos, page = [], 1
while True:
url = (f"https://api.github.com/users/{self.username}/repos"
f"?per_page=100&page={page}")
resp = requests.get(url, headers=self._headers(), timeout=20)
resp.raise_for_status()
chunk = resp.json()
if not chunk:
break
repos.extend((r["name"], r.get("default_branch", "main"))
for r in chunk)
if len(chunk) < 100:
break
page += 1
return repos
def _fetch_metadata(self, repo, default_branch):
branches = []
for b in (self.branch, default_branch):
if b and b not in branches:
branches.append(b)
for branch in branches:
raw = (f"https://raw.githubusercontent.com/{self.username}/"
f"{repo}/{branch}/{METADATA_FILE}")
try:
resp = requests.get(raw, headers=self._headers(), timeout=20)
except requests.RequestException:
continue
if resp.status_code == 200:
try:
return resp.json(), branch
except ValueError:
return None, None
return None, None
def _fetch_release(self, repo):
"""Latest published release tag for a repo, or None if it has none."""
url = (f"https://api.github.com/repos/{self.username}/"
f"{repo}/releases/latest")
try:
resp = requests.get(url, headers=self._headers(), timeout=20)
if resp.status_code == 200:
return resp.json().get("tag_name")
except requests.RequestException:
return None
return None
def _fetch_icon(self, repo, branch, icon_path):
if not icon_path:
return None
raw = (f"https://raw.githubusercontent.com/{self.username}/"
f"{repo}/{branch}/{icon_path}")
try:
resp = requests.get(raw, headers=self._headers(), timeout=20)
if resp.status_code == 200:
return resp.content
except requests.RequestException:
return None
return None
def run(self):
try:
self.status.emit("Contacting GitHub…")
apps = []
repos = self._list_repos()
for repo, default_branch in repos:
self.status.emit(f"Scanning {repo}…")
meta, branch = self._fetch_metadata(repo, default_branch)
if not meta:
continue
release_tag = None
if any(a.get("update_method") == "release"
for a in meta.get("apps", [])):
release_tag = self._fetch_release(repo)
for app in meta.get("apps", []):
icon_data = self._fetch_icon(repo, branch, app.get("icon"))
method = app.get("update_method", "sync")
apps.append({
"key": f"{repo}/{app.get('id')}",
"repo": repo,
"branch": branch,
"id": app.get("id"),
"name": app.get("name", app.get("id", "?")),
"tagline": app.get("tagline", ""),
"description": app.get("description", ""),
"category": app.get("category", "Other"),
"version": str(app.get("version", "")),
"author": app.get("author", self.username),
"icon_data": icon_data,
"subdir": app.get("subdir", "."),
"entrypoint": app.get("entrypoint", ""),
"run": app.get("run", ""),
"requirements": app.get("requirements"),
"maintained": app.get("maintained", True),
"update_method": method,
"release_tag": release_tag if method == "release"
else None,
"homepage": app.get("homepage")
or meta.get("homepage"),
})
apps.sort(key=lambda a: (a["category"].lower(), a["name"].lower()))
self.loaded.emit(apps)
except Exception as exc: # noqa: BLE001
self.failed.emit(str(exc))
class GitWorker(QThread):
"""Clone / update / install-deps without freezing the UI."""
done = pyqtSignal(bool, str)
def __init__(self, action, username, repo, repo_root, branch,
req_path=None, method="sync", release_tag=None):
super().__init__()
self.action = action
self.username = username
self.repo = repo
self.repo_root = Path(repo_root)
self.branch = branch
self.req_path = req_path
self.method = method
self.release_tag = release_tag
def _run(self, cmd, cwd=None):
proc = subprocess.run(cmd, cwd=cwd, capture_output=True, text=True)
if proc.returncode != 0:
raise RuntimeError(proc.stderr.strip() or proc.stdout.strip())
return proc.stdout
def _clone(self, ref):
"""Fresh shallow clone of the repo at a branch or tag."""
url = f"https://github.com/{self.username}/{self.repo}.git"
if self.repo_root.exists():
shutil.rmtree(self.repo_root)
self.repo_root.parent.mkdir(parents=True, exist_ok=True)
cmd = ["git", "clone", "--depth", "1"]
if ref:
cmd += ["--branch", ref]
cmd += [url, str(self.repo_root)]
self._run(cmd)
def run(self):
try:
# "release" apps track a tagged GitHub release; "sync" apps track
# the latest code on a branch.
release = (self.method == "release" and self.release_tag)
if self.action in ("install", "update"):
if release:
# Tags can't be fast-forwarded — re-clone at the new tag.
self._clone(self.release_tag)
elif self.action == "install" and \
not (self.repo_root / ".git").exists():
self._clone(self.branch)
else:
self._run(["git", "-C", str(self.repo_root), "pull",
"--ff-only"])
self.done.emit(
True, "Installed" if self.action == "install"
else "Updated")
elif self.action == "deps":
self._run([sys.executable, "-m", "pip", "install", "-r",
str(self.req_path)])
self.done.emit(True, "Dependencies installed")
except Exception as exc: # noqa: BLE001
self.done.emit(False, str(exc))
# --------------------------------------------------------------------------- #
# App card widget
# --------------------------------------------------------------------------- #
class AppCard(QFrame):
def __init__(self, app, store, context="store"):
super().__init__()
self.app = app
self.store = store
self.context = context
self.setObjectName("AppCard")
self.setFrameShape(QFrame.StyledPanel)
self._build()
def _build(self):
outer = QHBoxLayout(self)
outer.setContentsMargins(14, 12, 14, 12)
outer.setSpacing(14)
icon = QLabel()
pm = pixmap_from_bytes(self.app.get("icon_data")) \
or placeholder_pixmap(self.app["name"])
icon.setPixmap(pm)
icon.setFixedSize(ICON_SIZE, ICON_SIZE)
icon.setAlignment(Qt.AlignTop)
outer.addWidget(icon)
text = QVBoxLayout()
text.setSpacing(2)
title_row = QHBoxLayout()
title = QLabel(self.app["name"])
title.setObjectName("AppTitle")
title_row.addWidget(title)
if not self.app.get("maintained", True):
badge = QLabel("unmaintained")
badge.setObjectName("BadgeWarn")
title_row.addWidget(badge)
title_row.addStretch()
text.addLayout(title_row)
meta_bits = [self.app["category"]]
version = self.store.effective_version(self.app)
if version:
meta_bits.append("v" + version)
meta_bits.append(self.app["repo"])
if self.app.get("update_method") == "release":
meta_bits.append("↻ release")
else:
meta_bits.append("↻ latest code")
meta = QLabel(" · ".join(meta_bits))
meta.setObjectName("AppMeta")
text.addWidget(meta)
desc = QLabel(self.app.get("tagline")
or self.app.get("description", ""))
desc.setObjectName("AppDesc")
desc.setWordWrap(True)
text.addWidget(desc)
outer.addLayout(text, 1)
outer.addLayout(self._actions())
def _actions(self):
col = QVBoxLayout()
col.setSpacing(6)
col.addStretch()
installed = self.store.is_installed(self.app["key"])
if self.context in ("installed", "updates") or installed:
if self.store.has_update(self.app):
col.addWidget(self._btn("Update", "Primary",
self.store.update_app))
launch = self._btn("Open", "Primary" if not
self.store.has_update(self.app) else "Ghost",
self.store.launch_app)
col.addWidget(launch)
if self.store.has_launcher(self.app):
col.addWidget(self._btn("Remove launcher", "Ghost",
self.store.remove_launcher))
else:
col.addWidget(self._btn("Add to menu", "Ghost",
self.store.create_launcher))
if self.app.get("requirements"):
col.addWidget(self._btn("Install deps", "Ghost",
self.store.install_deps))
col.addWidget(self._btn("Remove", "Ghost",
self.store.uninstall_app))
else:
col.addWidget(self._btn("Install", "Primary",
self.store.install_app))
if self.app.get("homepage"):
col.addWidget(self._btn("Details", "Ghost",
self.store.open_homepage))
col.addStretch()
return col
def _btn(self, label, kind, slot):
btn = QPushButton(label)
btn.setObjectName(kind)
btn.setCursor(Qt.PointingHandCursor)
btn.setMinimumWidth(110)
btn.clicked.connect(lambda: slot(self.app))
return btn
# --------------------------------------------------------------------------- #
# Main window
# --------------------------------------------------------------------------- #
class CodeMaster(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle(APP_NAME)
self.setGeometry(100, 100, 980, 720)
self.config = load_config()
self.installed = load_installed()
# Show the previously-scanned catalog instantly; a fresh scan runs in
# the background right after the window is up.
self.catalog = load_catalog_cache()
self._workers = set()
central = QWidget()
root = QVBoxLayout(central)
root.setContentsMargins(0, 0, 0, 0)
root.setSpacing(0)
self.setCentralWidget(central)
root.addWidget(self._build_header())
self.tabs = QTabWidget()
root.addWidget(self.tabs, 1)
self.store_area, self.store_box = self._scroll_page()
self.installed_area, self.installed_box = self._scroll_page()
self.updates_area, self.updates_box = self._scroll_page()
self.tabs.addTab(self.store_area, "Store")
self.tabs.addTab(self.installed_area, "Installed")
self.tabs.addTab(self.updates_area, "Updates")
self.tabs.addTab(self._build_manual_tab(), "Manual & Settings")
self.tabs.addTab(self._build_runner_tab(), "Code Runner")
self.setStyleSheet(STYLE)
self.refresh_views()
self.load_catalog()
# -- header ----------------------------------------------------------- #
def _build_header(self):
bar = QWidget()
bar.setObjectName("Header")
lay = QHBoxLayout(bar)
lay.setContentsMargins(18, 12, 18, 12)
title = QLabel("🛍 " + APP_NAME)
title.setObjectName("HeaderTitle")
lay.addWidget(title)
lay.addSpacing(20)
self.search = QLineEdit()
self.search.setPlaceholderText("Search apps…")
self.search.setObjectName("Search")
self.search.textChanged.connect(self.rebuild_store)
lay.addWidget(self.search, 1)
self.refresh_btn = QPushButton("⟳ Refresh")
self.refresh_btn.setObjectName("Primary")
self.refresh_btn.setCursor(Qt.PointingHandCursor)
self.refresh_btn.clicked.connect(self.load_catalog)
lay.addWidget(self.refresh_btn)
return bar
def _scroll_page(self):
area = QScrollArea()
area.setWidgetResizable(True)
area.setObjectName("Page")
holder = QWidget()
box = QVBoxLayout(holder)
box.setContentsMargins(18, 18, 18, 18)
box.setSpacing(12)
box.addStretch()
area.setWidget(holder)
return area, box
# -- manual & settings tab ------------------------------------------- #
def _build_manual_tab(self):
page = QWidget()
lay = QVBoxLayout(page)
lay.setContentsMargins(18, 18, 18, 18)
lay.setSpacing(14)
intro = QLabel(
"Register jan-tdy apps you installed manually. Point Code Master "
"to a folder that contains a <b>codemaster-metadata.json</b> file "
"and its apps will appear under <b>Installed</b>.")
intro.setWordWrap(True)
lay.addWidget(intro)
add_btn = QPushButton("➕ Add app folder…")
add_btn.setObjectName("Primary")
add_btn.setCursor(Qt.PointingHandCursor)
add_btn.clicked.connect(self.add_manual_folder)
lay.addWidget(add_btn, alignment=Qt.AlignLeft)
self.manual_list = QLabel()
self.manual_list.setWordWrap(True)
self.manual_list.setObjectName("AppMeta")
lay.addWidget(self.manual_list)
line = QFrame()
line.setFrameShape(QFrame.HLine)
lay.addWidget(line)
settings = QLabel("<b>Settings</b>")
lay.addWidget(settings)
form = QFormLayout()
self.username_in = QLineEdit(self.config["username"])
self.branch_in = QLineEdit(self.config["branch"])
self.token_in = QLineEdit(self.config["token"])
self.token_in.setEchoMode(QLineEdit.Password)
self.token_in.setPlaceholderText("optional – raises GitHub rate limit")
form.addRow("GitHub user:", self.username_in)
form.addRow("Metadata branch:", self.branch_in)
form.addRow("GitHub token:", self.token_in)
lay.addLayout(form)
save_btn = QPushButton("Save settings")
save_btn.setObjectName("Primary")
save_btn.setCursor(Qt.PointingHandCursor)
save_btn.clicked.connect(self.save_settings)
lay.addWidget(save_btn, alignment=Qt.AlignLeft)
line2 = QFrame()
line2.setFrameShape(QFrame.HLine)
lay.addWidget(line2)
lay.addWidget(QLabel(f"<b>About Code Master</b> — v{APP_VERSION}"))
self_update_row = QHBoxLayout()
self.self_update_btn = QPushButton("Update Code Master")
self.self_update_btn.setObjectName("Primary")
self.self_update_btn.setCursor(Qt.PointingHandCursor)
self.self_update_btn.clicked.connect(self.self_update)
self_update_row.addWidget(self.self_update_btn)
self_update_row.addStretch()
lay.addLayout(self_update_row)
self.self_update_note = QLabel()
self.self_update_note.setObjectName("AppMeta")
self.self_update_note.setWordWrap(True)
lay.addWidget(self.self_update_note)
lay.addStretch()
self._refresh_manual_list()
self._refresh_self_update_note()
return page
def _build_runner_tab(self):
page = QWidget()
lay = QVBoxLayout(page)
lay.setContentsMargins(18, 18, 18, 18)
self.code_editor = QTextEdit()
self.code_editor.setPlaceholderText("Write or paste Python code here…")
lay.addWidget(self.code_editor)
self.run_btn = QPushButton("Run code")
self.run_btn.setObjectName("Primary")
self.run_btn.setCursor(Qt.PointingHandCursor)
self.run_btn.clicked.connect(self.run_code)
lay.addWidget(self.run_btn, alignment=Qt.AlignLeft)
self._runner_process = None
lay.addWidget(QLabel("Output:"))
self.code_output = QTextEdit()
self.code_output.setReadOnly(True)
lay.addWidget(self.code_output)
return page
# -- catalog ---------------------------------------------------------- #
def load_catalog(self):
self.refresh_btn.setEnabled(False)
self.refresh_btn.setText("⟳ Loading…")
# If we already have a cached catalog on screen, keep it visible and
# just refresh in the background; otherwise show the (slow scan) notice.
if self.catalog:
self._toast("Refreshing app list from GitHub… (can take a minute)")
else:
self._set_placeholder(
self.store_box,
"Scanning every jan-tdy repository on GitHub for apps…\n"
"This can take up to a minute on the first run.")
loader = CatalogLoader(self.config["username"], self.config["branch"],
self.config["token"])
loader.loaded.connect(self.on_catalog_loaded)
loader.failed.connect(self.on_catalog_failed)
loader.status.connect(
lambda msg: self.refresh_btn.setText("⟳ " + msg[:18]))
loader.finished.connect(lambda: self._workers.discard(loader))
self._workers.add(loader)
loader.start()
def on_catalog_loaded(self, apps):
self.catalog = apps
save_catalog_cache(apps)
self.refresh_btn.setEnabled(True)
self.refresh_btn.setText("⟳ Refresh")
self.refresh_views()
self._toast(f"Found {len(apps)} app(s)")
def on_catalog_failed(self, message):
self.refresh_btn.setEnabled(True)
self.refresh_btn.setText("⟳ Refresh")
# Keep the cached catalog on screen if the refresh failed (e.g. offline).
if self.catalog:
self._toast(f"Refresh failed, showing cached apps: {message}")
else:
self._set_placeholder(
self.store_box, f"Could not load catalog:\n{message}")
# -- view rebuilding -------------------------------------------------- #
def refresh_views(self):
self.rebuild_store()
self.rebuild_installed()
self.rebuild_updates()
if hasattr(self, "manual_list"):
self._refresh_manual_list()
self._refresh_self_update_note()
def _clear(self, box):
while box.count():
item = box.takeAt(0)
w = item.widget()
if w:
w.deleteLater()
def _set_placeholder(self, box, text):
self._clear(box)
lbl = QLabel(text)
lbl.setObjectName("Placeholder")
lbl.setAlignment(Qt.AlignCenter)
lbl.setWordWrap(True)
box.addWidget(lbl)
box.addStretch()
def _section(self, box, title):
lbl = QLabel(title)
lbl.setObjectName("Section")
box.addWidget(lbl)
def rebuild_store(self):
box = self.store_box
self._clear(box)
query = self.search.text().strip().lower() if hasattr(
self, "search") else ""
apps = [a for a in self.catalog
if query in a["name"].lower()
or query in a["tagline"].lower()
or query in a["description"].lower()
or query in a["category"].lower()]
if not apps:
self._set_placeholder(
box, "No apps found." if self.catalog
else "No apps yet — press Refresh to load from GitHub.")
return
current = None
for app in apps:
if app["category"] != current:
current = app["category"]
self._section(box, current)
box.addWidget(AppCard(app, self, context="store"))
box.addStretch()
def rebuild_installed(self):
box = self.installed_box
self._clear(box)
apps = self._installed_apps()
if not apps:
self._set_placeholder(
box, "Nothing installed yet.\nInstall apps from the Store, "
"or register a manual folder under Manual & Settings.")
return
for app in apps:
box.addWidget(AppCard(app, self, context="installed"))
box.addStretch()
def rebuild_updates(self):
box = self.updates_box
self._clear(box)
apps = [a for a in self._installed_apps() if self.has_update(a)]
idx = self.tabs.indexOf(self.updates_area) if hasattr(
self, "tabs") else -1
if hasattr(self, "tabs") and idx >= 0:
self.tabs.setTabText(idx, f"Updates ({len(apps)})"
if apps else "Updates")
if not apps:
self._set_placeholder(box, "Everything is up to date. 🎉")
return
header = QHBoxLayout()
update_all = QPushButton("Update all")
update_all.setObjectName("Primary")
update_all.setCursor(Qt.PointingHandCursor)
# One git pull per repo — several apps can share a clone, and parallel
# pulls in the same directory collide on .git/index.lock.
seen_repos = set()
unique_apps = []
for a in apps:
if a["repo"] not in seen_repos:
seen_repos.add(a["repo"])
unique_apps.append(a)
update_all.clicked.connect(
lambda: [self.update_app(a) for a in unique_apps])
wrap = QWidget()
wrap.setLayout(header)
header.addStretch()
header.addWidget(update_all)
box.addWidget(wrap)
for app in apps:
box.addWidget(AppCard(app, self, context="updates"))
box.addStretch()
def _installed_apps(self):
"""Merge live catalog data over the stored installed records."""
catalog_by_key = {a["key"]: a for a in self.catalog}
out = []
for key, rec in self.installed.items():
app = dict(catalog_by_key.get(key, {}))
app.update({k: v for k, v in rec.items() if v is not None
or k not in app})
app.setdefault("key", key)
app.setdefault("name", rec.get("name", key))
app.setdefault("category", rec.get("category", "Other"))
app.setdefault("version", rec.get("version", ""))
app.setdefault("repo", rec.get("repo", key.split("/")[0]))
# keep icon from catalog if the stored record has none
if not app.get("icon_data") and key in catalog_by_key:
app["icon_data"] = catalog_by_key[key].get("icon_data")
out.append(app)
out.sort(key=lambda a: a["name"].lower())
return out
# -- state queries ---------------------------------------------------- #
def is_installed(self, key):
return key in self.installed
@staticmethod
def effective_version(app):
"""The version we compare on: a release tag for 'release' apps,
otherwise the version declared in the metadata."""
if app.get("update_method") == "release" and app.get("release_tag"):
return str(app["release_tag"])
return str(app.get("version", ""))
def has_update(self, app):
rec = self.installed.get(app["key"])
if not rec:
return False
catalog = next((a for a in self.catalog if a["key"] == app["key"]),
None)
if not catalog:
return False
latest = self.effective_version(catalog)
if not latest:
return False
return latest != str(rec.get("version", ""))
# -- install / update / launch --------------------------------------- #
def _resolve(self, app):
"""Overlay the stored installed record onto an app dict.
Cards in the Store tab carry the raw catalog dict, which has no
``source``/``repo_root``; without this, acting on a manually-added app
from the Store would wrongly target ``apps/<repo>`` instead of the
folder it was installed from."""
if not app:
return app
rec = self.installed.get(app.get("key"))
if not rec:
return app
return {**app, **{k: v for k, v in rec.items() if v is not None}}
def _repo_root(self, app):
# Trust the installed record (looked up by key), not the passed dict.
if not app:
return APPS_DIR
rec = self.installed.get(app.get("key"))
if rec and rec.get("repo_root"):
return Path(rec["repo_root"])
return APPS_DIR / app.get("repo", "")
def install_app(self, app):
repo_root = APPS_DIR / app["repo"]
worker = GitWorker("install", self.config["username"], app["repo"],
repo_root, app.get("branch", self.config["branch"]),
method=app.get("update_method", "sync"),
release_tag=app.get("release_tag"))
def finished(ok, msg):
self._workers.discard(worker)
if not ok:
QMessageBox.warning(self, "Install failed", msg)
return
self.installed[app["key"]] = {
"name": app["name"], "repo": app["repo"],
"category": app["category"],
"version": self.effective_version(app),
"subdir": app.get("subdir", "."), "run": app.get("run", ""),
"requirements": app.get("requirements"),
"update_method": app.get("update_method", "sync"),
"repo_root": str(repo_root), "source": "store",
}
save_installed(self.installed)
self.refresh_views()
self._toast(f"Installed {app['name']}")
worker.done.connect(finished)
self._workers.add(worker)
worker.start()
self._toast(f"Installing {app['name']}…")
def update_app(self, app):
app = self._resolve(app)
repo_root = self._repo_root(app)
catalog = next((a for a in self.catalog if a["key"] == app["key"]),
None) or app
worker = GitWorker("update", self.config["username"], app["repo"],
repo_root, app.get("branch", self.config["branch"]),
method=catalog.get("update_method", "sync"),
release_tag=catalog.get("release_tag"))
def finished(ok, msg):
self._workers.discard(worker)
if not ok:
QMessageBox.warning(self, "Update failed", msg)
return
# Refreshing the clone updates every installed app from this repo —
# sync each one's stored version to the freshly installed one.
for key, inst in list(self.installed.items()):
if inst.get("repo") == app["repo"]:
cat = next((a for a in self.catalog
if a["key"] == key), None)
if cat:
inst["version"] = self.effective_version(cat)
save_installed(self.installed)
self.refresh_views()
self._toast(f"Updated {app['name']}")
worker.done.connect(finished)
self._workers.add(worker)
worker.start()
self._toast(f"Updating {app['name']}…")
def install_deps(self, app):
app = self._resolve(app)
repo_root = self._repo_root(app)
req = repo_root / app.get("subdir", ".") / app["requirements"]
if not req.exists():
QMessageBox.warning(self, "Dependencies",
f"Requirements file not found:\n{req}")
return
worker = GitWorker("deps", self.config["username"], app["repo"],
repo_root, app.get("branch"), req_path=req)
def finished(ok, msg):
self._workers.discard(worker)
QMessageBox.information(
self, "Dependencies",
msg if ok else f"Failed to install dependencies:\n{msg}")
worker.done.connect(finished)
self._workers.add(worker)
worker.start()
self._toast(f"Installing dependencies for {app['name']}…")
def launch_app(self, app):
app = self._resolve(app)
repo_root = self._repo_root(app)
cwd = repo_root / app.get("subdir", ".")
run = app.get("run") or (f"python3 {app.get('entrypoint')}"
if app.get("entrypoint") else "")
if not run:
QMessageBox.warning(self, "Launch",
"No run command defined for this app.")
return
if not cwd.exists():
QMessageBox.warning(self, "Launch",
f"App folder not found:\n{cwd}")
return
try:
subprocess.Popen(run, shell=True, cwd=str(cwd))
self._toast(f"Launched {app['name']}")
except Exception as exc: # noqa: BLE001
QMessageBox.warning(self, "Launch failed", str(exc))
# -- desktop launchers ------------------------------------------------ #
def _launcher_path(self, app):
safe = app["key"].replace("/", "-").replace(" ", "_")
return APPLICATIONS_DIR / f"codemaster-{safe}.desktop"
def _launcher_icon_path(self, app):
safe = app["key"].replace("/", "__").replace(" ", "_")
return LAUNCHER_ICON_DIR / f"{safe}.png"
def has_launcher(self, app):
return self._launcher_path(app).exists()