Skip to content

Commit

Permalink
Merge pull request #222 from deviantfero/keyword-per-theme
Browse files Browse the repository at this point in the history
Implement keyword per colorscheme feature/interface
  • Loading branch information
deviantfero authored Aug 15, 2021
2 parents 70226b4 + 090b155 commit c3505dc
Show file tree
Hide file tree
Showing 14 changed files with 310 additions and 196 deletions.
19 changes: 6 additions & 13 deletions wpgtk/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,11 +122,6 @@ def read_args(args):
help="preview your current colorscheme",
action="store_true")

parser.add_argument("--update",
help="update template(s) of your choice "
"to the new format",
nargs="+")

parser.add_argument("--noreload",
help="Skip reloading other software after"
"applying colorscheme",
Expand All @@ -136,6 +131,10 @@ def read_args(args):


def process_arg_errors(args):
if args.r and not args.s:
logging.error("invalid combination of flags, use with -s")
exit(1)

if args.m and (args.s or args.R):
logging.error("invalid combination of flags")
exit(1)
Expand Down Expand Up @@ -194,8 +193,8 @@ def process_args(args):

if args.l:
if args.t:
templates = files.get_file_list(OPT_DIR, False)
any(print(t) for t in templates if ".base" in t)
templates = files.get_file_list(OPT_DIR, r".*\.base$")
any(print(t) for t in templates)
else:
print("\n".join(files.get_file_list()))
exit(0)
Expand Down Expand Up @@ -295,12 +294,6 @@ def process_args(args):
print("\n".join(pywal.colors.list_backends()))
exit(0)

if args.update:
for arg in args.update:
if arg.endswith(".base"):
files.update_template(arg)
exit(0)

if args.noreload:
settings["reload"] = "false"

Expand Down
47 changes: 27 additions & 20 deletions wpgtk/data/color.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@
from subprocess import Popen
from random import shuffle, randint

from .config import settings, user_keywords
from .config import settings
from .config import WALL_DIR, WPG_DIR, FILE_DIC, OPT_DIR
from . import keywords
from . import files
from . import util
from . import sample
Expand Down Expand Up @@ -169,8 +170,7 @@ def auto_adjust(colors):
def change_templates(colors):
"""call change_colors on each custom template
installed or defined by the user"""
templates = files.get_file_list(OPT_DIR, images=False)
templates = [x for x in templates if ".base" in x]
templates = files.get_file_list(OPT_DIR, r".*\.base$")

try:
for template in templates:
Expand Down Expand Up @@ -230,38 +230,45 @@ def keyword_colors(hexc, is_dark_theme=True):
}


def get_color_dict(cdic):
"""ensamble wpgtk color dictionary"""
def get_color_dict(pywal_colors, colorscheme):
"""ensamble wpgtk color dictionary from pywal color dictionary"""
keyword_set = settings.get('keywords', 'default')
index = settings.getint("active")
index = index if index > 0 else randint(9, 14)

base_color = cdic["colors"]["color%s" % index]
color_list = list(cdic["colors"].values())
base_color = pywal_colors["colors"]["color%s" % index]
color_list = list(pywal_colors["colors"].values())
keyword_dict = keywords.get_keywords_section(keyword_set)

all_colors = {
"wallpaper": cdic["wallpaper"],
"alpha": cdic["alpha"],
**cdic["special"],
**cdic["colors"],
**add_icon_colors(cdic),
"wallpaper": pywal_colors["wallpaper"],
"alpha": pywal_colors["alpha"],
**pywal_colors["special"],
**pywal_colors["colors"],
**add_icon_colors(pywal_colors),
**keyword_colors(base_color, is_dark_theme(color_list))
}

try:
user_words = {k: v.format(**all_colors)
for k, v in user_keywords.items()}
all_colors = {**all_colors, **user_words}
all_colors = {
k: pywal.util.Color(v) for k, v in all_colors.items()
}

try:
user_words = {
k: pywal.util.Color(v.format_map(all_colors))
for k, v in keyword_dict.items()
}
except KeyError as e:
logging.error("%s - invalid, use double {{}} "
"to escape curly braces" % e)

return {k: pywal.util.Color(v) for k, v in all_colors.items()}

return {**all_colors, **user_words}

def apply_colorscheme(colors):
color_dict = get_color_dict(colors)

def apply_colorscheme(color_dict):
"""Receives a colorscheme dict ensambled by
color.get_color_dict as argument and applies it
system-wide."""
if os.path.isfile(FILE_DIC["icon-step2"]):
change_colors(color_dict, "icon-step1")
Popen(FILE_DIC["icon-step2"])
Expand Down
55 changes: 41 additions & 14 deletions wpgtk/data/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
import os
import logging

__version__ = '6.2.5'
__version__ = '6.5.0'

parser = None

settings = None

HOME = os.getenv("HOME", os.path.expanduser("~"))
CACHE = os.getenv("XDG_CACHE_HOME", os.path.join(HOME, ".cache"))
Expand All @@ -14,6 +15,7 @@

WPG_DIR = os.path.join(CONFIG, "wpg")
CONF_FILE = os.path.join(WPG_DIR, "wpg.conf")
KEYWORD_FILE = os.path.join(WPG_DIR, "keywords.conf")
MODULE_DIR = os.path.abspath(os.path.join(__file__, "../../"))
CONF_BACKUP = os.path.join(MODULE_DIR, "misc/wpg.conf")
WALL_DIR = os.path.join(WPG_DIR, "wallpapers")
Expand All @@ -30,38 +32,63 @@


