mirror of
https://github.com/imarkoff/Marble-shell-theme.git
synced 2025-09-18 01:07:55 -07:00
Fixed GDM reinstallation, extracted gresource and update-alternatives logic
This commit is contained in:
275
scripts/gdm.py
275
scripts/gdm.py
@@ -1,33 +1,24 @@
|
|||||||
import functools
|
|
||||||
import os
|
import os
|
||||||
import subprocess
|
from typing import Optional
|
||||||
from typing import Optional, TypeAlias
|
|
||||||
|
|
||||||
|
from .install.colors_definer import ColorsDefiner
|
||||||
from .theme import Theme
|
from .theme import Theme
|
||||||
from .utils import remove_properties, remove_keywords
|
from .utils import remove_properties, remove_keywords
|
||||||
from . import config
|
from . import config
|
||||||
|
from .utils.alternatives_updater import AlternativesUpdater
|
||||||
from .utils.console import Console, Color, Format
|
from .utils.console import Console, Color, Format
|
||||||
from .utils.files_labeler import FilesLabeler
|
from .utils.files_labeler import FilesLabeler
|
||||||
|
from .utils.gresource import Gresource, GresourceBackupNotFoundError
|
||||||
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
|
|
||||||
|
|
||||||
|
|
||||||
class GlobalTheme:
|
class GlobalTheme:
|
||||||
def __init__(self, colors_json, theme_folder, destination_folder, destination_file, temp_folder: str,
|
"""Class to install global theme for GDM"""
|
||||||
mode=None, is_filled=False):
|
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 colors_json: location of a JSON file with color values
|
||||||
:param theme_folder: raw theme location
|
:param theme_folder: raw theme location
|
||||||
:param destination_folder: folder where themes will be installed
|
:param destination_folder: folder where themes will be installed
|
||||||
@@ -35,70 +26,39 @@ class GlobalTheme:
|
|||||||
:param mode: theme mode (light or dark)
|
:param mode: theme mode (light or dark)
|
||||||
:param is_filled: if True, the theme will be filled
|
:param is_filled: if True, the theme will be filled
|
||||||
"""
|
"""
|
||||||
|
|
||||||
self.colors_json = colors_json
|
self.colors_json = colors_json
|
||||||
self.theme_folder = theme_folder
|
self.theme_folder = theme_folder
|
||||||
self.destination_folder = destination_folder
|
self.destination_folder = destination_folder
|
||||||
self.destination_file = destination_file
|
self.destination_file = destination_file
|
||||||
self.temp_folder = temp_folder
|
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.is_filled = is_filled
|
||||||
self.mode = mode
|
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):
|
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()
|
self.__find_themes()
|
||||||
|
|
||||||
def __extract(self):
|
def __is_installed(self) -> bool:
|
||||||
"""Extract gresource files to temp folder"""
|
if not hasattr(self, '__is_installed_cached'):
|
||||||
extract_line = Console.Line()
|
with open(self.__gresource_file, "rb") as f:
|
||||||
extract_line.update("Extracting gresource files...")
|
self.__is_installed_cached = self.__is_installed_trigger.encode() in f.read()
|
||||||
|
|
||||||
resources_list_response = subprocess.run(
|
return self.__is_installed_cached
|
||||||
["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
|
|
||||||
|
|
||||||
def __find_themes(self):
|
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_modes = ("dark", "light")
|
||||||
allowed_css = ("gnome-shell-dark", "gnome-shell-light", "gnome-shell")
|
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
|
mode = last_mode if last_mode in allowed_modes else None
|
||||||
self.__append_theme(style_name, mode=mode or self.mode, label=mode)
|
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"""
|
"""Helper to create theme objects"""
|
||||||
theme = Theme(theme_type, self.colors_json, self.theme_folder,
|
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)
|
mode=mode, is_filled=self.is_filled)
|
||||||
theme.prepare()
|
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))
|
self.themes.append(ThemePrepare(theme=theme, theme_file=theme_file, label=label))
|
||||||
|
|
||||||
def install(self, hue, sat=None):
|
def install(self, hue, sat=None):
|
||||||
@@ -124,34 +84,16 @@ class GlobalTheme:
|
|||||||
if os.geteuid() != 0:
|
if os.geteuid() != 0:
|
||||||
raise Exception("Root privileges required to install GDM theme")
|
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.__generate_themes(hue, 'Marble', sat)
|
||||||
self.__backup()
|
|
||||||
|
|
||||||
# generate gnome-shell-theme.gresource.xml
|
self.__gresource.compile()
|
||||||
with open(f"{self.extracted_theme}/{self.destination_file}.xml", 'w') as gresource_xml:
|
if not self.__is_installed():
|
||||||
generated_xml = self.__generate_gresource_xml()
|
self.__gresource.backup()
|
||||||
gresource_xml.write(generated_xml)
|
self.__gresource.move()
|
||||||
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()
|
self.__update_alternatives()
|
||||||
|
|
||||||
def __is_installed(self) -> bool:
|
def __generate_themes(self, hue: int, color: str, sat: Optional[int] = None):
|
||||||
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"""
|
"""Generate theme files for gnome-shell-theme.gresource.xml"""
|
||||||
for theme_prepare in self.themes:
|
for theme_prepare in self.themes:
|
||||||
if theme_prepare.label is not None:
|
if theme_prepare.label is not None:
|
||||||
@@ -164,60 +106,14 @@ class GlobalTheme:
|
|||||||
|
|
||||||
self.__add_gnome_styles(theme_prepare.theme)
|
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):
|
def __add_gnome_styles(self, theme: Theme):
|
||||||
"""Add gnome styles to the start of the file"""
|
"""Add gnome styles to the start of the file"""
|
||||||
with open(f"{theme.destination_folder}/{theme.theme_type}.css", 'r') as gnome_theme:
|
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)
|
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"<file>{rel_path}</file>")
|
|
||||||
nl = "\n" # fstring doesn't support newline character
|
|
||||||
|
|
||||||
return f"""<?xml version="1.0" encoding="UTF-8"?>
|
|
||||||
<gresources>
|
|
||||||
<gresource prefix="/org/gnome/shell/theme">
|
|
||||||
{nl.join(files_to_include)}
|
|
||||||
</gresource>
|
|
||||||
</gresources>"""
|
|
||||||
|
|
||||||
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):
|
def __update_alternatives(self):
|
||||||
link = os.path.join(self.destination_folder, config.ubuntu_gresource_link)
|
link = os.path.join(self.destination_folder, config.ubuntu_gresource_link)
|
||||||
name = config.ubuntu_gresource_link
|
name = config.ubuntu_gresource_link
|
||||||
@@ -228,17 +124,13 @@ class GlobalTheme:
|
|||||||
if self.__is_installed():
|
if self.__is_installed():
|
||||||
removing_line = Console.Line()
|
removing_line = Console.Line()
|
||||||
removing_line.update("Theme is installed. Removing...")
|
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):
|
try:
|
||||||
subprocess.run(["sudo", "mv", backup_path, dest_path], check=True)
|
self.__gresource.restore()
|
||||||
removing_line.success("Global theme removed successfully. Restart GDM to apply changes.")
|
removing_line.success("Global theme removed successfully. Restart GDM to apply changes.")
|
||||||
|
except GresourceBackupNotFoundError:
|
||||||
else:
|
|
||||||
formatted_shell = Console.format("gnome-shell", color=Color.BLUE, format_type=Format.BOLD)
|
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.")
|
removing_line.error(f"Backup file not found. Try reinstalling {formatted_shell} package.")
|
||||||
|
|
||||||
else:
|
else:
|
||||||
Console.Line().error("Theme is not installed. Nothing to remove.")
|
Console.Line().error("Theme is not installed. Nothing to remove.")
|
||||||
Console.Line().warn("If theme is still installed globally, try reinstalling gnome-shell package.")
|
Console.Line().warn("If theme is still installed globally, try reinstalling gnome-shell package.")
|
||||||
@@ -249,80 +141,9 @@ class GlobalTheme:
|
|||||||
AlternativesUpdater.remove(name, path)
|
AlternativesUpdater.remove(name, path)
|
||||||
|
|
||||||
|
|
||||||
class AlternativesUpdater:
|
class ThemePrepare:
|
||||||
@staticmethod
|
"""Theme data class prepared for installation"""
|
||||||
def ubuntu_specific(func):
|
def __init__(self, theme: Theme, theme_file, label: Optional[str] = None):
|
||||||
"""
|
self.theme = theme
|
||||||
Decorator for Ubuntu-specific functionality.
|
self.theme_file = theme_file
|
||||||
Silently ignores errors when not running on Ubuntu systems.
|
self.label = label
|
||||||
"""
|
|
||||||
@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.")
|
|
86
scripts/utils/alternatives_updater.py
Normal file
86
scripts/utils/alternatives_updater.py
Normal file
@@ -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.")
|
162
scripts/utils/gresource.py
Normal file
162
scripts/utils/gresource.py
Normal file
@@ -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"""
|
||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<gresources>
|
||||||
|
<gresource prefix="/org/gnome/shell/theme">
|
||||||
|
{nl.join(files_to_include)}
|
||||||
|
</gresource>
|
||||||
|
</gresources>
|
||||||
|
""")
|
||||||
|
|
||||||
|
def __get_files_to_include(self):
|
||||||
|
temp_path = Path(self.temp_folder)
|
||||||
|
return [
|
||||||
|
f"<file>{file.relative_to(temp_path)}</file>"
|
||||||
|
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.")
|
Reference in New Issue
Block a user