Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rework group code, KWin app switcher install #96

Merged
merged 3 commits into from
Oct 24, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
163 changes: 93 additions & 70 deletions setup_toshy.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
import textwrap
import subprocess

from subprocess import DEVNULL
from subprocess import DEVNULL, PIPE
from typing import Dict

# local import
Expand Down Expand Up @@ -154,7 +154,7 @@ def __init__(self) -> None:
self.keyszer_url = 'https://github.com/RedBearAK/keyszer.git'
self.keyszer_clone_cmd = f'git clone -b {self.keyszer_branch} {self.keyszer_url}'

self.input_group_name = 'input'
self.input_group = 'input'
self.user_name = pwd.getpwuid(os.getuid()).pw_name

self.barebones_config = None
Expand Down Expand Up @@ -281,7 +281,7 @@ def call_attention_to_password_prompt():
print()


def prompt_for_reboot():
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):
Expand Down Expand Up @@ -569,13 +569,6 @@ def __init__(self) -> None:

def handle_quirks_CentOS_7(self):
print('Doing prep/checks for CentOS 7...')
# remove these from package list, not available on CentOS 7
# pkgs_to_remove = ['dbus-daemon', 'gnome-shell-extension-appindicator']
# _pkgs_for_distro: list = cnfg.pkgs_for_distro # type hinting for VSCode
# for pkg in pkgs_to_remove:
# if pkg in cnfg.pkgs_for_distro:
# _pkgs_for_distro.remove(pkg)
# cnfg.pkgs_for_distro = _pkgs_for_distro

