-
-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathsetup_toshy.py
executable file
·3907 lines (3237 loc) · 171 KB
/
setup_toshy.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
__version__ = '20250208' # CLI option "--version" will print this out.
import os
os.environ['PYTHONDONTWRITEBYTECODE'] = '1' # prevent this script from creating cache files
import re
import sys
import pwd
import grp
import glob
import random
import string
import signal
import shutil
import sqlite3
import zipfile
import argparse
import builtins
import datetime
import platform
import textwrap
import subprocess
from subprocess import DEVNULL, PIPE
from typing import Dict, List, Tuple, Optional
# local imports
from lib.env_context import EnvironmentInfo
from lib.logger import debug, error, warn, info
from lib import logger
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
if os.name == 'posix' and os.geteuid() == 0:
error("This app should not be run as root/superuser. Exiting.")
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('~')
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
# Check if 'sudo' command is available to user
if not shutil.which('sudo'):
print("Error: 'sudo' not found. Installer will fail without it. Exiting.")
sys.exit(1)
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.qdbus = 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_url = 'https://github.com/RedBearAK/xwaykeyz.git'
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.app_switcher = None # Install/upgrade Application Switcher KWin script
self.tweak_applied = None
self.remind_extensions = 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:
return [self.py_interp_path, '-m', 'venv', self.venv_path]
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?
#
# invalidate the sudo ticket, don't leave system in "superuser" state
subprocess.run(['sudo', '-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 back the distro name (ID), distro version, session type and desktop
environment 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',
'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.
"""
# Retrieve environment variables and normalize strings where needed
colorterm_env = os.getenv('COLORTERM', '')
ls_colors_env = os.getenv('LS_COLORS', '')
term_env = os.getenv('TERM', '').lower()
# Check if COLORTERM environment variable is set and not empty
colorterm_set = bool(colorterm_env)
# Check if LS_COLORS environment variable is set and not empty
ls_colors_set = bool(ls_colors_env)
# Check if the TERM environment variable contains 'color'
term_is_color = "color" in term_env
# If any variable is truthy, terminal probably supports color codes
color_supported = colorterm_set or ls_colors_set or term_is_color
return color_supported
# 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_sudo_tkt_exp():
"""Utility function to emphasize the sudo password prompt"""
try:
subprocess.run( ['sudo', '-n', 'true'], stdout=DEVNULL, stderr=DEVNULL, check=True)
except subprocess.CalledProcessError:
main_clr = 'blue'
alt_clr = 'magenta'
# sudo ticket not valid, requires a password, so get user attention
print()
print(fancy_str(' ---------------------------------------- ', main_clr, bold=True))
# print(fancy_str(' -- SUDO PASSWORD REQUIRED TO CONTINUE -- ', 'blue', bold=True))
print(
fancy_str(' -- ', main_clr, bold=True) +
fancy_str('SUDO PASSWORD REQUIRED TO CONTINUE', alt_clr, bold=True) +
fancy_str(' -- ', main_clr, bold=True)
)
print(fancy_str(' ---------------------------------------- ', main_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 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']:
# 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 check_gnome_wayland_exts():
"""
Utility function to check for installed/enabled shell extensions compatible with the
keymapper, for supporting app-specific remapping in Wayland+GNOME sessions.
"""
if not cnfg.DESKTOP_ENV == 'gnome':
return
extensions_to_check = [
]
# 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 extensions_to_check:
if (os.path.exists(os.path.join(user_ext_dir, ext_uuid)) or
os.path.exists(os.path.join(sys_ext_dir, ext_uuid))):
installed_exts.append(ext_uuid)
# Check enabled state via gsettings
try:
cmd_lst = ['gsettings', 'get', 'org.gnome.shell', 'enabled-extensions']
if py_interp_ver_tup >= (3, 7):
result = subprocess.run(cmd_lst, capture_output=True, text=True)
elif py_interp_ver_tup == (3, 6):
result = subprocess.run(cmd_lst, stdout=PIPE, stderr=PIPE, universal_newlines=True)
# Versions older than 3.6 already blocked in code, right after safe_shutdown defined.
# Get raw string output and clean it
gsettings_output = result.stdout.strip()
# Parse the string safely - it's a list literal with single quotes
if gsettings_output.startswith('[') and gsettings_output.endswith(']'):
# Remove brackets and split on commas
raw_exts = gsettings_output[1:-1].split(',')
# Clean up each extension string
all_enabled_exts = [ext.strip().strip("'") for ext in raw_exts if ext.strip()]
else:
all_enabled_exts = []
# Filter to just our required extensions that are both installed and enabled
enabled_exts = [ext for ext in installed_exts if ext in all_enabled_exts]
except (subprocess.SubprocessError, ValueError):
enabled_exts = [] # Can't determine enabled state
if len(enabled_exts) >= 1:
# If at least one GNOME extension is enabled, everything is good
print()
print("A compatible GNOME shell extension is enabled for GNOME Wayland support. Good.")
print(f"Enabled extension(s) found:\n {enabled_exts}")
elif not enabled_exts and len(installed_exts) >= 1:
# If no GNOME extensions enabled, but at least one installed, remind user to enable
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()
elif not installed_exts:
# If no GNOME extension installed, remind user to install and enable one
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():
"""
Utility function to check for an installed and enabled GNOME shell extension for
supporting the display of app indicators in the top bar. Such as the extension
'AppIndicator and KStatusNotifierItem Support' maintained by Ubuntu.
"""
if not cnfg.DESKTOP_ENV == 'gnome':
return
extensions_to_check = [
]
# 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 extensions_to_check:
if (os.path.exists(os.path.join(user_ext_dir, ext_uuid)) or
os.path.exists(os.path.join(sys_ext_dir, ext_uuid))):
installed_exts.append(ext_uuid)
# Check enabled state via gsettings
try:
cmd_lst = ['gsettings', 'get', 'org.gnome.shell', 'enabled-extensions']
if py_interp_ver_tup >= (3, 7):
result = subprocess.run(cmd_lst, capture_output=True, text=True)
elif py_interp_ver_tup == (3, 6):
result = subprocess.run(cmd_lst, stdout=PIPE, stderr=PIPE, universal_newlines=True)
# Versions older than 3.6 already blocked in code, right after safe_shutdown defined.
# Get raw string output and clean it
gsettings_output = result.stdout.strip()
# Parse the string safely - it's a list literal with single quotes
if gsettings_output.startswith('[') and gsettings_output.endswith(']'):
# Remove brackets and split on commas
raw_exts = gsettings_output[1:-1].split(',')
# Clean up each extension string
all_enabled_exts = [ext.strip().strip("'") for ext in raw_exts if ext.strip()]
else:
all_enabled_exts = []
# Filter to just our required extensions that are both installed and enabled
enabled_exts = [ext for ext in installed_exts if ext in all_enabled_exts]
except (subprocess.SubprocessError, ValueError):
enabled_exts = [] # Can't determine enabled state
if len(enabled_exts) >= 1:
# If at least one GNOME extension is enabled, everything is good
print()
print("A compatible GNOME shell extension is enabled for system tray icons. Good.")
print(f"Enabled extension(s) found:\n {enabled_exts}")
elif not enabled_exts and len(installed_exts) >= 1:
# If no GNOME extensions enabled, but at least one installed, remind user to enable
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()
elif not installed_exts:
# If no GNOME extension installed, remind user to install and enable one
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 a sudo "incident" report unnecessarily
for _ in range(max_attempts):
response = input(
f'Is user "{cnfg.user_name}" an admin user that can run "sudo" commands? [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. Too many attempts.')
safe_shutdown(1)
if response.casefold() == 'y':
call_attn_to_pwd_prompt_if_sudo_tkt_exp()
try:
cmd_lst = ['sudo', 'bash', '-c', 'echo -e "\nUsing elevated privileges..."']
subprocess.run(cmd_lst, check=True)
except subprocess.CalledProcessError as proc_err:
print()
if cnfg.prep_only:
print()
error('ERROR: Problem invoking "sudo" command. Is this really an admin user?')
error('Only an admin user with sudo access can use "prep-only" command. Exiting.')
error('ERROR: Problem invoking "sudo" command. Try answering "n" to admin question.')
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
should also run when the admin user logs into a desktop session.
When using "su --login adminuser", that user will also need to
download an independent copy of the Toshy zip file to install from,
using a "wget" or "curl" command. Or use "sudo" to copy the zip
file from the unprivileged user's Downloads folder. See the Wiki
for a better example of the full "prep-only" sequence with a
separate admin user.
""")
print(md_wrapped_str)
print()
md_wrapped_str = md_wrap(width=55, text="""
If you understand everything written above or already took care
of prepping the system and want to proceed with an unprivileged
install, enter the secret code:
""")
response = input(md_wrapped_str)
if response == secret_code:
# set a flag to bypass functions that do system "prep" work with `sudo`
cnfg.unprivileged_user = True
print()
print("Good code. Continuing with an unprivileged install of Toshy user components...")
return
else:
print()
error('Code does not match! Try the installer again after installing Toshy \n'
' first using an admin user that has access to "sudo".')
safe_shutdown(1)
#####################################################################################################
### START OF NATIVE PACKAGE INSTALLER SECTION
#####################################################################################################
distro_groups_map: Dict[str, List[str]] = {
# separate references for RHEL types versus Fedora types
'fedora-based': ["fedora", "fedoralinux", "nobara", "ultramarine"],
'rhel-based': ["almalinux", "centos", "eurolinux", "oreon", "rhel", "rocky"],
# separate references for Fedora immutables using rpm-ostree
'fedora-immutables': ["bazzite", "kinoite", "silverblue"],
# separate references for Tumbleweed types, Leap types, MicroOS types
'tumbleweed-based': ["opensuse-tumbleweed", "tumbleweed"],
'leap-based': ["leap", "opensuse-leap"],
'microos-based': ["opensuse-aeon", "opensuse-kalpa", "opensuse-microos"],
'mandriva-based': ["openmandriva"],
'ubuntu-based': ["elementary", "mint", "neon", "pop", "tuxedo", "ubuntu", "zorin"],
'debian-based': ["debian", "deepin", "kali", "lmde", "peppermint", "q4os"],
'arch-based': ["arch", "arcolinux", "endeavouros", "garuda", "manjaro"],
'solus-based': ["solus"],
'void-based': ["void"],
# Attempted to add and test KaOS Linux. Result:
# KaOS is NOT compatible with this project.
# No packages provide "evtest", "libappindicator", "zenity".
# The KaOS repos seem highly restricted to only Qt/KDE related packages.
# Add more as needed...
}
# Checklist of distro type representatives with
# '/usr/bin/gdbus' pre-installed in clean VM:
#
# - AlmaLinux 8.x [Provided by 'glib2']
# - AlmaLinux 9.x [Provided by 'glib2']
# - CentOS 7 [Provided by 'glib2']
# - Fedora [Provided by 'glib2']
# - KDE Neon User Edition (Ubuntu 22.04 LTS) [Provided by 'libglib2.0-bin']
# - Manjaro KDE (Arch-based) [Provided by 'glib2']
# - OpenMandriva Lx 5.0 (Plasma Slim) [Provided by 'glib2.0-common']
# - openSUSE Leap 15.6 [Provided by 'glib2-tools']
# - Ubuntu 20.04 LTS [Provided by 'libglib2.0-bin']
# - Void Linux (rolling) [Provided by 'glib']
#
pkg_groups_map: Dict[str, List[str]] = {
# NOTE: Do not add 'gnome-shell-extension-appindicator' to Fedora/RHELs.
# This will install extension but requires logging out of GNOME to activate.
# Also, installing DE-specific packages is probably a bad idea.
'fedora-based': ["cairo-devel", "cairo-gobject-devel",
"dbus-daemon", "dbus-devel",
"evtest",
"gcc", "git", "gobject-introspection-devel",
"libappindicator-gtk3", "libnotify", "libxkbcommon-devel",
"python3-dbus", "python3-devel", "python3-pip", "python3-tkinter",
"systemd-devel",
"wayland-devel",
"xset",
"zenity"],
# NOTE: Do not add 'gnome-shell-extension-appindicator' to Fedora/RHELs.
# This will install extension but requires logging out of GNOME to activate.
# Also, installing DE-specific packages is probably a bad idea.
'rhel-based': ["cairo-devel", "cairo-gobject-devel",
"dbus-daemon", "dbus-devel",
"gcc", "git", "gobject-introspection-devel",
"libappindicator-gtk3", "libnotify", "libxkbcommon-devel",
"python3-dbus", "python3-devel", "python3-pip", "python3-tkinter",
"systemd-devel",
# The 'xdg-open' and 'xdg-mime' utils were missing on CentOS Stream 10,
# necessitating adding 'xdg-utils' as dependency. Very unusual.
"xdg-utils", "xset",
"zenity"],
# NOTE: Do not add 'gnome-shell-extension-appindicator' to Fedora/RHELs.
# This will install extension but requires logging out of GNOME to activate.
# Also, installing DE-specific packages is probably a bad idea.
'fedora-immutables': ["cairo-devel", "cairo-gobject-devel",
"dbus-daemon", "dbus-devel",
"evtest",
"gcc", "git", "gobject-introspection-devel",
"libappindicator-gtk3", "libnotify", "libxkbcommon-devel",
"python3-dbus", "python3-devel", "python3-pip", "python3-tkinter",
"systemd-devel",
"wayland-devel",
"xset",
"zenity"],
# NOTE: for openSUSE (Tumbleweed, not applicable to Leap):
# How to get rid of the need to use specific version numbers in packages:
# pkgconfig(packagename)>=N.nn (version symbols optional)
# How to query a package to see what the equivalent pkgconfig(packagename) syntax would be:
# rpm -q --provides packagename | grep -i pkgconfig
'tumbleweed-based': ["cairo-devel",
"dbus-1-daemon", "dbus-1-devel",
"gcc", "git", "gobject-introspection-devel",
"libappindicator3-devel", "libnotify-tools", "libxkbcommon-devel",
# f"python{py_pkg_ver_str}-dbus-python-devel",
"python3-dbus-python-devel",
# f"python{py_pkg_ver_str}-devel",
"python3-devel",
# f"python{py_pkg_ver_str}-tk",
"python3-tk",
"systemd-devel",
"tk", "typelib-1_0-AyatanaAppIndicator3-0_1",
"zenity"],
# TODO: update Leap Python package versions as it makes newer Python available
'leap-based': ["cairo-devel",
"dbus-1-devel",
"gcc", "git", "gobject-introspection-devel",
"libappindicator3-devel", "libnotify-tools", "libxkbcommon-devel",
"python311",
"python311-dbus-python-devel",
"python311-devel",
"python311-tk",
"systemd-devel",
"tk", "typelib-1_0-AyatanaAppIndicator3-0_1",
"zenity"],
# NOTE: This is a copy of Tumbleweed-based package list! For use with 'transactional-update'.
# But this needs to use the versioned package names because we are checking with 'rpm -q'.
'microos-based': ["cairo-devel",
"dbus-1-daemon", "dbus-1-devel",
"gcc", "git", "gobject-introspection-devel",
"libappindicator3-devel", "libnotify-tools", "libxkbcommon-devel",
f"python{py_pkg_ver_str}-dbus-python-devel",
# "python3-dbus-python-devel",
f"python{py_pkg_ver_str}-devel",
# "python3-devel",
f"python{py_pkg_ver_str}-tk",
# "python3-tk",
"systemd-devel",
"tk", "typelib-1_0-AyatanaAppIndicator3-0_1",
"zenity"],