Optimize code

This commit is contained in:
Vladyslav Hroshev
2023-03-20 21:28:31 +02:00
parent e24425450c
commit 656958244a
3 changed files with 256 additions and 239 deletions

View File

@@ -22,118 +22,25 @@ import argparse
import textwrap
def destination_return(path_name, theme_mode):
def generate_file(folder, final_file):
"""
Copied/modified gnome-shell theme location
:param path_name: color name
:param theme_mode: theme name (light or dark)
:return: copied files' folder location
Combines all files in a folder into a single file
:param folder: source folder
:param final_file: location where file will be created
"""
return f"~/.themes/Marble-{path_name}-{theme_mode}/gnome-shell"
opened_file = open(final_file, "w")
for file in os.listdir(folder):
opened_file.write(open(folder + file).read() + '\n')
opened_file.close()
def copy_files(source, destination):
"""
Copy files from the source to another directory
:param source: where files will be copied
:param destination: where files will be pasted
"""
destinationDirs = destination.split("/")
loopCreateDirs = f"{destinationDirs[0]}/"
# create necessary folders
for i in range(1, len(destinationDirs)):
loopCreateDirs += f"{destinationDirs[i]}/"
os.system(f"mkdir -p {loopCreateDirs}")
os.system(f"cp -aT {source} {destination}")
def apply_colors(hue, destination, theme_mode, apply_file, sat=None):
"""
Install accent colors from colors.json to different file
:param hue
:param destination: file directory
:param theme_mode: theme name (light or dark)
:param apply_file: file name
:param sat: color saturation (optional)
"""
with open(os.path.expanduser(f"{destination}/{apply_file}"), "r") as file:
edit_file = file.read()
# colorsys works in range(0, 1)
h = hue / 360
for element in colors["elements"]:
# convert to range(0, 1)
lightness = int(colors["elements"][element][theme_mode]["l"]) / 100
saturation = int(colors["elements"][element][theme_mode]["s"]) / 100 if sat is None else int(
colors["elements"][element][theme_mode]["s"]) * (sat / 100) / 100
alpha = colors["elements"][element][theme_mode]["a"]
# convert hsl to rgb and multiple every item
red, green, blue = [int(item * 256) for item in colorsys.hls_to_rgb(h, lightness, saturation)]
replace_keyword = colors["elements"][element]["replace"]
edit_file = edit_file.replace(replace_keyword, f"rgba({red}, {green}, {blue}, {alpha})")
with open(os.path.expanduser(f"{destination}/{apply_file}"), "w") as file:
file.write(edit_file)
def generate_file():
gnome_shell = open("./gnome-shell/gnome-shell.css", "w")
for file in os.listdir("./css/"):
gnome_shell.write(open('./css/'+ file).read() + '\n')
gnome_shell.close()
def write_to_file(file, edit_file):
def concatenate_files(file, edit_file):
open(edit_file, 'a').write('\n' + open(file).read())
def apply_theme(hue, destination, theme_mode, sat=None):
"""
Apply theme to all files listed in "apply-theme-files" (colors.json)
:param hue
:param destination: file directory
:param theme_mode: theme name (light or dark)
:param sat: color saturation (optional)
"""
for apply_file in os.listdir("./gnome-shell/"):
apply_colors(hue, destination, theme_mode, apply_file, sat=sat)
def install_color(hue, name, theme_mode, sat=None):
"""
Copy files and generate theme with different accent color
:param hue
:param name: theme name
:param theme_mode: light or dark mode
:param sat: color saturation (optional)
"""
print(f"Creating {name} {', '.join(theme_mode)} theme...", end=" ")
try:
for mode in theme_mode:
copy_files("./gnome-shell", destination_return(name, mode))
apply_theme(hue, destination_return(name, mode), mode, sat=sat)
except Exception as err:
print("\nError: " + str(err))
else:
print("Done.")
def remove_files():
# Define the paths of the folders to be deleted
paths = ["~/.themes", "~/.local/share/themes"]
@@ -181,6 +88,126 @@ def remove_files():
print(f"The path {path} does not exist.")
def destination_return(path_name, theme_mode):
"""
Copied/modified gnome-shell theme location
:param path_name: color name
:param theme_mode: theme name (light or dark)
:return: copied files' folder location
"""
return f"~/.themes/Marble-{path_name}-{theme_mode}/gnome-shell"
def copy_files(source, destination):
"""
Copy files from the source to another directory
:param source: where files will be copied
:param destination: where files will be pasted
"""
destination_dirs = destination.split("/")
loop_create_dirs = f"{destination_dirs[0]}/"
# create necessary folders
for i in range(1, len(destination_dirs)):
loop_create_dirs += f"{destination_dirs[i]}/"
os.system(f"mkdir -p {loop_create_dirs}")
os.system(f"cp -aT {source} {destination}")
def apply_colors(hue, destination, theme_mode, apply_file, sat=None):
"""
Install accent colors from colors.json to different file
:param hue
:param destination: file directory
:param theme_mode: theme name (light or dark)
:param apply_file: file name
:param sat: color saturation (optional)
"""
with open(os.path.expanduser(f"{destination}/{apply_file}"), "r") as file:
edit_file = file.read()
# colorsys works in range(0, 1)
h = hue / 360
for element in colors["elements"]:
# convert to range(0, 1)
lightness = int(colors["elements"][element][theme_mode]["l"]) / 100
saturation = int(colors["elements"][element][theme_mode]["s"]) / 100 if sat is None else int(
colors["elements"][element][theme_mode]["s"]) * (sat / 100) / 100
alpha = colors["elements"][element][theme_mode]["a"]
# convert hsl to rgb and multiple every item
red, green, blue = [int(item * 256) for item in colorsys.hls_to_rgb(h, lightness, saturation)]
replace_keyword = colors["elements"][element]["replace"]
edit_file = edit_file.replace(replace_keyword, f"rgba({red}, {green}, {blue}, {alpha})")
with open(os.path.expanduser(f"{destination}/{apply_file}"), "w") as file:
file.write(edit_file)
def apply_theme(hue, destination, theme_mode, sat=None):
"""
Apply theme to all files listed in "apply-theme-files" (colors.json)
:param hue
:param destination: file directory
:param theme_mode: theme name (light or dark)
:param sat: color saturation (optional)
"""
for apply_file in os.listdir("./gnome-shell/"):
apply_colors(hue, destination, theme_mode, apply_file, sat=sat)
def install_color(hue, name, theme_mode, sat=None):
"""
Copy files and generate theme with different accent color
:param hue
:param name: theme name
:param theme_mode: light or dark mode
:param sat: color saturation (optional)
"""
print(f"Creating {name} {', '.join(theme_mode)} theme...", end=" ")
try:
for mode in theme_mode:
copy_files("./gnome-shell", destination_return(name, mode))
apply_theme(hue, destination_return(name, mode), mode, sat=sat)
except Exception as err:
print("\nError: " + str(err))
else:
print("Done.")
def hex_to_rgba(hex_color):
"""
Convert hex(a) to rgba
:param hex_color: input value
"""
try:
if len(hex_color) in range(6, 10):
hex_color = hex_color.lstrip('#') + "ff"
# is convertable
int(hex_color[:], 16)
else:
raise ValueError
except ValueError:
raise ValueError(f'Error: Invalid HEX color code: {hex_color}')
else:
return int(hex_color[0:2], 16), int(hex_color[2:4], 16), int(hex_color[4:6], 16), int(hex_color[6:8], 16) / 255
def main():
parser = argparse.ArgumentParser(prog="python install.py",
formatter_class=argparse.RawDescriptionHelpFormatter,
@@ -214,12 +241,6 @@ def main():
custom_args.add_argument('--hue', type=int, choices=range(0, 361), help='generate theme from Hue prompt',
metavar='(0 - 360)')
custom_args.add_argument('--name', nargs='?', help='theme name (optional)')
# Add arguments for panel tweaks
panel_args = parser.add_argument_group('Panel tweaks')
panel_args.add_argument('--panel_default_size', action='store_true', help='set default panel size')
panel_args.add_argument('--panel_no_pill', action='store_true', help='remove panel button background')
panel_args.add_argument('--panel_text_color', type=str, nargs='?', help='custom panel HEXA text color')
# Add arguments for optional theme tweaks
color_tweaks = parser.add_argument_group('Optional theme tweaks')
@@ -227,38 +248,31 @@ def main():
color_tweaks.add_argument('--sat', type=int, choices=range(0, 251),
help='custom color saturation (<100%% - reduce, >100%% - increase)', metavar='(0 - 250)%')
# Add arguments for panel tweaks
panel_args = parser.add_argument_group('Panel tweaks')
panel_args.add_argument('-Pds', '--panel_default_size', action='store_true', help='set default panel size')
panel_args.add_argument('-Pnp', '--panel_no_pill', action='store_true', help='remove panel button background')
panel_args.add_argument('-Ptc', '--panel_text_color', type=str, nargs='?', help='custom panel HEX(A) text color')
args = parser.parse_args()
mode = [args.mode] if args.mode else ['light', 'dark']
generate_file()
generate_file("./css/", gnome_shell_css)
if args.panel_default_size:
write_to_file("./tweaks/panel/def-size.css", "./gnome-shell/gnome-shell.css")
concatenate_files("./tweaks/panel/def-size.css", gnome_shell_css)
if args.panel_no_pill:
write_to_file("./tweaks/panel/no-pill.css", "./gnome-shell/gnome-shell.css")
concatenate_files("./tweaks/panel/no-pill.css", gnome_shell_css)
if args.panel_text_color and len(args.panel_text_color) in range(6, 10):
try:
args.panel_text_color = args.panel_text_color.lstrip('#') + "ff"
int(args.panel_text_color[:], 16)
except ValueError:
print(f'Error: Invalid HEXA color code: {args.panel_text_color}')
else:
print(f'Panel HEXA color code: {args.panel_text_color}')
open('./gnome-shell/gnome-shell.css', 'a')\
.write(".panel-button,\
.clock,\
.clock-display StIcon {\
color: rgba(" +
', '.join(str(int(args.panel_text_color[i:i+2], 16)) for i in (0, 2, 4)) +
', ' + str(int(args.panel_text_color[6:8], 16) / 255) + ");\
}")
if args.panel_text_color:
open('./gnome-shell/gnome-shell.css', 'a') \
.write(".panel-button,\
.clock,\
.clock-display StIcon {\
color: rgba(" + ', '.join(map(str, hex_to_rgba(args.panel_text_color))) + ");\
}")
# Process the arguments and perform the installation accordingly
if args.remove:
@@ -291,8 +305,9 @@ def main():
if __name__ == "__main__":
gnome_shell_css = "./gnome-shell/gnome-shell.css"
colors = json.load(open("colors.json")) # used as database for replacing colors
main()
os.remove("./gnome-shell/gnome-shell.css")
os.remove("./gnome-shell/gnome-shell.css")