native_pkg_installer.check_for_pkg_mgr_cmd('yum')
yum_cmd_lst = ['sudo', 'yum', 'install', '-y']
Expand Down Expand Up @@ -831,8 +824,7 @@ def install_on_rpmostree_distro():
# Filter out packages that are already installed
filtered_pkg_lst = []
for pkg in cnfg.pkgs_for_distro:
result = subprocess.run(["rpm", "-q", pkg],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
result = subprocess.run(["rpm", "-q", pkg], stdout=PIPE, stderr=PIPE)
if result.returncode != 0:
filtered_pkg_lst.append(pkg)
else:
Expand Down Expand Up @@ -1002,7 +994,7 @@ def reload_udev_rules():
print('Reloaded the "udev" rules successfully.')
except subprocess.CalledProcessError as proc_err:
print(f'Failed to reload "udev" rules:\n\t{proc_err}')
prompt_for_reboot()
enable_prompt_for_reboot()


def install_udev_rules():
Expand Down Expand Up @@ -1042,59 +1034,70 @@ def install_udev_rules():
show_task_completed_msg()


def create_group(group_name):
"""Utility function to create the specified group if it does not already exist."""
try:
grp.getgrnam(group_name)
print(f'Group "{group_name}" already exists.')
except KeyError:
print(f'Creating "{group_name}" group...')
call_attention_to_password_prompt()
if cnfg.DISTRO_NAME in distro_groups_map['fedora-immutables']:
# Special handling for Fedora immutable distributions
with open('/etc/group') as f:
if not re.search(rf'^{group_name}:', f.read(), re.MULTILINE):
# https://docs.fedoraproject.org/en-US/fedora-silverblue/troubleshooting/
# Special command to make Fedora Silverblue/uBlue work, or usermod will fail:
# grep -E '^input:' /usr/lib/group | sudo tee -a /etc/group
command = f"grep -E '^{group_name}:' /usr/lib/group | sudo tee -a /etc/group >/dev/null"
try:
subprocess.run(command, shell=True, check=True)
print(f"Added '{group_name}' group to system.")
except subprocess.CalledProcessError as proc_err:
error(f"Problem adding '{group_name}' group to system.\n\t{proc_err}")
safe_shutdown(1)
else:
try:
cmd_lst = ['sudo', 'groupadd', group_name]
subprocess.run(cmd_lst, check=True)
print(f'Group "{group_name}" created successfully.')
except subprocess.CalledProcessError as proc_err:
print()
error(f'ERROR: Problem when trying to create "input" group.\n')
err_output: bytes = proc_err.output # Type hinting the error output variable
# Deal with possible 'NoneType' error output
error(f'Command output:\n{err_output.decode() if err_output else "No error output"}')
safe_shutdown(1)


def verify_user_groups():
"""Check if the `input` group exists and user is in group"""
print(f'\n\n§ Checking if user is in "input" group...\n{cnfg.separator}')
#
if cnfg.DISTRO_NAME == 'silverblue-experimental':
# https://docs.fedoraproject.org/en-US/fedora-silverblue/troubleshooting/
# Special command to make Fedora Silverblue/uBlue work, or usermod will fail:
# grep -E '^input:' /usr/lib/group | sudo tee -a /etc/group
command = "grep -E '^input:' /usr/lib/group | sudo tee -a /etc/group >/dev/null"
subprocess.run(command, shell=True, check=True)
#
try:
grp.getgrnam(cnfg.input_group_name)
except KeyError:
# The group doesn't exist, so create it
print(f'Creating "input" group...')
try:
call_attention_to_password_prompt()
subprocess.run(['sudo', 'groupadd', cnfg.input_group_name], check=True)
except subprocess.CalledProcessError as proc_err:
print()
error(f'ERROR: Problem when trying to create "input" group.\n')
err_output: bytes = proc_err.output # Type hinting the error output variable
# Deal with possible 'NoneType' error output
error(f'Command output:\n{err_output.decode() if err_output else "No error output"}')
print()
error(f'ERROR: Install failed.')
safe_shutdown(1)
#
create_group(cnfg.input_group)
# Check if the user is already in the `input` group
group_info = grp.getgrnam(cnfg.input_group_name)
group_info = grp.getgrnam(cnfg.input_group)
if cnfg.user_name in group_info.gr_mem:
print(f'User "{cnfg.user_name}" is a member of '
f'group "{cnfg.input_group_name}".')
f'group "{cnfg.input_group}".')
else:
# Add the user to the input group
try:
call_attention_to_password_prompt()
subprocess.run(
['sudo', 'usermod', '-aG', cnfg.input_group_name, cnfg.user_name], check=True)
['sudo', 'usermod', '-aG', cnfg.input_group, cnfg.user_name], check=True)
except subprocess.CalledProcessError as proc_err:
print()
error(f'ERROR: Problem when trying to add user "{cnfg.user_name}" to '
f'group "{cnfg.input_group_name}".\n')
f'group "{cnfg.input_group}".\n')
err_output: bytes = proc_err.output # Type hinting the error output variable
# Deal with possible 'NoneType' error output
error(f'Command output:\n{err_output.decode() if err_output else "No error output"}')
print()
error(f'ERROR: Install failed.')
safe_shutdown(1)
#
print(f'User "{cnfg.user_name}" added to group "{cnfg.input_group_name}".')
prompt_for_reboot()
print(f'User "{cnfg.user_name}" added to group "{cnfg.input_group}".')
enable_prompt_for_reboot()
show_task_completed_msg()


Expand Down Expand Up @@ -1487,7 +1490,7 @@ def setup_kwin2dbus_script():
# Try to remove any installed KWin script entirely
process = subprocess.Popen(
['kpackagetool5', '-t', 'KWin/Script', '-r', kwin_script_name],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout=PIPE, stderr=PIPE)
out, err = process.communicate()
out = out.decode('utf-8')
err = err.decode('utf-8')
Expand All @@ -1502,7 +1505,7 @@ def setup_kwin2dbus_script():
# Install the KWin script
process = subprocess.Popen(
['kpackagetool5', '-t', 'KWin/Script', '-i', script_tmp_file],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout=PIPE, stderr=PIPE)
out, err = process.communicate()
out = out.decode('utf-8')
err = err.decode('utf-8')
Expand All @@ -1522,8 +1525,7 @@ def setup_kwin2dbus_script():
# Enable the script using kwriteconfig5
process = subprocess.Popen(
[ 'kwriteconfig5', '--file', 'kwinrc', '--group', 'Plugins', '--key',
f'{kwin_script_name}Enabled', 'true'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
f'{kwin_script_name}Enabled', 'true'], stdout=PIPE, stderr=PIPE)
out, err = process.communicate()
out = out.decode('utf-8')
err = err.decode('utf-8')
Expand Down Expand Up @@ -1717,28 +1719,49 @@ def apply_tweaks_KDE():
# git clone https://github.com/nclarius/kwin-application-switcher.git
# cd kwin-application-switcher
# ./install.sh
switcher_url = 'https://github.com/nclarius/kwin-application-switcher.git'
switcher_dir = 'kwin-application-switcher'
script_path = os.path.dirname(os.path.realpath(__file__))
switcher_dir_path = os.path.join(script_path, switcher_dir)
#
# switcher_url = 'https://github.com/nclarius/kwin-application-switcher.git'

