From 8a377455ea62e09d199aa6dc32bfca2b2a80ab90 Mon Sep 17 00:00:00 2001 From: Vladyslav Hroshev Date: Wed, 2 Apr 2025 21:37:52 +0300 Subject: [PATCH 1/6] Check for results in concurrent tasks, remove stop_after_first_installed_color flag --- scripts/install/theme_installer.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/scripts/install/theme_installer.py b/scripts/install/theme_installer.py index 0e6ae90..4f53669 100644 --- a/scripts/install/theme_installer.py +++ b/scripts/install/theme_installer.py @@ -14,7 +14,6 @@ class ThemeInstaller(ABC): def __init__(self, args: argparse.Namespace, colors: ColorsDefiner): self.args = args self.colors = colors - self.stop_after_first_installed_color = False self._define_theme() @abstractmethod @@ -84,9 +83,6 @@ class ThemeInstaller(ABC): sat = values.get('s', args.sat) colors_to_install.append((hue, color, sat)) - if self.stop_after_first_installed_color: - break - if not colors_to_install: return False self._run_concurrent_installation(colors_to_install) @@ -96,4 +92,6 @@ class ThemeInstaller(ABC): with concurrent.futures.ThreadPoolExecutor() as executor: futures = [executor.submit(self._install_theme, hue, color, sat) for hue, color, sat in colors_to_install] - concurrent.futures.wait(futures) \ No newline at end of file + + for future in concurrent.futures.as_completed(futures): + future.result() \ No newline at end of file From 2ea1dd2d2d83f5add5354b04fd77253c7a3e4033 Mon Sep 17 00:00:00 2001 From: Vladyslav Hroshev Date: Thu, 3 Apr 2025 21:21:28 +0300 Subject: [PATCH 2/6] Added support for installing GDM theming on Ubuntu - From now GlobalTheme use another method to check does GDM support light/dark mode or not - Structurized GlobalTheme methods - Lowered Python version from 3.12 to 3.10 --- install.py | 3 +- scripts/config.py | 2 + scripts/gdm.py | 343 +++++++++++++++++++++------------ scripts/utils/console.py | 3 + scripts/utils/files_labeler.py | 4 +- 5 files changed, 225 insertions(+), 130 deletions(-) diff --git a/install.py b/install.py index 1c2f84c..a73cdc6 100644 --- a/install.py +++ b/install.py @@ -45,4 +45,5 @@ if __name__ == "__main__": try: main() finally: - shutil.rmtree(config.temp_folder, ignore_errors=True) \ No newline at end of file + pass + # shutil.rmtree(config.temp_folder, ignore_errors=True) \ No newline at end of file diff --git a/scripts/config.py b/scripts/config.py index 83c9732..8a0e6f1 100644 --- a/scripts/config.py +++ b/scripts/config.py @@ -1,3 +1,4 @@ +import os.path from tempfile import gettempdir # folder definitions @@ -13,6 +14,7 @@ scripts_folder = "scripts" # GDM definitions global_gnome_shell_theme = "/usr/share/gnome-shell" gnome_shell_gresource = "gnome-shell-theme.gresource" +ubuntu_gresource_link = "gtk-theme.gresource" extracted_gdm_folder = "theme" # files definitions diff --git a/scripts/gdm.py b/scripts/gdm.py index 4a5104d..f085ca6 100644 --- a/scripts/gdm.py +++ b/scripts/gdm.py @@ -1,35 +1,39 @@ +import functools import os import subprocess +from typing import Optional, TypeAlias from .theme import Theme -from .utils import remove_properties, remove_keywords, gnome +from .utils import remove_properties, remove_keywords from . import config from .utils.console import Console, Color, Format from .utils.files_labeler import FilesLabeler +Path: TypeAlias = str | bytes + class ThemePrepare: """ Theme object prepared for installation """ - def __init__(self, theme: Theme, theme_file, should_label=False): + def __init__(self, theme: Theme, theme_file, label: Optional[str] = None): self.theme = theme self.theme_file = theme_file - self.should_label = should_label + self.label = label class GlobalTheme: - def __init__(self, colors_json, theme_folder, destination_folder, destination_file, temp_folder, + def __init__(self, colors_json, theme_folder, destination_folder, destination_file, temp_folder: str, mode=None, is_filled=False): """ Initialize GlobalTheme class - :param colors_json: location of a json file with colors + :param colors_json: location of a JSON file with color values :param theme_folder: raw theme location :param destination_folder: folder where themes will be installed :param temp_folder: folder where files will be collected - :param mode: theme mode (light or dark). applied only for gnome-shell < 44 - :param is_filled: if True, theme will be filled + :param mode: theme mode (light or dark) + :param is_filled: if True, the theme will be filled """ self.colors_json = colors_json @@ -39,88 +43,121 @@ class GlobalTheme: self.temp_folder = temp_folder self.backup_file = f"{self.destination_file}.backup" - self.backup_trigger = "\n/* Marble theme */\n" # trigger to check if theme is installed + self.backup_trigger = "\n/* Marble theme */\n" self.extracted_theme: str = os.path.join(self.temp_folder, config.extracted_gdm_folder) - self.gst = os.path.join(self.destination_folder, self.destination_file) # use backup file if theme is installed + self.gresource_file = os.path.join(self.destination_folder, self.destination_file) self.themes: list[ThemePrepare] = [] self.is_filled = is_filled self.mode = mode - - def __create_theme(self, theme_type: str, mode=None, should_label=False, is_filled=False): - """Helper to create theme objects""" - theme = Theme(theme_type, self.colors_json, self.theme_folder, - self.extracted_theme, self.temp_folder, - mode=mode, is_filled=is_filled) - theme.prepare() - theme_file = os.path.join(self.extracted_theme, f"{theme_type}.css") - return ThemePrepare(theme=theme, theme_file=theme_file, should_label=should_label) - - def __is_installed(self): - """ - Check if theme is installed - :return: True if theme is installed, False otherwise - """ - - with open(self.gst, "rb") as f: - return self.backup_trigger.encode() in f.read() + def prepare(self): + self.__extract() + self.__find_themes() def __extract(self): - """ - Extract gresource files to temp folder - """ + """Extract gresource files to temp folder""" extract_line = Console.Line() extract_line.update("Extracting gresource files...") - resources = subprocess.getoutput(f"gresource list {self.gst}").split("\n") - prefix = "/org/gnome/shell/" + resources_list_response = subprocess.run( + ["gresource", "list", self.gresource_file], + capture_output=True, text=True, check=False + ) + + if resources_list_response.stderr: + extract_line.error(f"Failed to extract resources: {resources_list_response.stderr.strip()}") + raise Exception(f"gresource could not process the theme file: {self.gresource_file}") + + resources = resources_list_response.stdout.strip().split("\n") + prefix = "/org/gnome/shell/theme/" try: for resource in resources: resource_path = resource.replace(prefix, "") - dir_path = os.path.join(self.temp_folder, os.path.dirname(resource_path)) - output_path = os.path.join(self.temp_folder, resource_path) + output_path = os.path.join(self.extracted_theme, resource_path) + os.makedirs(os.path.dirname(output_path), exist_ok=True) - os.makedirs(dir_path, exist_ok=True) with open(output_path, 'wb') as f: - subprocess.run(["gresource", "extract", self.gst, resource], stdout=f, check=True) + subprocess.run(["gresource", "extract", self.gresource_file, resource], stdout=f, check=True) extract_line.success("Extracted gresource files.") except FileNotFoundError as e: if "gresource" in str(e): - print("Error: 'gresource' command not found.") - print("Please install the glib2-devel package:") - print(" - For Fedora/RHEL: sudo dnf install glib2-devel") - print(" - For Ubuntu/Debian: sudo apt install libglib2.0-dev") - print(" - For Arch: sudo pacman -S glib2-devel") - raise Exception("Missing required dependency: glib2-devel") from e + self.__raise_gresource_error(e) raise - def __add_gnome_styles(self, theme): - """ - Add gnome styles to the start of the file - :param theme: Theme object - """ + @staticmethod + def __raise_gresource_error(e: Exception): + print("Error: 'gresource' command not found.") + print("Please install the glib2-devel package:") + print(" - For Fedora/RHEL: sudo dnf install glib2-devel") + print(" - For Ubuntu/Debian: sudo apt install libglib2.0-dev") + print(" - For Arch: sudo pacman -S glib2-devel") + raise Exception("Missing required dependency: glib2-devel") from e - with open(f"{self.extracted_theme}/{theme.theme_type}.css", 'r') as gnome_theme: - gnome_styles = gnome_theme.read() + self.backup_trigger - theme.add_to_start(gnome_styles) + def __find_themes(self): + extracted_theme_files = os.listdir(self.extracted_theme) - def __generate_themes(self, hue, color, sat=None): - """ - Generate theme files for gnome-shell-theme.gresource.xml - :param hue: color hue - :param color: color name - :param sat: color saturation - """ + allowed_modes = ("dark", "light") + allowed_css = ("gnome-shell-dark", "gnome-shell-light", "gnome-shell") + for style_name in allowed_css: + style_file = style_name + ".css" + if style_file in extracted_theme_files: + last_mode = style_name.split("-")[-1] + mode = last_mode if last_mode in allowed_modes else None + self.__append_theme(style_name, mode=mode or self.mode, label=mode) + + def __append_theme(self, theme_type: str, mode=None, label: Optional[str] = None): + """Helper to create theme objects""" + theme = Theme(theme_type, self.colors_json, self.theme_folder, + self.extracted_theme, self.temp_folder, + mode=mode, is_filled=self.is_filled) + theme.prepare() + theme_file = os.path.join(self.extracted_theme, f"{theme_type}.css") + self.themes.append(ThemePrepare(theme=theme, theme_file=theme_file, label=label)) + + def install(self, hue, sat=None): + """Install theme globally""" + if os.geteuid() != 0: + raise Exception("Root privileges required to install GDM theme") + + if self.__is_installed(): + Console.Line().info("Theme is installed. Reinstalling...") + self.gresource_file += ".backup" + + self.__generate_themes(hue, 'Marble', sat) + self.__backup() + + # generate gnome-shell-theme.gresource.xml + with open(f"{self.extracted_theme}/{self.destination_file}.xml", 'w') as gresource_xml: + generated_xml = self.__generate_gresource_xml() + gresource_xml.write(generated_xml) + self.__compile_resources() + + install_line = Console.Line() + install_line.update("Moving compiled theme to system folder...") + subprocess.run(["sudo", "cp", "-f", + f"{self.extracted_theme}/{self.destination_file}", + f"{self.destination_folder}/{self.destination_file}"], + check=True) + install_line.success("Theme moved to system folder.") + + self.__update_alternatives() + + def __is_installed(self) -> bool: + with open(self.gresource_file, "rb") as f: + return self.backup_trigger.encode() in f.read() + + def __generate_themes(self, hue: int, color: str, sat: Optional[int]=None): + """Generate theme files for gnome-shell-theme.gresource.xml""" for theme_prepare in self.themes: - if theme_prepare.should_label: + if theme_prepare.label is not None: temp_folder = theme_prepare.theme.temp_folder main_styles = theme_prepare.theme.main_styles - FilesLabeler(temp_folder, main_styles).append_label("light") + FilesLabeler(temp_folder, main_styles).append_label(theme_prepare.label) remove_keywords(theme_prepare.theme_file, "!important") remove_properties(theme_prepare.theme_file, "background-color", "color", "box-shadow", "border-radius") @@ -129,6 +166,11 @@ class GlobalTheme: theme_prepare.theme.install(hue, color, sat, destination=self.extracted_theme) + def __add_gnome_styles(self, theme: Theme): + """Add gnome styles to the start of the file""" + with open(f"{theme.destination_folder}/{theme.theme_type}.css", 'r') as gnome_theme: + gnome_styles = gnome_theme.read() + self.backup_trigger + theme.add_to_start(gnome_styles) def __backup(self): if self.__is_installed(): @@ -137,89 +179,52 @@ class GlobalTheme: backup_line = Console.Line() backup_line.update("Backing up default theme...") - subprocess.run(["cp", "-aT", self.gst, f"{self.gst}.backup"], cwd=self.destination_folder, check=True) + subprocess.run(["cp", "-aT", self.gresource_file, f"{self.gresource_file}.backup"], + cwd=self.destination_folder, check=True) backup_line.success("Backed up default theme.") def __generate_gresource_xml(self): - # list of files to add to gnome-shell-theme.gresource.xml - files = [f"{file}" for file in os.listdir(self.extracted_theme)] + files_to_include = [] + for root, dirs, filenames in os.walk(self.extracted_theme): + for filename in filenames: + # Get a path relative to extracted_theme directory + full_path = os.path.join(root, filename) + rel_path = os.path.relpath(full_path, self.extracted_theme) + files_to_include.append(f"{rel_path}") nl = "\n" # fstring doesn't support newline character return f""" - {nl.join(files)} + {nl.join(files_to_include)} """ - def prepare(self): - try: - gnome_version = gnome.gnome_version() - gnome_major = gnome_version.split(".")[0] - if int(gnome_major) >= 44: - self.themes += [ - self.__create_theme("gnome-shell-light", mode='light', should_label=True, is_filled=self.is_filled), - self.__create_theme("gnome-shell-dark", mode='dark', is_filled=self.is_filled) - ] - except Exception as e: - print(f"Error: {e}") - print("Using single theme.") - - if not self.themes: - self.themes.append( - self.__create_theme( - "gnome-shell", mode=self.mode if self.mode else 'dark', is_filled=self.is_filled)) - - def install(self, hue, sat=None): - """ - Install theme globally - :param hue: color hue - :param sat: color saturation - """ - - if os.geteuid() != 0: - raise Exception("Root privileges required to install GDM theme") - - if self.__is_installed(): - print("Theme is installed. Reinstalling...") - self.gst += ".backup" - - self.__extract() - - # generate theme files for global theme - self.__generate_themes(hue, 'Marble', sat) - - # generate gnome-shell-theme.gresource.xml - with open(f"{self.extracted_theme}/{self.destination_file}.xml", 'w') as gresource_xml: - generated_xml = self.__generate_gresource_xml() - gresource_xml.write(generated_xml) - - # compile gnome-shell-theme.gresource.xml + def __compile_resources(self): compile_line = Console.Line() compile_line.update("Compiling gnome-shell theme...") - subprocess.run(["glib-compile-resources" , f"{self.destination_file}.xml"], - cwd=self.extracted_theme, check=True) + + try: + subprocess.run(["glib-compile-resources", + "--sourcedir", self.extracted_theme, + "--target", f"{self.extracted_theme}/{self.destination_file}", + f"{self.destination_file}.xml" + ], + cwd=self.extracted_theme, check=True) + except FileNotFoundError as e: + if "glib-compile-resources" in str(e): + self.__raise_gresource_error(e) + raise + compile_line.success("Theme compiled.") - # backup installed theme - self.__backup() - - # install theme - install_line = Console.Line() - install_line.update("Moving compiled theme to system folder...") - subprocess.run(["sudo", "cp", "-f", - f"{self.extracted_theme}/{self.destination_file}", - f"{self.destination_folder}/{self.destination_file}"], - check=True) - install_line.success("Theme moved to system folder.") - + def __update_alternatives(self): + link = os.path.join(self.destination_folder, config.ubuntu_gresource_link) + name = config.ubuntu_gresource_link + path = os.path.join(self.destination_folder, self.destination_file) + AlternativesUpdater.install_and_set(link, name, path) def remove(self): - """ - Remove installed theme - """ - - # use backup file if theme is installed if self.__is_installed(): removing_line = Console.Line() removing_line.update("Theme is installed. Removing...") @@ -227,7 +232,7 @@ class GlobalTheme: dest_path = os.path.join(self.destination_folder, self.destination_file) if os.path.isfile(backup_path): - subprocess.run(["sudo", "mv", backup_path, dest_path], check=True) + subprocess.run(["sudo", "mv", backup_path, dest_path], check=True) removing_line.success("Global theme removed successfully. Restart GDM to apply changes.") else: @@ -236,4 +241,88 @@ class GlobalTheme: else: Console.Line().error("Theme is not installed. Nothing to remove.") - Console.Line().update("If theme is still installed globally, try reinstalling gnome-shell package.", icon="⚠️") + Console.Line().warn("If theme is still installed globally, try reinstalling gnome-shell package.") + + def __remove_alternatives(self): + name = config.ubuntu_gresource_link + path = os.path.join(self.destination_folder, self.destination_file) + AlternativesUpdater.remove(name, path) + + +class AlternativesUpdater: + @staticmethod + def ubuntu_specific(func): + """ + Decorator for Ubuntu-specific functionality. + Silently ignores errors when not running on Ubuntu systems. + """ + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + result = func(*args, **kwargs) + return result + except FileNotFoundError as e: + if not "update-alternatives" in str(e): + raise + return None + + return wrapper + + @staticmethod + @ubuntu_specific + def install_and_set(link: str, name: str, path: Path, priority: int = 0): + AlternativesUpdater.install(link, name, path, priority) + AlternativesUpdater.set(name, path) + + @staticmethod + @ubuntu_specific + def install(link: str, name: str, path: Path, priority: int = 0): + """ + Add an alternative to the system + :param link: Absolute path with file name where the link will be created + :param name: Name of the alternative + :param path: An absolute path to the file that will be linked + :param priority: Priority of the alternative; Higher number means higher priority + + Example: + install(/usr/share/gnome-shell/gdm-theme.gresource, + gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) + """ + subprocess.run([ + "update-alternatives", "--quiet", "--install", + link, name, str(path), str(priority) + ], check=True) + Console.Line().success(f"Installed {name} alternative.") + + @staticmethod + @ubuntu_specific + def set(name: str, path: Path): + """ + Set path as alternative to name in system + :param name: Name of the alternative + :param path: An absolute path to the file that will be linked + + Example: + set(gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) + """ + subprocess.run([ + "update-alternatives", "--quiet", "--set", + name, str(path) + ], check=True) + + @staticmethod + @ubuntu_specific + def remove(name: str, path: Path): + """ + Remove alternative from system + :param name: Name of the alternative + :param path: An absolute path to the file that will be linked + + Example: + remove(gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) + """ + subprocess.run([ + "update-alternatives", "--quiet", "--remove", + name, str(path) + ], check=True) + Console.Line().success(f"Removed {name} alternative.") \ No newline at end of file diff --git a/scripts/utils/console.py b/scripts/utils/console.py index af44267..53d2738 100644 --- a/scripts/utils/console.py +++ b/scripts/utils/console.py @@ -43,6 +43,9 @@ class Console: def warn(self, message): self.update(message, "⚠️") + def info(self, message): + self.update(message, "ℹ️ ") + def _reserve_line(self): """Reserve a line for future updates""" with Console._print_lock: diff --git a/scripts/utils/files_labeler.py b/scripts/utils/files_labeler.py index ddfcf26..6243f7a 100644 --- a/scripts/utils/files_labeler.py +++ b/scripts/utils/files_labeler.py @@ -1,7 +1,7 @@ import os -from typing import Tuple +from typing import Tuple, TypeAlias -type LabeledFileGroup = Tuple[str, str] +LabeledFileGroup: TypeAlias = Tuple[str, str] class FilesLabeler: def __init__(self, directory: str, *args: str): From 6f5f2b4cac15faff68d9edcfd80c1a0c2610eaa7 Mon Sep 17 00:00:00 2001 From: Vladyslav Hroshev Date: Thu, 3 Apr 2025 21:33:49 +0300 Subject: [PATCH 3/6] Updated README.md --- README.md | 12 +++++------- 1 file changed, 5 insertions(+), 7 deletions(-) diff --git a/README.md b/README.md index f9e91e4..3bc42c8 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,8 @@ Shell theme for GNOME DE. Based on https://www.pling.com/p/1939902/.
Click me 🐈 Icon theme: https://github.com/vinceliuice/Colloid-icon-theme -#### Overview [[Blur My Shell](https://extensions.gnome.org/extension/3193/blur-my-shell/) / Light / Dark] ([Neon Gas Station](https://www.heroscreen.cc/2025/03/neon-gas-station-4k-wallpaper.html)) + +#### Overview [[Blur My Shell](https://extensions.gnome.org/extension/3193/blur-my-shell/) / Light / Dark] ([Neon Gas Station](https://www.heroscreen.cc/2025/03/neon-gas-station-4k-wallpaper.html) - AI Generated) ![Overview with Blur My Shell](./readme-images/overview_blur-my-shell.png?raw=true "Overview with Blur My Shell") ![Overview in light mode](./readme-images/overview_light.png?raw=true "Overview in light mode") ![Overview in dark mode](./readme-images/overview_dark.png?raw=true "Overview in dark mode") @@ -26,7 +27,7 @@ Icon theme: https://github.com/vinceliuice/Colloid-icon-theme #### Modal dialog ([Wide Angle Photography of Mountain](https://www.pexels.com/photo/wide-angle-photography-of-mountain-1612559/)) ![Modal dialog look](./readme-images/modal.png?raw=true "Modal dialog look") -#### Calendar & notifications ([Neon Gas Station](https://www.heroscreen.cc/2025/03/neon-gas-station-4k-wallpaper.html)) +#### Calendar & notifications ![Calendar & notifications look](./readme-images/datemenu.png?raw=true) #### Dash ([Dash To Dock](https://extensions.gnome.org/extension/307/dash-to-dock/ "Dash To Dock")) @@ -43,7 +44,7 @@ Icon theme: https://github.com/vinceliuice/Colloid-icon-theme ## 🚧 Requirements - GNOME 42-48. Correct functionality on other versions is not guaranteed. - [User Themes](https://extensions.gnome.org/extension/19/user-themes/ "User Themes") extension. -- Python 3.9+. +- Python 3.10 or higher. ## 💡 Installation @@ -56,7 +57,7 @@ Icon theme: https://github.com/vinceliuice/Colloid-icon-theme git clone https://github.com/imarkoff/Marble-shell-theme.git cd Marble-shell-theme ``` -3. Run the program (install all accent colors, light & dark mode): +3. Run the program (install all accent colors, light and dark mode): ```shell python install.py -a ``` @@ -86,9 +87,6 @@ If you want to remove the theme, see the [uninstallation](#%EF%B8%8F-uninstallat > > **Config:** `sudo python install.py --gdm --blue --filled --gdm-image /path/to/image.jpg --gdm-blur=40 --gdm-darken=30` -> [!NOTE] -> This theme only supports GNOME Display Manager. Ubuntu Display Manager is currently not supported. - > [!WARNING] > I am not responsible for any damage caused by the installation of the theme. If you have any problems, please open an issue. From 4494e980809f5adddb222b87c7ae8795d69ac37d Mon Sep 17 00:00:00 2001 From: Vladyslav Hroshev Date: Thu, 3 Apr 2025 21:46:17 +0300 Subject: [PATCH 4/6] Bring back removing temporary files --- install.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/install.py b/install.py index a73cdc6..1c2f84c 100644 --- a/install.py +++ b/install.py @@ -45,5 +45,4 @@ if __name__ == "__main__": try: main() finally: - pass - # shutil.rmtree(config.temp_folder, ignore_errors=True) \ No newline at end of file + shutil.rmtree(config.temp_folder, ignore_errors=True) \ No newline at end of file From 19cdad30411b815837f1dc733d3b937fc06d870e Mon Sep 17 00:00:00 2001 From: Vladyslav Hroshev Date: Fri, 4 Apr 2025 20:25:57 +0300 Subject: [PATCH 5/6] Fixed GDM reinstallation, extracted gresource and update-alternatives logic --- scripts/gdm.py | 275 +++++--------------------- scripts/utils/alternatives_updater.py | 86 ++++++++ scripts/utils/gresource.py | 162 +++++++++++++++ 3 files changed, 296 insertions(+), 227 deletions(-) create mode 100644 scripts/utils/alternatives_updater.py create mode 100644 scripts/utils/gresource.py diff --git a/scripts/gdm.py b/scripts/gdm.py index f085ca6..5a573a4 100644 --- a/scripts/gdm.py +++ b/scripts/gdm.py @@ -1,33 +1,24 @@ -import functools import os -import subprocess -from typing import Optional, TypeAlias +from typing import Optional +from .install.colors_definer import ColorsDefiner from .theme import Theme from .utils import remove_properties, remove_keywords from . import config +from .utils.alternatives_updater import AlternativesUpdater from .utils.console import Console, Color, Format from .utils.files_labeler import FilesLabeler - -Path: TypeAlias = str | bytes - - -class ThemePrepare: - """ - Theme object prepared for installation - """ - - def __init__(self, theme: Theme, theme_file, label: Optional[str] = None): - self.theme = theme - self.theme_file = theme_file - self.label = label +from .utils.gresource import Gresource, GresourceBackupNotFoundError class GlobalTheme: - def __init__(self, colors_json, theme_folder, destination_folder, destination_file, temp_folder: str, - mode=None, is_filled=False): + """Class to install global theme for GDM""" + def __init__(self, + colors_json: ColorsDefiner, theme_folder: str, + destination_folder: str, destination_file: str, temp_folder: str, + mode: Optional[str] = None, is_filled = False + ): """ - Initialize GlobalTheme class :param colors_json: location of a JSON file with color values :param theme_folder: raw theme location :param destination_folder: folder where themes will be installed @@ -35,70 +26,39 @@ class GlobalTheme: :param mode: theme mode (light or dark) :param is_filled: if True, the theme will be filled """ - self.colors_json = colors_json self.theme_folder = theme_folder self.destination_folder = destination_folder self.destination_file = destination_file self.temp_folder = temp_folder - - self.backup_file = f"{self.destination_file}.backup" - self.backup_trigger = "\n/* Marble theme */\n" - self.extracted_theme: str = os.path.join(self.temp_folder, config.extracted_gdm_folder) - self.gresource_file = os.path.join(self.destination_folder, self.destination_file) - - self.themes: list[ThemePrepare] = [] self.is_filled = is_filled self.mode = mode + self.themes: list[ThemePrepare] = [] + + self.__is_installed_trigger = "\n/* Marble theme */\n" + self.__gresource_file = os.path.join(self.destination_folder, self.destination_file) + + self.__gresource_temp_folder = os.path.join(self.temp_folder, config.extracted_gdm_folder) + self.__gresource = Gresource(self.destination_file, self.__gresource_temp_folder, self.destination_folder) + def prepare(self): - self.__extract() + if self.__is_installed(): + Console.Line().info("Theme is installed. Reinstalling...") + self.__gresource.use_backup_gresource() + + self.__gresource.extract() self.__find_themes() - def __extract(self): - """Extract gresource files to temp folder""" - extract_line = Console.Line() - extract_line.update("Extracting gresource files...") + def __is_installed(self) -> bool: + if not hasattr(self, '__is_installed_cached'): + with open(self.__gresource_file, "rb") as f: + self.__is_installed_cached = self.__is_installed_trigger.encode() in f.read() - resources_list_response = subprocess.run( - ["gresource", "list", self.gresource_file], - capture_output=True, text=True, check=False - ) - - if resources_list_response.stderr: - extract_line.error(f"Failed to extract resources: {resources_list_response.stderr.strip()}") - raise Exception(f"gresource could not process the theme file: {self.gresource_file}") - - resources = resources_list_response.stdout.strip().split("\n") - prefix = "/org/gnome/shell/theme/" - - try: - for resource in resources: - resource_path = resource.replace(prefix, "") - output_path = os.path.join(self.extracted_theme, resource_path) - os.makedirs(os.path.dirname(output_path), exist_ok=True) - - with open(output_path, 'wb') as f: - subprocess.run(["gresource", "extract", self.gresource_file, resource], stdout=f, check=True) - - extract_line.success("Extracted gresource files.") - - except FileNotFoundError as e: - if "gresource" in str(e): - self.__raise_gresource_error(e) - raise - - @staticmethod - def __raise_gresource_error(e: Exception): - print("Error: 'gresource' command not found.") - print("Please install the glib2-devel package:") - print(" - For Fedora/RHEL: sudo dnf install glib2-devel") - print(" - For Ubuntu/Debian: sudo apt install libglib2.0-dev") - print(" - For Arch: sudo pacman -S glib2-devel") - raise Exception("Missing required dependency: glib2-devel") from e + return self.__is_installed_cached def __find_themes(self): - extracted_theme_files = os.listdir(self.extracted_theme) + extracted_theme_files = os.listdir(self.__gresource_temp_folder) allowed_modes = ("dark", "light") allowed_css = ("gnome-shell-dark", "gnome-shell-light", "gnome-shell") @@ -110,13 +70,13 @@ class GlobalTheme: mode = last_mode if last_mode in allowed_modes else None self.__append_theme(style_name, mode=mode or self.mode, label=mode) - def __append_theme(self, theme_type: str, mode=None, label: Optional[str] = None): + def __append_theme(self, theme_type: str, mode = None, label: Optional[str] = None): """Helper to create theme objects""" theme = Theme(theme_type, self.colors_json, self.theme_folder, - self.extracted_theme, self.temp_folder, + self.__gresource_temp_folder, self.temp_folder, mode=mode, is_filled=self.is_filled) theme.prepare() - theme_file = os.path.join(self.extracted_theme, f"{theme_type}.css") + theme_file = os.path.join(self.__gresource_temp_folder, f"{theme_type}.css") self.themes.append(ThemePrepare(theme=theme, theme_file=theme_file, label=label)) def install(self, hue, sat=None): @@ -124,34 +84,16 @@ class GlobalTheme: if os.geteuid() != 0: raise Exception("Root privileges required to install GDM theme") - if self.__is_installed(): - Console.Line().info("Theme is installed. Reinstalling...") - self.gresource_file += ".backup" - self.__generate_themes(hue, 'Marble', sat) - self.__backup() - # generate gnome-shell-theme.gresource.xml - with open(f"{self.extracted_theme}/{self.destination_file}.xml", 'w') as gresource_xml: - generated_xml = self.__generate_gresource_xml() - gresource_xml.write(generated_xml) - self.__compile_resources() - - install_line = Console.Line() - install_line.update("Moving compiled theme to system folder...") - subprocess.run(["sudo", "cp", "-f", - f"{self.extracted_theme}/{self.destination_file}", - f"{self.destination_folder}/{self.destination_file}"], - check=True) - install_line.success("Theme moved to system folder.") + self.__gresource.compile() + if not self.__is_installed(): + self.__gresource.backup() + self.__gresource.move() self.__update_alternatives() - def __is_installed(self) -> bool: - with open(self.gresource_file, "rb") as f: - return self.backup_trigger.encode() in f.read() - - def __generate_themes(self, hue: int, color: str, sat: Optional[int]=None): + def __generate_themes(self, hue: int, color: str, sat: Optional[int] = None): """Generate theme files for gnome-shell-theme.gresource.xml""" for theme_prepare in self.themes: if theme_prepare.label is not None: @@ -164,60 +106,14 @@ class GlobalTheme: self.__add_gnome_styles(theme_prepare.theme) - theme_prepare.theme.install(hue, color, sat, destination=self.extracted_theme) + theme_prepare.theme.install(hue, color, sat, destination=self.__gresource_temp_folder) def __add_gnome_styles(self, theme: Theme): """Add gnome styles to the start of the file""" with open(f"{theme.destination_folder}/{theme.theme_type}.css", 'r') as gnome_theme: - gnome_styles = gnome_theme.read() + self.backup_trigger + gnome_styles = gnome_theme.read() + self.__is_installed_trigger theme.add_to_start(gnome_styles) - def __backup(self): - if self.__is_installed(): - return - - backup_line = Console.Line() - - backup_line.update("Backing up default theme...") - subprocess.run(["cp", "-aT", self.gresource_file, f"{self.gresource_file}.backup"], - cwd=self.destination_folder, check=True) - backup_line.success("Backed up default theme.") - - def __generate_gresource_xml(self): - files_to_include = [] - for root, dirs, filenames in os.walk(self.extracted_theme): - for filename in filenames: - # Get a path relative to extracted_theme directory - full_path = os.path.join(root, filename) - rel_path = os.path.relpath(full_path, self.extracted_theme) - files_to_include.append(f"{rel_path}") - nl = "\n" # fstring doesn't support newline character - - return f""" - - - {nl.join(files_to_include)} - -""" - - def __compile_resources(self): - compile_line = Console.Line() - compile_line.update("Compiling gnome-shell theme...") - - try: - subprocess.run(["glib-compile-resources", - "--sourcedir", self.extracted_theme, - "--target", f"{self.extracted_theme}/{self.destination_file}", - f"{self.destination_file}.xml" - ], - cwd=self.extracted_theme, check=True) - except FileNotFoundError as e: - if "glib-compile-resources" in str(e): - self.__raise_gresource_error(e) - raise - - compile_line.success("Theme compiled.") - def __update_alternatives(self): link = os.path.join(self.destination_folder, config.ubuntu_gresource_link) name = config.ubuntu_gresource_link @@ -228,17 +124,13 @@ class GlobalTheme: if self.__is_installed(): removing_line = Console.Line() removing_line.update("Theme is installed. Removing...") - backup_path = os.path.join(self.destination_folder, self.backup_file) - dest_path = os.path.join(self.destination_folder, self.destination_file) - if os.path.isfile(backup_path): - subprocess.run(["sudo", "mv", backup_path, dest_path], check=True) + try: + self.__gresource.restore() removing_line.success("Global theme removed successfully. Restart GDM to apply changes.") - - else: + except GresourceBackupNotFoundError: formatted_shell = Console.format("gnome-shell", color=Color.BLUE, format_type=Format.BOLD) removing_line.error(f"Backup file not found. Try reinstalling {formatted_shell} package.") - else: Console.Line().error("Theme is not installed. Nothing to remove.") Console.Line().warn("If theme is still installed globally, try reinstalling gnome-shell package.") @@ -249,80 +141,9 @@ class GlobalTheme: AlternativesUpdater.remove(name, path) -class AlternativesUpdater: - @staticmethod - def ubuntu_specific(func): - """ - Decorator for Ubuntu-specific functionality. - Silently ignores errors when not running on Ubuntu systems. - """ - @functools.wraps(func) - def wrapper(*args, **kwargs): - try: - result = func(*args, **kwargs) - return result - except FileNotFoundError as e: - if not "update-alternatives" in str(e): - raise - return None - - return wrapper - - @staticmethod - @ubuntu_specific - def install_and_set(link: str, name: str, path: Path, priority: int = 0): - AlternativesUpdater.install(link, name, path, priority) - AlternativesUpdater.set(name, path) - - @staticmethod - @ubuntu_specific - def install(link: str, name: str, path: Path, priority: int = 0): - """ - Add an alternative to the system - :param link: Absolute path with file name where the link will be created - :param name: Name of the alternative - :param path: An absolute path to the file that will be linked - :param priority: Priority of the alternative; Higher number means higher priority - - Example: - install(/usr/share/gnome-shell/gdm-theme.gresource, - gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) - """ - subprocess.run([ - "update-alternatives", "--quiet", "--install", - link, name, str(path), str(priority) - ], check=True) - Console.Line().success(f"Installed {name} alternative.") - - @staticmethod - @ubuntu_specific - def set(name: str, path: Path): - """ - Set path as alternative to name in system - :param name: Name of the alternative - :param path: An absolute path to the file that will be linked - - Example: - set(gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) - """ - subprocess.run([ - "update-alternatives", "--quiet", "--set", - name, str(path) - ], check=True) - - @staticmethod - @ubuntu_specific - def remove(name: str, path: Path): - """ - Remove alternative from system - :param name: Name of the alternative - :param path: An absolute path to the file that will be linked - - Example: - remove(gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) - """ - subprocess.run([ - "update-alternatives", "--quiet", "--remove", - name, str(path) - ], check=True) - Console.Line().success(f"Removed {name} alternative.") \ No newline at end of file +class ThemePrepare: + """Theme data class prepared for installation""" + def __init__(self, theme: Theme, theme_file, label: Optional[str] = None): + self.theme = theme + self.theme_file = theme_file + self.label = label \ No newline at end of file diff --git a/scripts/utils/alternatives_updater.py b/scripts/utils/alternatives_updater.py new file mode 100644 index 0000000..f5e4ff8 --- /dev/null +++ b/scripts/utils/alternatives_updater.py @@ -0,0 +1,86 @@ +import functools +import subprocess +from typing import TypeAlias + +from scripts.utils.console import Console + +PathString: TypeAlias = str | bytes + +class AlternativesUpdater: + """ + Manages update-alternatives for Ubuntu. + Ignores errors if update-alternatives not found. + """ + + @staticmethod + def ubuntu_specific(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + try: + result = func(*args, **kwargs) + return result + except FileNotFoundError as e: + if not "update-alternatives" in str(e): + raise + return None + + return wrapper + + @staticmethod + @ubuntu_specific + def install_and_set(link: str, name: str, path: PathString, priority: int = 0): + AlternativesUpdater.install(link, name, path, priority) + AlternativesUpdater.set(name, path) + + @staticmethod + @ubuntu_specific + def install(link: str, name: str, path: PathString, priority: int = 0): + """ + Add an alternative to the system + :param link: Absolute path with file name where the link will be created + :param name: Name of the alternative + :param path: An absolute path to the file that will be linked + :param priority: Priority of the alternative; Higher number means higher priority + + Example: + install(/usr/share/gnome-shell/gdm-theme.gresource, + gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) + """ + subprocess.run([ + "update-alternatives", "--quiet", "--install", + link, name, str(path), str(priority) + ], check=True) + Console.Line().success(f"Installed {name} alternative.") + + @staticmethod + @ubuntu_specific + def set(name: str, path: PathString): + """ + Set path as alternative to name in system + :param name: Name of the alternative + :param path: An absolute path to the file that will be linked + + Example: + set(gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) + """ + subprocess.run([ + "update-alternatives", "--quiet", "--set", + name, str(path) + ], check=True) + + @staticmethod + @ubuntu_specific + def remove(name: str, path: PathString): + """ + Remove alternative from system + :param name: Name of the alternative + :param path: An absolute path to the file that will be linked + + Example: + remove(gdm-theme.gresource, /usr/share/gnome-shell/gnome-shell-theme.gresource) + """ + subprocess.run([ + "update-alternatives", "--quiet", "--remove", + name, str(path) + ], check=True) + Console.Line().success(f"Removed {name} alternative.") \ No newline at end of file diff --git a/scripts/utils/gresource.py b/scripts/utils/gresource.py new file mode 100644 index 0000000..6e5cdae --- /dev/null +++ b/scripts/utils/gresource.py @@ -0,0 +1,162 @@ +import os +import subprocess +import textwrap +from pathlib import Path + +from scripts.utils.console import Console + + +class GresourceBackupNotFoundError(FileNotFoundError): + pass + + +class Gresource: + """Handles the extraction and compilation of gresource files for GNOME Shell themes.""" + + def __init__(self, gresource_file: str, temp_folder: str, destination: str): + """ + :param gresource_file: The name of the gresource file to be processed. + :param temp_folder: The temporary folder where resources will be extracted. + :param destination: The destination folder where the compiled gresource file will be saved. + """ + self.gresource_file = gresource_file + self.temp_folder = temp_folder + self.destination = destination + + self.__temp_gresource = os.path.join(temp_folder, gresource_file) + self.__destination_gresource = os.path.join(destination, gresource_file) + self.__source_gresource = self.__destination_gresource + self.__gresource_xml = os.path.join(temp_folder, f"{gresource_file}.xml") + + def use_backup_gresource(self): + if not self.__source_gresource.endswith(".backup"): + self.__source_gresource += ".backup" + if not os.path.exists(self.__source_gresource): + raise GresourceBackupNotFoundError() + + def extract(self): + extract_line = Console.Line() + extract_line.update("Extracting gresource files...") + + resources = self.__get_resources_list() + self.__extract_resources(resources) + + extract_line.success("Extracted gresource files.") + + def __get_resources_list(self): + resources_list_response = subprocess.run( + ["gresource", "list", self.__source_gresource], + capture_output=True, text=True, check=False + ) + + if resources_list_response.stderr: + raise Exception(f"gresource could not process the theme file: {self.__source_gresource}") + + return resources_list_response.stdout.strip().split("\n") + + def __extract_resources(self, resources: list[str]): + prefix = "/org/gnome/shell/theme/" + try: + for resource in resources: + resource_path = resource.replace(prefix, "") + output_path = os.path.join(self.temp_folder, resource_path) + os.makedirs(os.path.dirname(output_path), exist_ok=True) + + with open(output_path, 'wb') as f: + subprocess.run( + ["gresource", "extract", self.__source_gresource, resource], + stdout=f, check=True + ) + except FileNotFoundError as e: + if "gresource" in str(e): + self.__raise_gresource_error(e) + raise + + @staticmethod + def __raise_gresource_error(e: Exception): + print("Error: 'gresource' command not found.") + print("Please install the glib2-devel package:") + print(" - For Fedora/RHEL: sudo dnf install glib2-devel") + print(" - For Ubuntu/Debian: sudo apt install libglib2.0-dev") + print(" - For Arch: sudo pacman -S glib2-devel") + raise Exception("Missing required dependency: glib2-devel") from e + + def compile(self): + compile_line = Console.Line() + compile_line.update("Compiling gnome-shell theme...") + + self.__create_gresource_xml() + self.__compile_resources() + + compile_line.success("Theme compiled.") + + def __create_gresource_xml(self): + with open(self.__gresource_xml, 'w') as gresource_xml: + gresource_xml.write(self.__generate_gresource_xml()) + + def __generate_gresource_xml(self): + files_to_include = self.__get_files_to_include() + nl = "\n" # fstring doesn't support newline character + return textwrap.dedent(f""" + + + + {nl.join(files_to_include)} + + + """) + + def __get_files_to_include(self): + temp_path = Path(self.temp_folder) + return [ + f"{file.relative_to(temp_path)}" + for file in temp_path.glob('**/*') + if file.is_file() + ] + + def __compile_resources(self): + try: + subprocess.run(["glib-compile-resources", + "--sourcedir", self.temp_folder, + "--target", self.__temp_gresource, + self.__gresource_xml + ], + cwd=self.temp_folder, check=True) + except FileNotFoundError as e: + if "glib-compile-resources" in str(e): + self.__raise_gresource_error(e) + raise + + def backup(self): + backup_line = Console.Line() + backup_line.update("Backing up gresource files...") + + subprocess.run(["cp", "-aT", + self.__destination_gresource, + f"{self.__destination_gresource}.backup"], + check=True) + + backup_line.success("Backed up gresource files.") + + def restore(self): + backup_gresource = f"{self.__destination_gresource}.backup" + + if not os.path.exists(backup_gresource): + raise GresourceBackupNotFoundError() + + subprocess.run(["sudo", "mv", "-f", + backup_gresource, + self.__destination_gresource], + check=True) + + + def move(self): + move_line = Console.Line() + move_line.update("Moving gresource files...") + + subprocess.run(["sudo", "cp", "-f", + self.__temp_gresource, + self.__destination_gresource], + check=True) + + move_line.success("Moved gresource files.") \ No newline at end of file From ad8f3fb9bd84d70eb44501617adc6df9687f5b0d Mon Sep 17 00:00:00 2001 From: Vladyslav Hroshev Date: Fri, 4 Apr 2025 20:54:08 +0300 Subject: [PATCH 6/6] Use __backup_gresource, simplified use_backup_gresource() --- scripts/utils/gresource.py | 32 +++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/scripts/utils/gresource.py b/scripts/utils/gresource.py index 6e5cdae..8d15657 100644 --- a/scripts/utils/gresource.py +++ b/scripts/utils/gresource.py @@ -7,7 +7,11 @@ from scripts.utils.console import Console class GresourceBackupNotFoundError(FileNotFoundError): - pass + def __init__(self, location: str = None): + if location: + super().__init__(f"Gresource backup file not found: {location}") + else: + super().__init__("Gresource backup file not found.") class Gresource: @@ -25,14 +29,14 @@ class Gresource: self.__temp_gresource = os.path.join(temp_folder, gresource_file) self.__destination_gresource = os.path.join(destination, gresource_file) - self.__source_gresource = self.__destination_gresource + self.__active_source_gresource = self.__destination_gresource + self.__backup_gresource = os.path.join(destination, f"{gresource_file}.backup") self.__gresource_xml = os.path.join(temp_folder, f"{gresource_file}.xml") def use_backup_gresource(self): - if not self.__source_gresource.endswith(".backup"): - self.__source_gresource += ".backup" - if not os.path.exists(self.__source_gresource): - raise GresourceBackupNotFoundError() + if not os.path.exists(self.__backup_gresource): + raise GresourceBackupNotFoundError(self.__backup_gresource) + self.__active_source_gresource = self.__backup_gresource def extract(self): extract_line = Console.Line() @@ -45,12 +49,12 @@ class Gresource: def __get_resources_list(self): resources_list_response = subprocess.run( - ["gresource", "list", self.__source_gresource], + ["gresource", "list", self.__active_source_gresource], capture_output=True, text=True, check=False ) if resources_list_response.stderr: - raise Exception(f"gresource could not process the theme file: {self.__source_gresource}") + raise Exception(f"gresource could not process the theme file: {self.__active_source_gresource}") return resources_list_response.stdout.strip().split("\n") @@ -64,7 +68,7 @@ class Gresource: with open(output_path, 'wb') as f: subprocess.run( - ["gresource", "extract", self.__source_gresource, resource], + ["gresource", "extract", self.__active_source_gresource, resource], stdout=f, check=True ) except FileNotFoundError as e: @@ -133,19 +137,17 @@ class Gresource: subprocess.run(["cp", "-aT", self.__destination_gresource, - f"{self.__destination_gresource}.backup"], + self.__backup_gresource], check=True) backup_line.success("Backed up gresource files.") def restore(self): - backup_gresource = f"{self.__destination_gresource}.backup" - - if not os.path.exists(backup_gresource): - raise GresourceBackupNotFoundError() + if not os.path.exists(self.__backup_gresource): + raise GresourceBackupNotFoundError(self.__backup_gresource) subprocess.run(["sudo", "mv", "-f", - backup_gresource, + self.__backup_gresource, self.__destination_gresource], check=True)