-
-
Notifications
You must be signed in to change notification settings - Fork 38
Expand file tree
/
Copy pathsetup_toshy.py
More file actions
executable file
·4960 lines (4108 loc) · 217 KB
/
setup_toshy.py
File metadata and controls
executable file
·4960 lines (4108 loc) · 217 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
__version__ = '20260201' # CLI option "--version" will print this out.
import os
os.environ['PYTHONDONTWRITEBYTECODE'] = '1' # prevent this script from creating cache files
import re
import grp
import pwd
import sys
import glob
import random
import shutil
import signal
import string
import sqlite3
import zipfile
import argparse
import builtins
import datetime
import platform
import textwrap
import subprocess
from subprocess import DEVNULL, PIPE
# Type hints are about to become a problem due to issues between <3.9 and >3.15 Python releases.
# So we will have to remove many or most of them to retain 3.8-3.15+ compatibility.
# from typing import Dict, List, Tuple, Optional
# local imports
from toshy_common import logger
from toshy_common.env_context import EnvironmentInfo
from toshy_common.logger import debug, error, warn, info
logger.FLUSH = True
# Save the original print function
original_print = builtins.print
# Override the print function
def print(*args, **kwargs):
# Set flush to True, to force logging to be in correct order.
# Some terminals do weird buffering, cause out-of-order logs.
kwargs['flush'] = True
original_print(*args, **kwargs) # Call the original print
# Replace the built-in print with our custom print (where flush is always True)
builtins.print = print
def is_script_running_as_root():
"""Utility function to catch the user running the entire script as superuser/root,
which is undesirable since it is so user-oriented in nature. A simple check of
EUID == 0 does not cover non-sudo setups well."""
# Check environment indicators first (most reliable)
env_indicators = [
# Direct privilege elevation indicators
'SUDO_USER' in os.environ,
'DOAS_USER' in os.environ,
# Root user indicators
os.environ.get('USER') == 'root',
os.environ.get('LOGNAME') == 'root',
os.environ.get('HOME') == '/root',
]
if any(env_indicators):
return True
# Fall back to UID checks if environment doesn't indicate elevation
return os.geteuid() == 0 or os.getuid() == 0
if is_script_running_as_root():
print()
error("This setup script should not be run as root/superuser. Exiting.\n")
sys.exit(1)
def signal_handler(sig, frame):
"""Handle signals like Ctrl+C"""
if sig in (signal.SIGINT, signal.SIGQUIT):
# Perform any cleanup code here before exiting
# traceback.print_stack(frame)
print('\n')
debug(f'SIGINT or SIGQUIT received. Exiting.\n')
sys.exit(1)
if platform.system() != 'Windows':
signal.signal(signal.SIGINT, signal_handler)
signal.signal(signal.SIGQUIT, signal_handler)
signal.signal(signal.SIGHUP, signal_handler)
signal.signal(signal.SIGUSR1, signal_handler)
signal.signal(signal.SIGUSR2, signal_handler)
else:
signal.signal(signal.SIGINT, signal_handler)
error(f'This is only meant to run on Linux. Exiting.')
sys.exit(1)
original_PATH_str = os.getenv('PATH')
if original_PATH_str is None:
print()
error(f"ERROR: PATH variable is not set. This is abnormal. Exiting.")
print()
sys.exit(1)
# TODO: Integrate this into the rest of the setup script?
def get_linux_app_dirs(app_name):
# Default XDG directories
def_xdg_data_home = os.path.join(os.environ['HOME'], '.local', 'share')
def_xdg_config_home = os.path.join(os.environ['HOME'], '.config')
def_xdg_cache_home = os.path.join(os.environ['HOME'], '.cache')
def_xdg_state_home = os.path.join(os.environ['HOME'], '.local', 'state')
# Actual XDG directories on system
xdg_data_home = os.environ.get('XDG_DATA_HOME', def_xdg_data_home)
xdg_config_home = os.environ.get('XDG_CONFIG_HOME', def_xdg_config_home)
xdg_cache_home = os.environ.get('XDG_CACHE_HOME', def_xdg_cache_home)
xdg_state_home = os.environ.get('XDG_STATE_HOME', def_xdg_state_home)
app_dirs = {
'data_dir': os.path.join(xdg_data_home, app_name),
'config_dir': os.path.join(xdg_config_home, app_name),
'cache_dir': os.path.join(xdg_cache_home, app_name),
'log_dir': os.path.join(xdg_state_home, app_name)
}
return app_dirs
# Example usage
app_name = 'toshy'
app_dirs = get_linux_app_dirs(app_name)
# print(app_dirs)
home_dir = os.path.expanduser('~')
# This was being defined several times in different functions, for some reason. Moved to global.
autostart_dir_path = os.path.join(home_dir, '.config', 'autostart')
trash_dir = os.path.join(home_dir, '.local', 'share', 'Trash')
this_file_path = os.path.realpath(__file__)
this_file_dir = os.path.dirname(this_file_path)
this_file_name = os.path.basename(__file__)
if trash_dir in this_file_path or '/trash/' in this_file_path.lower():
print()
error(f"Path to this file:\n\t{this_file_path}")
error(f"You probably did not intend to run this from the TRASH. See path. Exiting.")
print()
sys.exit(1)
home_local_bin = os.path.join(home_dir, '.local', 'bin')
run_tmp_dir = os.environ.get('XDG_RUNTIME_DIR') or '/tmp'
good_path_tmp_file = 'toshy_installer_says_path_is_good'
good_path_tmp_path = os.path.join(run_tmp_dir, good_path_tmp_file)
fix_path_tmp_file = 'toshy_installer_says_fix_path'
fix_path_tmp_path = os.path.join(run_tmp_dir, fix_path_tmp_file)
# set a standard path for duration of script run, to avoid issues with user customized paths
os.environ['PATH'] = '/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin'
# deactivate Python virtual environment, if one is active, to avoid issues with sys.executable
if sys.prefix != sys.base_prefix:
os.environ["VIRTUAL_ENV"] = ""
sys.path = [p for p in sys.path if not p.startswith(sys.prefix)]
sys.prefix = sys.base_prefix
do_not_ask_about_path = None
if home_local_bin in original_PATH_str:
with open(good_path_tmp_path, 'a') as file:
file.write('Nothing to see here.')
# subprocess.run(['touch', path_good_tmp_path])
do_not_ask_about_path = True
else:
debug("Home user local bin not part of PATH string.")
# do the 'else' of creating 'path_fix_tmp_path' later in function that prompts user
# system Python version
py_ver_mjr, py_ver_mnr = sys.version_info[:2]
py_interp_ver_tup = (py_ver_mjr, py_ver_mnr)
py_pkg_ver_str = f'{py_ver_mjr}{py_ver_mnr}'
class InstallerSettings:
"""Set up variables for necessary information to be used by all functions"""
def __init__(self) -> None:
sep_reps = 80
self.sep_char = '='
self.separator = self.sep_char * sep_reps
self.DISTRO_ID = None
self.DISTRO_VER: str = ""
self.VARIANT_ID = None
self.SESSION_TYPE = None
self.DESKTOP_ENV = None
self.DE_MAJ_VER: str = ""
self.WINDOW_MGR = None
self.distro_mjr_ver: str = ""
self.distro_mnr_ver: str = ""
self.valid_KDE_vers = ['6', '5', '4', '3']
self.systemctl_present = shutil.which('systemctl') is not None
self.init_system = None
self.pkgs_for_distro = None
self.priv_elev_cmd = None
self.first_priv_elev_done = False # For secondary password prompts after timeouts
self.qdbus_cmd = self.find_qdbus_command()
# current stable Python release version (TODO: update when needed):
# 3.11 Release Date: Oct. 24, 2022
self.curr_py_rel_ver_mjr = 3
self.curr_py_rel_ver_mnr = 11
self.curr_py_rel_ver_tup = (self.curr_py_rel_ver_mjr, self.curr_py_rel_ver_mnr)
self.curr_py_rel_ver_str = f'{self.curr_py_rel_ver_mjr}.{self.curr_py_rel_ver_mnr}'
self.py_interp_ver_str = f'{py_ver_mjr}.{py_ver_mnr}'
self.py_interp_path = shutil.which('python3')
self.toshy_dir_path = os.path.join(home_dir, '.config', 'toshy')
self.db_file_name = 'toshy_user_preferences.sqlite'
self.db_file_path = os.path.join(self.toshy_dir_path, self.db_file_name)
self.backup_succeeded = None
self.existing_cfg_data = None
self.existing_cfg_slices = None
self.venv_path = os.path.join(self.toshy_dir_path, '.venv')
# This was changed to a property method that re-evaluates on each access:
# self.venv_cmd_lst = [self.py_interp_path, '-m', 'venv', self.venv_path]
self.keymapper_tmp_path = os.path.join(this_file_dir, 'keymapper-temp')
self.keymapper_branch = 'main' # new branch when switched to 'xwaykeyz'
self.keymapper_dev_branch = 'dev_beta' # branch to test new keymapper features
self.keymapper_cust_branch = None # Branch name provided by CLI flag argument
self.keymapper_url = 'https://github.com/RedBearAK/xwaykeyz.git'
# This was changed to a property method that re-evaluates on each access:
# self.keymapper_clone_cmd = f'git clone -b {self.keymapper_branch} {self.keymapper_url}'
self.input_group = 'input'
self.user_name = pwd.getpwuid(os.getuid()).pw_name
self.autostart_tray_icon = True
self.unprivileged_user = False
self.prep_only = None
# option flags for the "install" command:
self.override_distro = None # will be a string if not None
self.barebones_config = None
self.skip_native = None
self.fancy_pants = None
self.no_dbus_python = None
self.use_dev_keymapper = None
self.app_switcher = None # Install/upgrade Application Switcher KWin script
self.tweak_applied = None
self.remind_extensions = None
self.enabled_gnome_exts = None
self.should_reboot = None
self.run_tmp_dir = run_tmp_dir
self.reboot_tmp_file = f"{self.run_tmp_dir}/toshy_installer_says_reboot"
self.reboot_ascii_art = textwrap.dedent("""
██████ ███████ ██████ ██████ ██████ ████████ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██████ █████ ██████ ██ ██ ██ ██ ██ ██
██ ██ ██ ██ ██ ██ ██ ██ ██ ██
██ ██ ███████ ██████ ██████ ██████ ██ ██
""")
@property
def venv_cmd_lst(self):
# Originally a class instance attribute variable:
# self.venv_cmd_lst = [self.py_interp_path, '-m', 'venv', self.venv_path]
# Needs to re-evaluate itself when accessed, in case Python interpreter path changed:
is_AerynOS_based = cnfg.DISTRO_ID in distro_groups_map['aerynos-based']
# Add '--copies' flag to avoid using symlinks to system Python interpreter, and
# hopefully prevent Toshy from breaking when user does a dist-upgrade.
# (Didn't work for that purpose, but still a good idea for other reasons.)
if is_AerynOS_based:
# Use 'virtualenv' on AerynOS (formerly Serpent OS) because 'ensurepip' missing,
# which is a dependency for the 'venv' module.
return [self.py_interp_path, '-m', 'virtualenv', '--copies', self.venv_path]
return [self.py_interp_path, '-m', 'venv', '--copies', self.venv_path]
@property
def keymapper_clone_cmd(self):
# Originally a class instance attribute variable:
# self.keymapper_clone_cmd = f'git clone -b {self.keymapper_branch} {self.keymapper_url}'
if self.use_dev_keymapper:
if self.keymapper_cust_branch:
_km_branch = self.keymapper_cust_branch
else:
_km_branch = self.keymapper_dev_branch
else:
_km_branch = self.keymapper_branch
_clone_cmd = f'git clone -b {_km_branch} {self.keymapper_url}'
print(f"Keymapper clone command:\n {_clone_cmd}")
return _clone_cmd
def detect_elevation_command(self):
"""Detect the appropriate privilege elevation command"""
# Order of preference for elevation commands
known_privilege_elevation_cmds = ["sudo", "doas", "run0", "sudo-rs"]
print()
print(f"Checking for the following commands:\n {known_privilege_elevation_cmds}")
for cmd in known_privilege_elevation_cmds:
if shutil.which(cmd):
cnfg.priv_elev_cmd = cmd
print(f"Using the '{cmd}' command for privilege elevation (if needed).")
return
# If no elevation command found
error("No known privilege elevation command found. Cannot continue.")
safe_shutdown(1)
def find_qdbus_command(self):
# List of qdbus command names by preference
commands = ['qdbus6', 'qdbus-qt6', 'qdbus-qt5', 'qdbus']
for command in commands:
if shutil.which(command):
return command
# Fallback to 'qdbus' if none of the preferred options are found
return 'qdbus'
def safe_shutdown(exit_code: int):
"""do some stuff on the way out"""
# good place to do some file cleanup?
# Only sudo has a standard way to invalidate tickets
if cnfg.priv_elev_cmd in ['sudo', 'sudo-rs']:
# invalidate the sudo ticket, don't leave system in "superuser" state
subprocess.run([cnfg.priv_elev_cmd, '-k'])
print() # avoid crowding the prompt on exit
sys.exit(exit_code)
# Limit script to operating on Python 3.6 or later (e.g. CentOS 7, Leap, RHEL 8, etc.)
if py_interp_ver_tup < (3, 6):
print()
error(f"Python version is older than 3.6. This is untested and probably will not work.")
safe_shutdown(1)
def show_reboot_prompt():
"""show the big ASCII reboot prompt"""
print()
print()
print()
print(cnfg.separator)
print(cnfg.separator)
print(cnfg.reboot_ascii_art)
print(cnfg.separator)
print(cnfg.separator)
def get_environment_info():
"""Get the necessary info from the environment evaluation module"""
print(f'\n§ Getting environment information...\n{cnfg.separator}')
known_init_systems = {
'systemd': 'Systemd',
'init': 'SysVinit',
'upstart': 'Upstart',
'openrc': 'OpenRC',
'runit': 'Runit',
'dinit': 'Dinit',
'initng': 'Initng',
}
try:
with open('/proc/1/comm', 'r') as f:
cnfg.init_system = f.read().strip()
except (PermissionError, FileNotFoundError, OSError) as init_check_err:
error(f'ERROR: Problem when checking init system:\n\t{init_check_err}')
if cnfg.init_system:
if cnfg.init_system in known_init_systems:
init_sys_full_name = known_init_systems[cnfg.init_system]
print(f"The active init system is: '{cnfg.init_system}' ({init_sys_full_name})")
else:
print(f"Init system process unknown: '{cnfg.init_system}'")
else:
error("ERROR: Init system (process 1) could not be determined. (See above error.)")
print() # blank line after init system message
if cnfg.prep_only and not os.environ.get('XDG_SESSION_DESKTOP'):
# su-ing to an admin user will show no graphical environment info
# we don't care what it is, just that it is set to avoid errors in get_env_info()
os.environ['XDG_SESSION_DESKTOP'] = 'gnome'
if cnfg.prep_only and not os.environ.get('XDG_SESSION_TYPE'):
# su-ing to an admin user will show no graphical environment info
# we don't care what it is, just that it is set to avoid errors in get_env_info()
os.environ['XDG_SESSION_TYPE'] = 'x11'
# env_info_dct = env.get_env_info()
env_ctxt_getter = EnvironmentInfo()
env_info_dct = env_ctxt_getter.get_env_info()
# Avoid casefold() errors by converting all to strings
if cnfg.override_distro:
cnfg.DISTRO_ID = str(cnfg.override_distro).casefold()
else:
cnfg.DISTRO_ID = str(env_info_dct.get('DISTRO_ID', 'keymissing')).casefold()
cnfg.DISTRO_VER = str(env_info_dct.get('DISTRO_VER', 'keymissing')).casefold()
cnfg.VARIANT_ID = str(env_info_dct.get('VARIANT_ID', 'keymissing')).casefold()
cnfg.SESSION_TYPE = str(env_info_dct.get('SESSION_TYPE', 'keymissing')).casefold()
cnfg.DESKTOP_ENV = str(env_info_dct.get('DESKTOP_ENV', 'keymissing')).casefold()
cnfg.DE_MAJ_VER = str(env_info_dct.get('DE_MAJ_VER', 'keymissing')).casefold()
cnfg.WINDOW_MGR = str(env_info_dct.get('WINDOW_MGR', 'keymissing')).casefold()
# split out the major version from the minor version, if there is one
distro_ver_parts = cnfg.DISTRO_VER.split('.') if cnfg.DISTRO_VER else []
cnfg.distro_mjr_ver = distro_ver_parts[0] if distro_ver_parts else 'NO_VER'
cnfg.distro_mnr_ver = distro_ver_parts[1] if len(distro_ver_parts) > 1 else 'no_mnr_ver'
debug('Toshy installer sees this environment:'
f"\n\t DISTRO_ID = '{cnfg.DISTRO_ID}'"
f"\n\t DISTRO_VER = '{cnfg.DISTRO_VER}'"
f"\n\t VARIANT_ID = '{cnfg.VARIANT_ID}'"
f"\n\t SESSION_TYPE = '{cnfg.SESSION_TYPE}'"
f"\n\t DESKTOP_ENV = '{cnfg.DESKTOP_ENV}'"
f"\n\t DE_MAJ_VER = '{cnfg.DE_MAJ_VER}'"
f"\n\t WINDOW_MGR = '{cnfg.WINDOW_MGR}'"
'', ctx='EV')
def md_wrap(text: str, width: int = 80):
"""
Process and wrap text as if written in Markdown style, where double newlines signify
paragraph breaks. Single newlines are treated as a space for better formatting, unless
they are part of a paragraph break. Text is wrapped to the specified width (characters).
Text blocks can be indented like the surrounding code. The indenting will be removed.
Args:
text (str): The input text to wrap and print.
width (int): The maximum width of the wrapped text, default is 80.
"""
# Dedent the text to remove any common leading whitespace
text = textwrap.dedent(text)
# Detect and store any trailing spaces preceding the final newline
trailing_spaces = re.findall(r' +\n$', text)
if trailing_spaces:
# Extract the spaces from the list (only one element expected)
trailing_spaces = trailing_spaces[0][:-1] # Remove the newline character
else:
trailing_spaces = ''
# Replace explicit double newlines with a placeholder to preserve them
text = text.replace('\n\n', '\uffff')
# Replace single newlines (which are for code readability) with a space
text = text.replace('\n', ' ')
# Convert the placeholders back to double newlines
text = text.replace('\uffff', '\n\n')
# Wrap each paragraph separately to maintain intended formatting
paragraphs = text.split('\n\n')
# Join the string back together, applying wrap width.
wrapped_text = '\n\n'.join(textwrap.fill(paragraph, width=width) for paragraph in paragraphs)
# Clean up space inserted inappropriately beginning of joined string.
wrapped_text = re.sub(r'^[ ]+', '', wrapped_text)
# Clean up doubled spaces from a space being left at the end of a line.
wrapped_text = re.sub(' +', ' ', wrapped_text)
# Append any trailing spaces that were initially present
wrapped_text += trailing_spaces
# Return the wrapped_text string.
return wrapped_text
def check_term_color_code_support():
"""
Determine if the terminal supports ANSI color codes.
:return: True if color is probably supported, False otherwise.
"""
color_term_checks = [
bool(os.getenv('LS_COLORS', '')), # Most common - set on most Linux/Unix
"color" in os.getenv('TERM', '').lower(), # Very common - xterm-256color, etc.
bool(os.getenv('COLORTERM', '')), # Modern terminals
"256" in os.getenv('TERM', '').lower(), # 256-color terminals
os.getenv('TERM', '').lower().startswith("xterm") # xterm variants
]
return any(color_term_checks)
# Global variable to indicate that terminal supports ANSI color codes
term_supports_color_codes = check_term_color_code_support()
def fancy_str(text, color_name, *, bold=False, color_supported=term_supports_color_codes):
"""
Return text wrapped in the specified color code.
:param text: Text to be colorized.
:param color_name: Natural name of the color.
:param bold: Boolean to indicate if text should be bold.
:return: Colorized string if terminal likely supports it, otherwise the original string.
"""
color_codes = { 'red': '31', 'green': '32', 'yellow': '33', 'blue': '34',
'magenta': '35', 'cyan': '36', 'white': '37', 'default': '0'}
if color_supported and color_name in color_codes:
bold_code = '1;' if bold else ''
return f"\033[{bold_code}{color_codes[color_name]}m{text}\033[0m"
else:
return text
def call_attn_to_pwd_prompt_if_needed():
"""Utility function to emphasize the admin/superuser password prompt"""
if cnfg.priv_elev_cmd is None or cnfg.unprivileged_user:
error("Attention function was called with no elevation command, or unprivileged user.")
return # Skip if no elevation command or in unprivileged mode (should never happen)
if cnfg.priv_elev_cmd in ['sudo', 'doas', 'sudo-rs']:
try:
subprocess.run( [cnfg.priv_elev_cmd, '-n', 'true'],
stdout=DEVNULL, stderr=DEVNULL, check=True)
return
except subprocess.CalledProcessError:
# Password is needed, show the alert
pass
elif cnfg.priv_elev_cmd == 'run0':
try:
subprocess.run( [cnfg.priv_elev_cmd, '--no-ask-password', 'true'],
stdout=DEVNULL, stderr=DEVNULL, check=True)
return
except subprocess.CalledProcessError:
# Password is needed, show the alert
pass
else:
print()
error(f"Privilege elevation command '{cnfg.priv_elev_cmd}' is not handled in the\n"
" attention function. Please notify the dev to fix this error.\n")
return
# Get user attention if there is a password needed (prompt will appear after this)
main_clr = 'blue'
alt_clr = 'magenta'
print()
print(fancy_str(' ----------------------------------------- ', main_clr, bold=True))
print(
fancy_str(' -- ', main_clr, bold=True) +
fancy_str(' PASSWORD REQUIRED TO CONTINUE ', alt_clr, bold=True) +
fancy_str(' -- ', main_clr, bold=True)
)
print(fancy_str(' ----------------------------------------- ', main_clr, bold=True))
print()
# After native package install, the sudo timestamp may have expired.
# Block with input() so the user can return at their leisure before
# the actual sudo prompt appears (which has its own timeout).
if cnfg.first_priv_elev_done:
input(fancy_str(' Press Enter to continue (elevated privileges expired)... ',
alt_clr, bold=True))
print()
def enable_prompt_for_reboot():
"""Utility function to make sure user is reminded to reboot if necessary"""
cnfg.should_reboot = True
if not os.path.exists(cnfg.reboot_tmp_file):
os.mknod(cnfg.reboot_tmp_file)
def verify_device_permissions():
"""
Check if current user can access the devices the keymapper needs.
Returns (success: bool, error_message: str | None)
"""
uinput_path = '/dev/uinput'
input_dir = '/dev/input'
# Check /dev/uinput write access
if not os.path.exists(uinput_path):
return False, f"'{uinput_path}' does not exist"
if not os.access(uinput_path, os.W_OK):
return False, f"No write permission on '{uinput_path}'"
# Check /dev/input/event* read/write access
if not os.path.isdir(input_dir):
return False, f"'{input_dir}' directory does not exist"
for filename in os.listdir(input_dir):
if not filename.startswith('event'):
continue
event_path = os.path.join(input_dir, filename)
if os.access(event_path, os.R_OK | os.W_OK):
return True, None
return False, f"No accessible event devices in '{input_dir}'"
def verify_config_service_running():
"""Check if toshy-config.service is active."""
try:
result = subprocess.run(
['systemctl', '--user', 'is-active', 'toshy-config.service'],
capture_output=True, text=True, timeout=5
)
return result.stdout.strip() == 'active'
except (subprocess.SubprocessError, OSError):
return False
def can_skip_reboot():
"""
Determine if reboot can be skipped despite should_reboot being set.
If permissions are working and service is running, uaccess did its job.
"""
perms_ok, perms_msg = verify_device_permissions()
if not perms_ok:
debug(f"Permission check failed: {perms_msg}")
return False
if not verify_config_service_running():
debug("toshy-config.service is not active")
return False
return True
def show_task_completed_msg():
"""Utility function to show a standard message after each major section completes"""
print(fancy_str(' >> Task completed successfully << ', 'green', bold=True))
def generate_secret_code(length: int = 4) -> str:
"""Return a random upper/lower case ASCII letters string of specified length"""
return ''.join(random.choice(string.ascii_letters) for _ in range(length))
def dot_Xmodmap_warning():
"""Check for '.Xmodmap' file in user's home folder, show warning about mod key remaps"""
xmodmap_file_path = os.path.join(home_dir, '.Xmodmap')
if os.path.isfile(xmodmap_file_path):
print()
print(f'{cnfg.separator}')
print(f'{cnfg.separator}')
warn_str = "\t WARNING: You have an '.Xmodmap' file in your home folder!!!"
print(fancy_str(warn_str, "red"))
print(f' This can cause confusing PROBLEMS if you are remapping any modifier keys!')
print(f'{cnfg.separator}')
print(f'{cnfg.separator}')
print()
secret_code = generate_secret_code()
response = input(
f"You must take responsibility for the issues an '.Xmodmap' file may cause."
f"\n\n\t If you understand, enter the secret code '{secret_code}': "
)
if response == secret_code:
print()
info("Good code. User has taken responsibility for '.Xmodmap' file. Proceeding...\n")
else:
print()
error("Code does not match! Try the installer again after dealing with '.Xmodmap'.")
safe_shutdown(1)
def ask_is_distro_updated():
"""Ask user if the distro has recently been updated"""
print()
debug('NOTICE: It is ESSENTIAL to have your system completely updated.', ctx="!!")
print()
response = input('Have you updated your system recently? [y/N]: ')
if response not in ['y', 'Y']:
print()
error("Try the installer again after you've done a full system update. Exiting.")
safe_shutdown(1)
def ask_add_home_local_bin():
"""
Check if `~/.local/bin` is in original PATH. Done earlier in script.
Ask user if it is OK to add the `~/.local/bin` folder to the PATH permanently.
Create temp file to allow bincommands script to bypass question.
"""
if do_not_ask_about_path:
pass
else:
print()
response = input('The "~/.local/bin" folder is not in PATH. OK to add it? [Y/n]: ') or 'y'
if response in ['y', 'Y']:
# Let's prompt a reboot when we need to add local-bin to the PATH
cnfg.should_reboot = True
# create temp file that will get script to add local bin to path without asking
with open(fix_path_tmp_path, 'a') as file:
file.write('Nothing to see here.')
def ask_for_attn_on_info():
"""
Utility function to request confirmation of attention before
moving on in the install process.
"""
secret_code = generate_secret_code()
print()
response = input(
f"To show that you read the info just above, enter the secret code '{secret_code}': "
)
if response == secret_code:
print()
info("Good code. User has acknowledged reading the info above. Proceeding...\n")
else:
print()
error("Code does not match! Run the installer again and pay more attention...")
safe_shutdown(1)
def get_enabled_gnome_extensions():
"""
Get list of all enabled GNOME extensions (user and system).
Caches result in cnfg.enabled_gnome_exts for reuse.
"""
# Return cached result if already fetched
if cnfg.enabled_gnome_exts is not None:
return cnfg.enabled_gnome_exts
gnome_ext_cmd_exists = shutil.which('gnome-extensions') is not None
gsettings_cmd_exists = shutil.which('gsettings') is not None
# Prefer gnome-extensions CLI - it sees both user and system extensions
if gnome_ext_cmd_exists:
try:
cmd_lst = ['gnome-extensions', 'list', '--enabled']
output = subprocess.check_output(cmd_lst, stderr=DEVNULL)
cnfg.enabled_gnome_exts = output.decode().strip().splitlines()
debug("Used 'gnome-extensions' to get enabled extensions list")
return cnfg.enabled_gnome_exts
except subprocess.CalledProcessError as proc_err:
error(f"'gnome-extensions list --enabled' failed:\n\t{proc_err}")
else:
debug("Command 'gnome-extensions' not found", ctx="CG")
# Fallback: gsettings (only sees user-enabled extensions, not system defaults)
if gsettings_cmd_exists:
try:
cmd_lst = ['gsettings', 'get', 'org.gnome.shell', 'enabled-extensions']
output = subprocess.check_output(cmd_lst, stderr=DEVNULL)
raw_output = output.decode().strip()
if raw_output.startswith('[') and raw_output.endswith(']'):
raw_exts = raw_output[1:-1].split(',')
cnfg.enabled_gnome_exts = [
ext.strip().strip("'") for ext in raw_exts if ext.strip()
]
else:
cnfg.enabled_gnome_exts = []
debug("Used 'gsettings' to get enabled extensions list (user-enabled only)")
return cnfg.enabled_gnome_exts
except subprocess.CalledProcessError as proc_err:
error(f"'gsettings get enabled-extensions' failed:\n\t{proc_err}")
else:
debug("Command 'gsettings' not found", ctx="CG")
error("Unable to get enabled GNOME extensions: no suitable command available")
cnfg.enabled_gnome_exts = []
return cnfg.enabled_gnome_exts
def check_gnome_wayland_exts():
"""
Check for installed/enabled shell extensions compatible with the keymapper,
for supporting app-specific remapping in Wayland+GNOME sessions.
"""
if cnfg.DESKTOP_ENV != 'gnome':
return
wayland_ctx_extensions = [
'focused-window-dbus@flexagoon.com',
'window-calls-extended@hseliger.eu',
'xremap@k0kubun.com',
]
# Check for installed extensions
user_ext_dir = os.path.expanduser('~/.local/share/gnome-shell/extensions')
sys_ext_dir = '/usr/share/gnome-shell/extensions'
installed_exts = []
for ext_uuid in wayland_ctx_extensions:
user_path = os.path.join(user_ext_dir, ext_uuid)
sys_path = os.path.join(sys_ext_dir, ext_uuid)
if os.path.exists(user_path) or os.path.exists(sys_path):
installed_exts.append(ext_uuid)
# Check for enabled extensions
all_enabled_exts = get_enabled_gnome_extensions()
enabled_exts = [ext for ext in installed_exts if ext in all_enabled_exts]
if enabled_exts:
print()
print("A compatible GNOME shell extension is enabled for GNOME Wayland support. Good.")
print(f"Enabled extension(s) found:\n {enabled_exts}")
elif installed_exts:
print()
print(cnfg.separator)
print()
print("A shell extension is installed for GNOME Wayland support, but it is not enabled:")
print(f" {installed_exts}")
print("Enable any of the compatible GNOME shell extensions for GNOME Wayland support.")
print("Without this, app-specific keymapping will NOT work in a GNOME Wayland session.")
print(" (See 'Requirements' section in the Toshy README.)")
ask_for_attn_on_info()
else:
print()
print(cnfg.separator)
print()
print("No compatible shell extensions for GNOME Wayland session support were found...")
print("Install any of the compatible GNOME shell extensions for GNOME Wayland support.")
print("Without this, app-specific keymapping will NOT work in a GNOME Wayland session.")
print(" (See 'Requirements' section in the Toshy README.)")
ask_for_attn_on_info()
def check_gnome_indicator_ext():
"""
Check for an installed and enabled GNOME shell extension for supporting
the display of app indicators in the top bar.
"""
if cnfg.DESKTOP_ENV != 'gnome':
return
indicator_extensions = [
'appindicatorsupport@rgcjonas.gmail.com',
'ubuntu-appindicators@ubuntu.com',
'TopIcons@phocean.net',
'top-icons-redux@pop-planet.info',
'trayIconsReloaded@selfmade.pl',
]
# Check for installed extensions
user_ext_dir = os.path.expanduser('~/.local/share/gnome-shell/extensions')
sys_ext_dir = '/usr/share/gnome-shell/extensions'
installed_exts = []
for ext_uuid in indicator_extensions:
user_path = os.path.join(user_ext_dir, ext_uuid)
sys_path = os.path.join(sys_ext_dir, ext_uuid)
if os.path.exists(user_path) or os.path.exists(sys_path):
installed_exts.append(ext_uuid)
# Check for enabled extensions
all_enabled_exts = get_enabled_gnome_extensions()
enabled_exts = [ext for ext in installed_exts if ext in all_enabled_exts]
if enabled_exts:
print()
print("A compatible GNOME shell extension is enabled for system tray icons. Good.")
print(f"Enabled extension(s) found:\n {enabled_exts}")
elif installed_exts:
print()
print(cnfg.separator)
print()
print("There is a system tray indicator extension installed, but it is not enabled:")
print(f" {installed_exts}")
print("Without an extension enabled, the Toshy icon will NOT appear in the top bar.")
print(" (See 'Requirements' section in the Toshy README.)")
ask_for_attn_on_info()
else:
print()
print(cnfg.separator)
print()
print("Install any compatible GNOME shell extension for system tray icon support.")
print("Without an extension enabled, the Toshy icon will NOT appear in the top bar.")
print(" (See 'Requirements' section in the Toshy README.)")
ask_for_attn_on_info()
def check_kde_app_switcher():
"""
Utility function to check for the Application Switcher KWin script that enables
grouped-application-windows task switching in KDE/KWin environments.
"""
if not cnfg.DESKTOP_ENV == 'kde':
return
script_path = os.path.expanduser('~/.local/share/kwin/scripts/applicationswitcher')
if os.path.exists(script_path):
print()
print("Application Switcher KWin script is installed. Good.")
# Reinstall/upgrade the Application Switcher KWin script to make sure it is current
cnfg.app_switcher = True
else:
print()
result = input(
"Install a KWin script that enables macOS-like grouped window switching? [Y/n]: ")
if result.casefold() in ['y', 'yes', '']:
cnfg.app_switcher = True
elif result.casefold() not in ['n', 'no']:
error("Invalid input. Run the installer and try again.")
safe_shutdown(1)
def elevate_privileges():
"""Elevate privileges early in the installer process, or invoke unprivileged install"""
print() # blank line to separate
max_attempts = 3
# Ask politely if user is admin to avoid causing an "incident" report unnecessarily
for _ in range(max_attempts):
response = input(
f'Can user "{cnfg.user_name}" run admin commands (via sudo/doas/run0)? [y/n]: ')
if response.casefold() in ['y', 'n']:
# response is valid, so break loop and proceed with appropriate actions below
break
else:
print()
error("Response invalid. Valid responses are 'y' or 'n'.")
print() # blank line for separation, then continue loop
else: # this "else" belongs to the "for" loop
print()
error('Response invalid. Max attempts reached.')
safe_shutdown(1)
if response.casefold() == 'y':
cnfg.detect_elevation_command() # Get the actual command for elevated privileges
# Do this here, only if the privilege elevation command is 'sudo':
# Invalidate any `sudo` ticket that might be hanging around, to maximize
# the length of time before `sudo` might demand the password again
if cnfg.priv_elev_cmd == 'sudo':
try:
subprocess.run(['sudo', '-k'], check=True)
except subprocess.CalledProcessError as proc_err:
error(f"ERROR: 'sudo' found, but 'sudo -k' did not work. Very strange.\n{proc_err}")
call_attn_to_pwd_prompt_if_needed()
try:
cmd_lst = [cnfg.priv_elev_cmd, 'bash', '-c', 'echo -e "\nUsing elevated privileges..."']
subprocess.run(cmd_lst, check=True)
cnfg.first_priv_elev_done = True
except subprocess.CalledProcessError as proc_err:
print()
if cnfg.prep_only:
print()
error(f'ERROR: Problem invoking "{cnfg.priv_elev_cmd}" command. Not an admin user?')
error(f'Only a user with "{cnfg.priv_elev_cmd}" access can use "prep-only" command.')
error(f'Problem invoking the "{cnfg.priv_elev_cmd}" command.')
print('Try answering "n" to admin question next time.')
safe_shutdown(1)
elif response.casefold() == 'n':
secret_code = generate_secret_code()
print('\n\n')
print(fancy_str(
'ALERT! ALERT! ALERT! ALERT! ALERT! ALERT! ALERT! ALERT! ALERT! ALERT!\n',
color_name='red', bold=True))
md_wrapped_str = md_wrap(f"""
The secret code for this run is "{secret_code}". You will need this.
It is possible to install as an unprivileged user, but only after an
admin user first runs the full install or a "prep-only" sequence.
The admin user must install from a full desktop session, or from
a "su --login adminuser" shell instance. The admin user can do
just the "prep" steps with:
./{this_file_name} prep-only
... instead of using:
./{this_file_name} install
Use the "prep-only" command if it is not desired that Toshy