# TODO: Revert to main repo if/when patch for this is accepted.
# Patched branch that fixes some issues with maintaining grouping:
# 'https://github.com/RedBearAK/kwin-application-switcher/tree/grouping_fix'

switcher_branch = 'grouping_fix'
switcher_repo = (
'https://github.com/RedBearAK/kwin-application-switcher.git'
)

switcher_dir_name = 'kwin-application-switcher'
switcher_dir_path = os.path.join(this_file_dir, switcher_dir_name)
switcher_title = 'KWin Application Switcher'
switcher_cloned = False

git_clone_cmd = ['git', 'clone', '--branch',
switcher_branch, switcher_repo, switcher_dir_path]

# git should be installed by this point? Not necessarily.
if shutil.which('git'):
if not shutil.which('git'):
error(f"Unable to clone {switcher_title}. Install 'git' and try again.")
else:
if os.path.exists(switcher_dir_path):
try:
shutil.rmtree(switcher_dir_path)
except (FileNotFoundError, PermissionError, OSError) as file_err:
warn(f'Problem removing existing switcher clone folder:\n\t{file_err}')
try:
if os.path.exists(switcher_dir_path):
try:
shutil.rmtree(switcher_dir_path)
except (FileNotFoundError, PermissionError, OSError) as file_err:
error(f'Problem removing existing switcher clone folder:\n\t{file_err}')
subprocess.run(["git", "clone", switcher_url, switcher_dir_path], check=True,
stdout=DEVNULL, stderr=DEVNULL)
command_dir = os.path.join(script_path, switcher_dir)
subprocess.run(["./install.sh"], cwd=command_dir, check=True,
stdout=DEVNULL, stderr=DEVNULL)
print(f'Installed "Application Switcher" KWin script.')
subprocess.run(git_clone_cmd, check=True) # , stdout=DEVNULL, stderr=DEVNULL)
switcher_cloned = True
except subprocess.CalledProcessError as proc_err:
error(f'Something went wrong installing KWin Application Switcher.\n\t{proc_err}')
else:
error(f"ERROR: Unable to clone KWin Application Switcher. 'git' not installed.")
warn(f'Problem while cloning the {switcher_title} branch:\n\t{proc_err}')
if not switcher_cloned:
warn(f'Unable to install {switcher_title}. Clone did not succeed.')
else:
try:
subprocess.run(["./install.sh"], cwd=switcher_dir_path, check=True,
stdout=DEVNULL, stderr=DEVNULL)
print(f'Installed "{switcher_title}" KWin script.')
except subprocess.CalledProcessError as proc_err:
warn(f'Something went wrong installing {switcher_title}.\n\t{proc_err}')

do_kwin_reconfigure()

Expand Down Expand Up @@ -1775,7 +1798,7 @@ def apply_tweaks_KDE():
if shutil.which('kquitapp5'):
print('Stopping Plasma shell... ', flush=True, end='')
subprocess.run(['kquitapp5', 'plasmashell'], check=True,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout=PIPE, stderr=PIPE)
print('Plasma shell stopped.')
else:
error('The "kquitapp5" command is not found. Skipping plasmashell restart.')
Expand All @@ -1784,7 +1807,7 @@ def apply_tweaks_KDE():
error(f'\nProblem while stopping Plasma shell:\n\t{err_output.decode()}')

print('Starting Plasma shell (backgrounded)... ')
subprocess.Popen(['kstart5', 'plasmashell'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
subprocess.Popen(['kstart5', 'plasmashell'], stdout=PIPE, stderr=PIPE)

# THIS STUFF DOESN'T SEEM TO WORK!
# Disable "sort folders first" option in Dolphin:
Expand Down