-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsource code
More file actions
4091 lines (3560 loc) · 173 KB
/
Copy pathsource code
File metadata and controls
4091 lines (3560 loc) · 173 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
"""
Appify 2.2.1 - Bug Fix Release
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
BUG FIXES/CLEANUP in 2.2.1
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Fixes & Improvements
Fixed an extension conflict between 7TV and FrankerFaceZ caused by recent 7TV changes
The update made chat unreadable.
Other Twitch-related presets are unaffected
FrankerFaceZ has been removed from presets to prevent breakage
Replaced Aniwatch preset (service appears unavailable) with Anikai
Ensures preset list remains functional and up to date
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
BUG FIXES in 2.2.0
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
FIX: Unsupported flag warning in Chromium-based PWAs on X11
--disable-gpu-sandbox was being passed to all Chromium browsers on X11 as
part of the Nvidia tearing fix. Chromium now flags this as an unsupported
command-line flag and displays a stability/security warning banner on every
launch. The flag has been removed — --use-gl=desktop and
--ignore-gpu-blocklist are sufficient to resolve screen tearing on Nvidia
hardware and neither triggers the warning.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
BUG FIXES in 2.1.4
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
FIX: Screen tearing on X11 with Nvidia (the main issue)
The root cause was that get_display_backend_flags() returned an empty string
for X11, leaving Chromium-based browsers without the flags needed for Nvidia's
direct rendering path. Two fixes were applied:
- Chromium on X11: Now passes --use-gl=desktop --ignore-gpu-blocklist
--disable-gpu-sandbox. This forces the native OpenGL backend (bypassing EGL
paths that cause tearing on Nvidia), ensures hardware acceleration isn't
wrongly blocked, and lifts the sandbox restriction that prevents Nvidia's
driver from using its own vsync. A regular browser isn't affected because it
runs in your desktop session context with full driver access — the PWA wrapper
was stripping that.
- Firefox on X11: Added layers.acceleration.force-enabled, layers.omtp.enabled,
gfx.webrender.all, and gfx.webrender.enabled to the generated user.js. Fresh
Firefox profiles default to software compositing on some Nvidia + distro
combos, which is why video in a regular browser profile (which has accumulated
these prefs over time) looks fine but the blank PWA profile tears.
FIX: Blank line in generated launcher scripts
When firefox_wayland_env was empty (e.g. Firefox on X11, or any Chromium
browser), firefox_wayland_env.rstrip('\n') resolved to "", which was inserted
as a literal empty string in the lines list — producing a stray blank line and
potentially confusing set -euo pipefail. Now conditionally included with
*([...] if ... else []).
FIX: launch_app_from_cli ignored per-app nice/ionice
The CLI launch path was reading nice/ionice from the global config only. It
now reads from profile_cfg first (the values stored at install time), falling
back to global defaults. Apps installed with custom CPU/I/O priorities now
launch with those priorities from the desktop shortcut.
FIX: _SNAP_NAMES dict recreated on every wrapper generation
The dict was defined inside make_launcher_wrapper, so it was allocated and
garbage-collected on every install/reinstall. Moved to module level as a
proper constant.
NEW: Firefox userChrome.css import
A "Firefox Advanced Options" frame appears in the UI only when Firefox is the
selected browser. It contains:
- A Browse… button to select a .css file via file chooser
- A Clear button to remove the selection
- A path label showing the currently selected file
When Install is clicked with a file selected:
- The source path is saved to profile.json as "userchrome_css_source" so it
persists across reinstalls and is restored when you re-select the app
- init_firefox_profile copies the file to <profile>/chrome/userChrome.css
- toolkit.legacyUserProfileCustomizations.stylesheets is always written to
user.js (Firefox ignores userChrome.css completely without this pref)
FIX: firefox_wayland_env NameError for Flatpak/Snap Firefox
The variable was initialised inside the native-only branch but used
unconditionally afterwards via +=. Flatpak and Snap Firefox wrappers would
crash with a NameError. Initialisation moved before all branch points.
FIX: DEFAULT_APPS youtube/youtube Music name casing
Entries were lowercase ("youtube", "youtube Music") but PRESET_DOMAIN_MAP and
DEFAULT_EXT_PRESETS use title case ("YouTube", "YouTube Music"), causing
extension preset lookups to silently fail. Now consistently cased.
FIX: Fresh install DEFAULT_CONFIG apps stored as list
DEFAULT_CONFIG["apps"] was DEFAULT_APPS (a list). A brand-new config has
config_version=2, so the list→dict migration was skipped, and any code doing
CONFIG["apps"][slug] = ... would raise TypeError. DEFAULT_CONFIG["apps"] is
now initialised as a dict via {slugify(a["name"]): a for a in DEFAULT_APPS}.
FIX: tarfile.extractall without members= filter (CVE-2007-4559 hardening)
The safe_members list built by _safe_member validation was not passed to
extractall, so new members could theoretically appear between getmembers()
and extractall(). Now passes members=safe_members explicitly on all Python
versions, plus filter="data" on 3.12+ for an additional stdlib-level guard.
FIX: Adw.init() called at module level
Calling Adw.init() at import time crashes any non-GUI use (e.g. --launch-app
from a desktop shortcut on a headless session, or unit tests). Moved inside
main() so it only runs when the GTK window is actually being created.
FIX: ext_frame NameError — main window crashed on open
ext_frame was used (ext_frame.set_label_widget(...)) before being assigned.
The missing ext_frame = Gtk.Frame() line has been added.
FIX: Custom extension saved without URL validation or allowlist check
on_add_custom_ext was saving any URL (including javascript: URIs and
malformed strings) to the profile before checking validity, and never applied
the _ALLOWED_EXT_HOSTS allowlist used elsewhere. Now validates against the
same allowlist before saving; shows an error dialog on rejection.
FIX: Clone silently overwrites app with conflicting slug
on_clone wrote to CONFIG["apps"][new_slug] without checking whether that slug
already existed. A name collision (e.g. cloning "YouTube" as "youtube") would
silently overwrite the existing entry. Now shows an error dialog instead.
FIX: _perform_install mutated live CONFIG["apps"] dict in-place
app["kiosk"], app["gamepad"], and app["browser"] were set directly on the
dict reference inside CONFIG["apps"], leaving the config in a half-mutated
state if an exception occurred before save_config(). Now works on a copy and
writes it back atomically.
FIX: PRESET_DOMAIN_MAP substring matching produced wrong preset matches
"youtube.com" matched "music.youtube.com" and "studio.youtube.com" before
their own entries because dict iteration is insertion-order and substring
matching was used. get_app_key() now sorts PRESET_DOMAIN_MAP by key length
descending so more-specific entries always win. Also fixed: DEFAULT_EXT_PRESETS
keys "twitch" and "kick" renamed to "Twitch" and "Kick" to match the title-
cased values in PRESET_DOMAIN_MAP.
FIX: Extensions marked as installed even when browser launch failed
on_install_presets called save_installed_extensions unconditionally after
launch_extension_manager, even if the browser never opened. launch_extension_manager
now returns True/False, and extensions are only recorded when True.
FIX: Update checker surfaced GitHub draft releases
check_for_updates only skipped prerelease=True but not draft=True. A draft
release would be returned as "latest" by the GitHub API and shown to users.
Now skips both.
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
FEATURES CARRIED FORWARD FROM 2.1.5
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
- INTELLIGENT BROWSER DETECTION: Auto-detects native vs Flatpak installations
- WAYLAND/X11 NATIVE SUPPORT: Automatically configures for your display server
- DEFAULT BROWSER DETECTION: Uses your system's default browser
- 8 Browsers fully supported: Firefox, Edge, Brave, Vivaldi, Chrome, Chromium,
Opera, Ungoogled Chromium
- Enhanced WebHID with full UI control for cloud gaming
- Auto icon download with corrected icon-cache path
- Extension presets with verified working URLs; --new-window for Chromium installs
- Kiosk, GPU, nice/ionice optimisation (per-app overrides in profile.json)
- Dark mode, full logging, Linux-first design with smart detection
- check_webhid_portal() — detects xdg-desktop-portal daemon + DE-specific backend
(kde/gnome/cosmic/hyprland/wlr/gtk) before enabling WebHID
- WebHID Gamepad checkbox shows non-blocking advisory dialog if portal not ready
- System info banner shows live WebHID portal status with tooltip
- config_version field (v2) — explicit migration from list→dict app storage
- Cloud gaming default apps auto-enable WebHID gamepad
- Install Custom dialog pre-fills browser from main combo
- Post-install/uninstall dropdown selection reliably re-synced
- Icon= uses absolute path so KDE Wayland resolves icons without cache
- Audio routing via PULSE_PROP removed — browser handles sound natively
- Firefox no longer receives --class/--name/--disable-gpu (unsupported flags)
- user.js JS string injection — backslash/quote escaping in app name & URL
- gtk-update-icon-cache called on correct hicolor theme directory
- save_config() runs after all runtime detections complete
- tar _safe_member: device files unconditionally rejected
"""
import gi
gi.require_version("Gtk", "4.0")
gi.require_version("Gdk", "4.0")
gi.require_version("Adw", "1")
from gi.repository import Gtk, Gio, GLib, Gdk, Adw
import os
import re
import sys
import io
import json
import shutil
import argparse
import subprocess
import tempfile
import shlex
import tarfile
import threading
import datetime
import logging
import stat
from urllib.parse import urlparse
from pathlib import Path
from packaging.version import Version
import gettext
CURRENT_VERSION = "2.2.1"
CONFIG_VERSION = 2 # Increment when the on-disk schema changes.
# ---------------- Logging (must be first — used throughout the module) --------
def _setup_logger() -> logging.Logger:
"""
Configures a module-level logger that writes to stderr.
A FileHandler is attached lazily once LOG_FILE's parent directory exists.
"""
logger = logging.getLogger("appify")
if logger.handlers:
return logger # Already configured (e.g. during tests).
logger.setLevel(logging.DEBUG)
fmt = logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
)
sh = logging.StreamHandler(sys.stderr)
sh.setFormatter(fmt)
logger.addHandler(sh)
return logger
_logger = _setup_logger()
def _ensure_file_log_handler():
"""Attaches a FileHandler to the module logger once LOG_FILE is available."""
for h in _logger.handlers:
if isinstance(h, logging.FileHandler):
return
try:
LOG_FILE.parent.mkdir(parents=True, exist_ok=True)
fh = logging.FileHandler(str(LOG_FILE), encoding="utf-8")
fh.setFormatter(logging.Formatter(
"%(asctime)s [%(levelname)s] %(message)s",
datefmt="%Y-%m-%dT%H:%M:%S",
))
_logger.addHandler(fh)
except Exception as exc:
_logger.warning("Could not attach file log handler: %s", exc)
def log_debug(msg: str):
"""Convenience wrapper — logs at DEBUG level."""
_ensure_file_log_handler()
_logger.debug(msg)
# ---------------- Internationalization (i18n) ----------------
def setup_i18n():
"""
Detects the system language and loads a matching appify.mo translation file.
Searches all standard locale directories used across Linux distros:
- Debian/Ubuntu: /usr/share/locale/
- Arch Linux: /usr/share/locale/
- Fedora/RHEL: /usr/share/locale/
- AppImage (bundled): $APPDIR/usr/share/locale/
- User-local override: ~/.local/share/locale/
- Next to this script: ./locale/ (dev/testing)
If no .mo file is found for the detected language, silently falls back
to English (identity function) — no errors, no crashes.
To add a translation:
1. Extract strings: xgettext -L Python -o appify.pot Appify.py
2. Create .po: msginit -l de_DE -o locale/de_DE/LC_MESSAGES/appify.po
3. Compile .mo: msgfmt locale/de_DE/LC_MESSAGES/appify.po -o locale/de_DE/LC_MESSAGES/appify.mo
4. Install .mo to: /usr/share/locale/de_DE/LC_MESSAGES/appify.mo
"""
lang = (
os.environ.get("LC_ALL")
or os.environ.get("LANGUAGE")
or os.environ.get("LANG")
or ""
).split(".")[0].split(":")[0]
if not lang or lang.lower().startswith("c") or lang.lower() == "posix":
return lambda s: s
search_dirs = []
search_dirs.append(Path.home() / ".local" / "share" / "locale")
appdir = os.environ.get("APPDIR")
if appdir:
search_dirs.append(Path(appdir) / "usr" / "share" / "locale")
for p in [
"/usr/share/locale",
"/usr/local/share/locale",
"/var/lib/flatpak/exports/share/locale",
"/snap/core/current/usr/share/locale",
]:
search_dirs.append(Path(p))
search_dirs.append(Path(__file__).parent / "locale")
lang_variants = [lang]
if "_" in lang:
lang_variants.append(lang.split("_")[0])
for locale_dir in search_dirs:
for lang_code in lang_variants:
mo_path = locale_dir / lang_code / "LC_MESSAGES" / "appify.mo"
if mo_path.exists():
try:
translation = gettext.translation(
domain="appify",
localedir=str(locale_dir),
languages=[lang_code],
fallback=False,
)
_logger.info("Loaded translation: %s", mo_path)
return translation.gettext
except Exception as e:
_logger.warning("Translation load failed (%s): %s", mo_path, e)
continue
return lambda s: s
_ = setup_i18n()
# ---------------- Browser Detection System ----------------
# Maps desktop-file stems (and Flatpak app-IDs) to our internal browser keys.
# A single authoritative constant used by all detection paths in
# get_default_browser() so that adding a new browser only requires one edit.
BROWSER_DESKTOP_MAP: dict[str, str] = {
# Firefox
"firefox": "firefox",
"org.mozilla.firefox": "firefox",
# Edge
"microsoft-edge": "edge",
"com.microsoft.edge": "edge",
"msedge": "edge",
"edge": "edge",
# Brave
"brave": "brave",
"brave-browser": "brave",
"com.brave.browser": "brave",
# Vivaldi
"vivaldi": "vivaldi",
"com.vivaldi.vivaldi": "vivaldi",
# Chrome
"google-chrome": "chrome",
"com.google.chrome": "chrome",
"chrome": "chrome",
# Chromium
"chromium": "chromium",
"chromium-browser": "chromium",
"org.chromium.chromium":"chromium",
# Opera
"opera": "opera",
"com.opera.opera": "opera",
}
# Maps our internal browser keys to snap package names (they differ for some
# browsers). Defined at module level so it is not recreated on every call to
# make_launcher_wrapper().
_SNAP_NAMES: dict[str, str] = {
"firefox": "firefox",
"edge": "microsoft-edge",
"brave": "brave",
"vivaldi": "vivaldi",
"chrome": "google-chrome",
"chromium": "chromium",
"opera": "opera",
"ungoogled-chromium": "ungoogled-chromium",
}
def is_wayland_session() -> bool:
"""Detects if the current session is Wayland"""
return bool(os.environ.get('WAYLAND_DISPLAY'))
def is_x11_session() -> bool:
"""Detects if the current session is X11"""
return bool(os.environ.get('DISPLAY')) and not is_wayland_session()
def get_session_type() -> str:
"""Returns 'wayland', 'x11', or 'unknown'"""
if is_wayland_session():
return "wayland"
elif is_x11_session():
return "x11"
return "unknown"
def detect_wayland_compositor() -> str:
"""
Detects the active Wayland compositor/desktop environment.
Returns one of: 'gnome', 'kde', 'sway', 'hyprland', 'wlroots',
'cosmic', 'wayfire', 'river', 'labwc', 'unknown'
Detection strategy (cheapest first):
1. Check well-known environment variables set by specific compositors.
2. Check XDG_CURRENT_DESKTOP / DESKTOP_SESSION.
3. Check SWAYSOCK / HYPRLAND_INSTANCE_SIGNATURE sockets.
4. Fall back to 'unknown'.
"""
if not is_wayland_session():
return "unknown"
# --- Direct compositor env vars ---
if os.environ.get("HYPRLAND_INSTANCE_SIGNATURE"):
return "hyprland"
if os.environ.get("SWAYSOCK"):
return "sway"
# --- Desktop environment vars ---
xdg = (os.environ.get("XDG_CURRENT_DESKTOP") or "").lower()
ds = (os.environ.get("DESKTOP_SESSION") or "").lower()
combined = f"{xdg} {ds}"
if "gnome" in combined:
return "gnome"
if "kde" in combined or "plasma" in combined:
return "kde"
if "sway" in combined:
return "sway"
if "hyprland" in combined:
return "hyprland"
if "cosmic" in combined:
return "cosmic"
if "wayfire" in combined:
return "wayfire"
if "river" in combined:
return "river"
if "labwc" in combined:
return "labwc"
# --- Try querying the compositor via wlr-randr / wayland socket heuristics ---
# Check running processes for well-known compositor binaries
try:
procs = subprocess.run(
["ps", "-eo", "comm"], capture_output=True, text=True, timeout=2
).stdout.lower()
if "gnome-shell" in procs:
return "gnome"
if "kwin_wayland" in procs:
return "kde"
if "sway" in procs:
return "sway"
if "hyprland" in procs:
return "hyprland"
if "cosmic-comp" in procs:
return "cosmic"
if "wayfire" in procs:
return "wayfire"
if "river" in procs:
return "river"
if "labwc" in procs:
return "labwc"
except Exception:
pass
return "unknown"
def get_display_backend_flags(browser_key: str = "") -> str:
"""
Returns appropriate display-backend flags for the current session and browser.
Rules:
• X11 → Nvidia tearing fix: --use-gl=desktop --ignore-gpu-blocklist
- --use-gl=desktop forces the native OpenGL backend, bypassing EGL
paths that cause tearing on Nvidia.
- --ignore-gpu-blocklist prevents Chromium from wrongly disabling
hardware acceleration on some Nvidia driver versions.
- Note: --disable-gpu-sandbox is intentionally NOT included; it
triggers an "unsupported flag" security warning in Chromium and
is not required for the tearing fix.
• Wayland + Chromium-based:
- Most compositors: --ozone-platform=wayland + window decoration hint
- KDE/KWin: also add UseWaylandDecorations (server-side decorations)
- GNOME Mutter: standard ozone flags work fine
- wlroots-based (sway, hyprland, river, labwc, wayfire):
add WaylandWindowDecorations + --enable-wayland-ime
• Unknown session → --ozone-platform-hint=auto (let Chromium decide)
Firefox is intentionally NOT touched here; its kiosk mode must not receive
--ozone or GDK_BACKEND flags as arguments (that breaks kiosk on Wayland).
Firefox Wayland support is handled via the environment in make_launcher_wrapper.
"""
session = get_session_type()
chromium_browsers = [
"edge", "brave", "vivaldi", "chrome", "chromium", "opera", "ungoogled-chromium"
]
if browser_key.lower() not in chromium_browsers:
# Firefox / unknown — handled elsewhere; return empty.
return ""
if session == "x11":
# On X11 with Nvidia, Chromium's default GPU path can produce screen
# tearing because it falls back to software compositing or uses EGL
# paths that bypass the driver's vsync. Forcing the native OpenGL
# backend (--use-gl=desktop) eliminates tearing on all tested Nvidia
# driver generations (470 – 550).
# --ignore-gpu-blocklist is needed on some driver versions where
# Chromium mistakenly blocks hardware acceleration for Nvidia cards.
# These flags are harmless on non-Nvidia hardware.
# --disable-gpu-sandbox is deliberately omitted: it causes Chromium to
# display an "unsupported command-line flag" security warning and is not
# necessary for the tearing fix.
return (
"--use-gl=desktop "
"--ignore-gpu-blocklist"
)
if session == "wayland":
compositor = detect_wayland_compositor()
base = "--ozone-platform=wayland --enable-features=UseOzonePlatform"
if compositor == "kde":
# KDE Plasma supports server-side window decorations via xdg-decoration.
return f"{base},WaylandWindowDecorations"
if compositor in ("sway", "hyprland", "river", "labwc", "wayfire"):
# wlroots compositors: add WaylandWindowDecorations + sandbox hint.
return (
f"{base},WaylandWindowDecorations "
"--enable-wayland-ime"
)
if compositor in ("gnome", "cosmic"):
# GNOME Mutter / COSMIC: standard flags; CSD handled by the toolkit.
return f"{base},WaylandWindowDecorations"
# Generic / unknown Wayland compositor: safe defaults.
return f"{base},WaylandWindowDecorations"
# Unknown session type: let Chromium auto-detect.
return "--ozone-platform-hint=auto"
def detect_browser_installation(browser_key: str) -> dict:
"""
Detects how a browser is installed and returns installation info.
Returns: {
'type': 'native' | 'flatpak' | 'snap' | 'not_found',
'cmd': actual command to use,
'display_name': human-readable name
}
"""
browsers_info = {
"firefox": {
"native_cmds": ["firefox", "/usr/bin/firefox"],
"flatpak": "org.mozilla.firefox",
"snap": "firefox",
"name": "Firefox"
},
"edge": {
"native_cmds": ["microsoft-edge", "microsoft-edge-stable"],
"flatpak": "com.microsoft.Edge",
"snap": "microsoft-edge",
"name": "Microsoft Edge"
},
"brave": {
"native_cmds": ["brave-browser-stable", "brave-browser", "brave"],
"flatpak": "com.brave.Browser",
"snap": "brave",
"name": "Brave"
},
"vivaldi": {
"native_cmds": ["vivaldi", "vivaldi-stable"],
"flatpak": "com.vivaldi.Vivaldi",
"snap": "vivaldi",
"name": "Vivaldi"
},
"chrome": {
"native_cmds": ["google-chrome", "google-chrome-stable"],
"flatpak": "com.google.Chrome",
"snap": "google-chrome",
"name": "Google Chrome"
},
"chromium": {
"native_cmds": ["chromium", "chromium-browser"],
"flatpak": "org.chromium.Chromium",
"snap": "chromium",
"name": "Chromium"
},
"opera": {
"native_cmds": ["opera", "opera-stable"],
"flatpak": "com.opera.Opera",
"snap": "opera",
"name": "Opera"
},
"ungoogled-chromium": {
"native_cmds": ["ungoogled-chromium"],
"flatpak": None,
"snap": None,
"name": "Ungoogled Chromium"
}
}
if browser_key not in browsers_info:
return {'type': 'not_found', 'cmd': '', 'display_name': browser_key}
info = browsers_info[browser_key]
# Check native installation first
for cmd in info["native_cmds"]:
if shutil.which(cmd):
return {
'type': 'native',
'cmd': cmd,
'display_name': f"{info['name']} (Native)"
}
# Check Flatpak
if info.get("flatpak"):
try:
result = subprocess.run(
["flatpak", "info", info["flatpak"]],
capture_output=True,
text=True,
timeout=2
)
if result.returncode == 0:
return {
'type': 'flatpak',
'cmd': f"flatpak run {info['flatpak']}",
'flatpak_id': info['flatpak'],
'display_name': f"{info['name']} (Flatpak)"
}
except Exception:
pass
# Check Snap
if info.get("snap"):
try:
result = subprocess.run(
["snap", "list", info["snap"]],
capture_output=True,
text=True,
timeout=2
)
if result.returncode == 0:
return {
'type': 'snap',
'cmd': f"snap run {info['snap']}",
'snap_name': info['snap'],
'display_name': f"{info['name']} (Snap)"
}
except Exception:
pass
return {
'type': 'not_found',
'cmd': '',
'display_name': f"{info['name']} (Not Installed)"
}
def get_default_browser() -> str:
"""
Detects the system's default browser.
Returns browser key like 'firefox', 'chrome', etc.
"""
try:
# Try xdg-settings first (most reliable)
result = subprocess.run(
["xdg-settings", "get", "default-web-browser"],
capture_output=True,
text=True,
timeout=2
)
if result.returncode == 0:
desktop_file = result.stdout.strip().lower()
# Map desktop file names to our browser keys
# Handles both simple names and reverse domain notation (com.company.App.desktop)
browser_map = BROWSER_DESKTOP_MAP
# First try exact match (without .desktop extension)
desktop_name = desktop_file.replace('.desktop', '')
if desktop_name in browser_map:
return browser_map[desktop_name]
# Then try substring matching
for key, browser_key in browser_map.items():
if key in desktop_file:
return browser_key
except Exception:
pass
# Try alternative method: check mimeapps.list
try:
mimeapps_paths = [
Path.home() / '.config/mimeapps.list',
Path.home() / '.local/share/applications/mimeapps.list',
Path('/etc/xdg/mimeapps.list'),
]
for mimeapps_path in mimeapps_paths:
if mimeapps_path.exists():
with open(mimeapps_path, 'r') as f:
content = f.read().lower()
# Look for text/html or x-scheme-handler/http handlers
browser_patterns = BROWSER_DESKTOP_MAP
# Check for text/html association
for pattern, browser_key in browser_patterns.items():
if f'text/html={pattern}' in content or f'x-scheme-handler/http={pattern}' in content:
return browser_key
except Exception:
pass
# Try gio (GNOME/GTK default handler)
try:
result = subprocess.run(
["gio", "mime", "x-scheme-handler/http"],
capture_output=True,
text=True,
timeout=2
)
if result.returncode == 0:
desktop_file = result.stdout.strip().lower()
browser_map = BROWSER_DESKTOP_MAP
for key, browser_key in browser_map.items():
if key in desktop_file:
return browser_key
except Exception:
pass
# Fallback: Return the first INSTALLED browser from this priority list
# This ensures we don't default to Firefox if it's not even installed
priority_order = ['edge', 'firefox', 'chrome', 'brave', 'chromium', 'vivaldi', 'opera']
for browser in priority_order:
detection = detect_browser_installation(browser)
if detection['type'] != 'not_found':
return browser
# Ultimate fallback - only if no browsers found at all
return 'firefox'
def scan_available_browsers() -> dict:
"""
Scans system for all available browsers.
Returns dict mapping browser_key to detection info.
"""
browsers = {}
for browser_key in ["firefox", "edge", "brave", "vivaldi", "chrome", "chromium", "opera", "ungoogled-chromium"]:
detection = detect_browser_installation(browser_key)
if detection['type'] != 'not_found':
browsers[browser_key] = detection
return browsers
# ---------------- XDG Desktop Portal Detection ----------------
# Maps compositor/DE names (as returned by detect_wayland_compositor()) to the
# package/binary name of the portal backend that provides device-permission
# dialogs (including WebHID/gamepad). Used only for advisory warnings — the
# browser itself still works without the portal, but the user may be silently
# denied HID access.
_PORTAL_BACKENDS: dict[str, str] = {
"kde": "xdg-desktop-portal-kde",
"gnome": "xdg-desktop-portal-gnome",
"cosmic": "xdg-desktop-portal-cosmic",
"hyprland": "xdg-desktop-portal-hyprland",
"sway": "xdg-desktop-portal-wlr",
"river": "xdg-desktop-portal-wlr",
"labwc": "xdg-desktop-portal-wlr",
"wayfire": "xdg-desktop-portal-wlr",
# X11 / generic Wayland sessions use the GTK portal as a safe default.
"x11": "xdg-desktop-portal-gtk",
"unknown": "xdg-desktop-portal-gtk",
}
def check_webhid_portal() -> dict:
"""
Checks whether the xdg-desktop-portal stack required for WebHID/gamepad
device-permission dialogs is present and running.
Returns a dict with keys:
'ok' (bool) – True if everything needed appears to be in place.
'portal' (str) – Name of the portal backend we looked for.
'reason' (str) – Human-readable explanation when ok=False.
'running' (bool) – Whether xdg-desktop-portal daemon is running.
'backend_found' (bool) – Whether the DE-specific backend binary exists.
Detection strategy (cheapest checks first):
1. Verify the base xdg-desktop-portal binary is on PATH.
2. Check whether the portal daemon is running (via pgrep or D-Bus).
3. Determine which DE-specific backend is expected for the current session.
4. Check whether that backend binary exists on PATH or in /usr/libexec/.
"""
compositor = detect_wayland_compositor() if is_wayland_session() else "x11"
portal_pkg = _PORTAL_BACKENDS.get(compositor, "xdg-desktop-portal-gtk")
result: dict = {
"ok": False,
"portal": portal_pkg,
"reason": "",
"running": False,
"backend_found": False,
}
# ── Step 1: base portal binary ────────────────────────────────────────────
if not shutil.which("xdg-desktop-portal"):
result["reason"] = (
"xdg-desktop-portal is not installed. "
"WebHID/gamepad permission dialogs will not appear and device access "
"may be silently denied by the browser sandbox."
)
return result
# ── Step 2: is the portal daemon running? ─────────────────────────────────
try:
pgrep = subprocess.run(
["pgrep", "-x", "xdg-desktop-por"], # process name is truncated by kernel
capture_output=True, timeout=2,
)
if pgrep.returncode != 0:
# Try the full name in case the kernel didn't truncate it.
pgrep = subprocess.run(
["pgrep", "-f", "xdg-desktop-portal"],
capture_output=True, timeout=2,
)
result["running"] = pgrep.returncode == 0
except Exception:
result["running"] = False
# ── Step 3: check for the DE-specific backend binary ─────────────────────
# Backends typically live in /usr/libexec/ or /usr/lib/ rather than on PATH.
extra_dirs = [
"/usr/libexec",
"/usr/lib/xdg-desktop-portal",
"/usr/lib",
"/usr/local/libexec",
]
backend_found = bool(shutil.which(portal_pkg))
if not backend_found:
# Also search libexec directories.
backend_found = any(
(Path(d) / portal_pkg).exists() for d in extra_dirs
)
result["backend_found"] = backend_found
# ── Step 4: synthesise result ─────────────────────────────────────────────
if not result["running"]:
result["reason"] = (
f"xdg-desktop-portal is installed but not running. "
f"Start it with: systemctl --user start xdg-desktop-portal"
)
return result
if not backend_found:
result["reason"] = (
f"The portal daemon is running but the {compositor.upper()} backend "
f"({portal_pkg}) was not found. "
f"Install it with your package manager to enable WebHID/gamepad "
f"permission dialogs."
)
return result
result["ok"] = True
result["reason"] = f"Portal OK ({portal_pkg} present and daemon running)"
return result
# ---------------- Utilities ----------------
def slugify(text: str) -> str:
"""Converts a string to a URL-friendly slug."""
return re.sub(r"[^a-z0-9]+", "-", text.lower()).strip("-")
def sanitize_shell_string(value: str) -> str:
"""
Strips characters that could be interpreted as shell metacharacters when a
value is interpolated inside a double-quoted bash string.
We allow the full URL character-set (RFC 3986 unreserved + common
sub-delimiters) plus a small whitelist of extras that appear legitimately
in app names and paths. Anything outside that set is silently removed.
This is a defence-in-depth measure. Values are also always placed inside
double-quoted strings in the generated bash scripts, but stripping
metacharacters prevents backtick/dollar/quote injection even if quoting is
accidentally omitted in a future edit.
Safe chars kept:
- Alphanumerics and _ - . ~ (URL unreserved)
- : / ? = & # % + @ (URL sub-delimiters / path / query)
- Space (common in app names)
"""
return re.sub(r'[^a-zA-Z0-9 _.~/:?=&#%+@-]', '', value)
def get_browsers():
"""Returns the browser configuration dictionary."""
return CONFIG.get("browsers", DEFAULT_CONFIG.get("browsers", {}))
def get_profile_dir(app: dict) -> Path:
"""Calculates the PWA's isolated profile directory path."""
app_name = app.get("name", "untitled")
return CONFIG_DIR / "profiles" / slugify(app_name)
def profile_config_path(app: dict) -> Path:
"""Calculates the path to the profile's config file."""
return get_profile_dir(app) / "profile.json"
def load_profile_config(app: dict) -> dict:
"""Loads the config for a specific PWA profile."""
p = profile_config_path(app)
if p.exists():
try:
return json.loads(p.read_text())
except Exception:
return {}
return {}
def save_profile_config(app: dict, data: dict):
"""Saves the config for a specific PWA profile atomically with owner-only permissions."""
pd = get_profile_dir(app)
pd.mkdir(parents=True, exist_ok=True)
target = profile_config_path(app)
tmp = target.with_suffix(".json.tmp")
try:
tmp.write_text(json.dumps(data, indent=2), encoding="utf-8")
tmp.chmod(0o600)
tmp.rename(target)
except Exception as exc:
_logger.error("save_profile_config failed: %s", exc)
tmp.unlink(missing_ok=True)
raise
def get_hostname_from_url(url: str) -> str:
"""Extracts the clean hostname from a URL."""
try:
parsed = urlparse(url)
hostname = parsed.netloc or parsed.path
return hostname.replace('www.', '').split('/')[0].split(':')[0]
except Exception:
return ""
def check_for_updates(callback):
"""
Checks GitHub for a newer release in a background thread, then calls
*callback* with a notification message or None.
Uses only stdlib (urllib) so the `requests` package is not required.
"""
def _check():
try:
import urllib.request
import ssl
url = "https://api.github.com/repos/bobbycomet/Appify/releases/latest"
ctx = ssl.create_default_context() # Validates server certificate.
req = urllib.request.Request(
url,
headers={"Accept": "application/vnd.github+json", "User-Agent": f"Appify/{CURRENT_VERSION}"},
)
with urllib.request.urlopen(req, context=ctx, timeout=8) as resp:
if resp.status != 200:
return
data = json.loads(resp.read().decode())
if data.get("prerelease") or data.get("draft"):
return
latest_tag = data["tag_name"].lstrip("v")
latest_version = Version(latest_tag)
current_version = Version(CURRENT_VERSION)
if latest_version > current_version:
msg = f"New version available: {data['tag_name']}!\nDownload from GitHub Releases."
GLib.idle_add(callback, msg)
except Exception as exc:
_logger.debug("Update check failed: %s", exc)
threading.Thread(target=_check, daemon=True).start()
# ---------------- Extension Helpers ----------------
def get_app_key(app):
hostname = get_hostname_from_url(app.get("url", ""))
# Sort by key length descending so more-specific entries (e.g.
# "music.youtube.com") are checked before shorter ones ("youtube.com")
# and we don't accidentally match the wrong preset via substring.
for domain_substring, preset_key in sorted(
PRESET_DOMAIN_MAP.items(), key=lambda kv: len(kv[0]), reverse=True
):
if domain_substring in hostname:
# Normalize to match DEFAULT_EXT_PRESETS keys (case-insensitive).
normalized = next(