def write_conf(config_path=CONF_FILE):
global parser
global config_parser

with open(config_path, 'w') as config_file:
parser.write(config_file)
config_parser.write(config_file)


def write_keywords(keywords_path=KEYWORD_FILE):
global user_keywords

with open(keywords_path, 'w') as keywords_file:
user_keywords.write(keywords_file)

def load_sections():

def load_settings():
"""reads the sections of the config file"""
global parser
global settings
global user_keywords
global config_parser

parser = configparser.ConfigParser()
parser.optionxform = str
parser.read(CONF_FILE)
config_parser = configparser.ConfigParser()
config_parser.optionxform = str
config_parser.read(CONF_FILE)
settings = config_parser['settings']

return [parser['settings'], parser['keywords']]

def load_keywords():
global user_keywords

def load_settings():
if not os.path.exists(KEYWORD_FILE):
open(KEYWORD_FILE, 'a').close()

user_keywords = configparser.ConfigParser()
user_keywords.optionxform = str
user_keywords.read(KEYWORD_FILE)

if not user_keywords.has_section('default'):
user_keywords.add_section('default')
write_keywords()


def init_config():
os.makedirs(WALL_DIR, exist_ok=True)
os.makedirs(SAMPLE_DIR, exist_ok=True)
os.makedirs(SCHEME_DIR, exist_ok=True)
os.makedirs(FORMAT_DIR, exist_ok=True)
os.makedirs(OPT_DIR, exist_ok=True)

try:
return load_sections()
load_settings()
load_keywords()
except Exception:
logging.error("not a valid config file")
logging.info("copying default config file")

shutil.copy(CONF_BACKUP, CONF_FILE)
return load_sections()
load_settings()
load_keywords()


settings, user_keywords = load_settings()
init_config()
57 changes: 19 additions & 38 deletions wpgtk/data/files.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,23 @@
import shutil
import re
import logging
from subprocess import Popen
from pywal.colors import cache_fname, list_backends

from .config import settings, WALL_DIR, WPG_DIR, OPT_DIR, SAMPLE_DIR
from os.path import join, basename
from .config import (
settings,
WALL_DIR,
WPG_DIR,
OPT_DIR,
SAMPLE_DIR,
)


def get_file_list(path=WALL_DIR, images=True):
"""gets filenames in a given directory, optional
parameters for image filter."""
def get_file_list(path=WALL_DIR, regex=None):
"""gets file names in a given directory, optional regex
parameter to filter the list of files by."""

valid = re.compile(r"^[^\.](.*\.png$|.*\.jpg$|.*\.jpeg$|.*\.jpe$|.*\.gif$)")
files = []

for _, _, filenames in os.walk(path):
Expand All @@ -21,7 +27,8 @@ def get_file_list(path=WALL_DIR, images=True):

files.sort()

if images:
if regex is not None:
valid = re.compile(regex)
return [elem for elem in files if valid.fullmatch(elem)]
else:
return files
Expand All @@ -39,6 +46,7 @@ def write_script(wallpaper, colorscheme):
with open(join(WPG_DIR, "wp_init.sh"), "w") as script:
command = "wpg %s '%s' '%s'" % (flags, wallpaper, colorscheme)
script.writelines(["#!/usr/bin/env bash\n", command])
Popen(['chmod', '+x', join(WPG_DIR, "wp_init.sh")])


def get_cache_path(wallpaper, backend=None):
Expand Down Expand Up @@ -79,8 +87,7 @@ def add_template(cfile, bfile=None):
src_file = bfile if bfile else cfile

shutil.copy2(src_file, join(OPT_DIR, template_name))
os.symlink(cfile, join(OPT_DIR,
template_name.replace(".base", "")))
os.symlink(cfile, join(OPT_DIR, template_name.replace(".base", "")))

logging.info("created backup %s.bak" % cfile)
logging.info("added %s @ %s" % (template_name, cfile))
Expand All @@ -102,42 +109,16 @@ def delete_template(basefile):
logging.error(str(e.strerror))


def delete_colorschemes(wallpaper):
"""delete all colorschemes related to the given wallpaper"""
def delete_colorschemes(colorscheme):
"""delete all files related to the given colorscheme"""
for backend in list_backends():
try:
os.remove(get_cache_path(wallpaper, backend))
os.remove(get_sample_path(wallpaper, backend))
os.remove(get_cache_path(colorscheme, backend))
os.remove(get_sample_path(colorscheme, backend))
except OSError:
pass


def update_color(matchobj):
if matchobj.group(1):
return "{%s}" % matchobj.group(1).lower()


def update_template(template_path):
tmp_data = ""

with open(template_path, "r") as f:
tmp_data = f.read()

logging.info("escaping legitimate curly braces {} -> {{}}")
tmp_data = tmp_data.replace("{", "{{")
tmp_data = tmp_data.replace("}", "}}")

logging.info("replacing #<COLORXX> with braces {colorxx}")
tmp_data = re.sub(r"#<(COLOR[0-9]{1,2})>", update_color, tmp_data)
tmp_data = tmp_data.replace("#<COLORACT>", "{active}")
tmp_data = tmp_data.replace("#<COLORIN>", "{inactive}")

with open(template_path, "w") as f:
logging.info("writting %s" % template_path)
f.write(tmp_data)
logging.info("%s update complete" % template_path)


def change_current(filename):
"""update symlink to point to the current wallpaper"""
os.symlink(join(WALL_DIR, filename), join(WPG_DIR, ".currentTmp"))
Expand Down
Loading

0 comments on commit c3505dc

Please sign in to comment.