big updates

This commit is contained in:
sankalp committed 2024-07-30 10:19:03 +05:45
1 parent 0c82692536
commit c7c8ea67c7
42 files changed
+1083 -665

No files matched your search

+221
View File
@@ -0,0 +1,221 @@
import os
import sys
import importlib.util
import argparse
import fcntl
import subprocess
import asyncio
import random as _random
import colorsys
import json
lock_file_path = '/tmp/wallpaper.lock'
def acquire_lock():
global lock_file
lock_file = open(lock_file_path, 'w')
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
lock_file.write(str(os.getpid()))
lock_file.flush()
except IOError:
print("Another instance of the script is already running.")
sys.exit(1)
def release_lock():
fcntl.flock(lock_file, fcntl.LOCK_UN)
lock_file.close()
os.remove(lock_file_path)
def hue_to_numeric_hex(hue):
hue = hue / 360.0
rgb = colorsys.hls_to_rgb(hue, 0.5, 1.0)
hex_color_str = '#{:02x}{:02x}{:02x}'.format(int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))
numeric_hex_color = int(hex_color_str.lstrip('#'), 16)
return numeric_hex_color
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-I', '--image', type=str, help="Image")
group.add_argument('-P', '--prev', help="Use last used wallpaper for color generation", action='store_true')
group.add_argument('-R', '--random', help="Random image from folder", action='store_true')
parser.add_argument('-n', '--notify', help="Send notifications", action='store_true')
parser.add_argument('--status', type=str, help="Status file", default="/tmp/wallpaper.status")
args = parser.parse_args()
random = args.random
prev = args.prev
image = args.image
notify = args.notify
status = args.status
HOME = os.path.expanduser("~")
# Load configuration from JSON file
config_file = f"{HOME}/dotfiles/ags/assets/settings.json" # Path to your JSON configuration file
with open(config_file, 'r') as f:
config = json.load(f)
color_scheme = config.get("color-scheme", "dark")
custom_color = config.get("custom-color", "none")
generation_scheme = config.get("generation-scheme", "tonalSpot")
transition_type = config.get("swww-anim", "wipe")
module_path = f'{HOME}/dotfiles/material-colors'
sys.path.append(module_path)
module_name = 'generate'
file_path = f'{module_path}/{module_name}.py'
spec = importlib.util.spec_from_file_location(module_name, file_path)
GENERATOR = importlib.util.module_from_spec(spec) # type: ignore
spec.loader.exec_module(GENERATOR) # type: ignore
cache_file = f"{HOME}/.cache/current_wallpaper"
square = f"{HOME}/.cache/square_wallpaper.png"
png = f"{HOME}/.cache/current_wallpaper.png"
def current_state(str: str):
with open(status, 'w') as f:
f.write(str)
def send_notify(label: str, desc: str):
if not notify:
return
subprocess.run(["notify-send", label, desc])
def state(name: str | None, label: str | None, desc: str | None):
if name is not None:
current_state(name)
if label is not None:
send_notify(label, desc or "")
def join(*args):
return os.path.join(*args)
async def main():
state("init", None, None)
new_wallpaper = f"{HOME}/Pictures/wallpapers/1.jpg"
if random:
files = [f for f in os.listdir(f"{HOME}/Pictures/wallpapers") if f.endswith(('.png', '.jpg', '.jpeg'))]
if files:
new_wallpaper = join(f"{HOME}/Pictures/wallpapers", _random.choice(files))
elif prev:
try:
with open(cache_file) as f:
new_wallpaper = f.read().strip()
except FileNotFoundError:
...
elif image is not None:
new_wallpaper = os.path.abspath(image)
print(f":: Wallpaper {new_wallpaper}")
with open(cache_file, 'w') as f:
f.write(new_wallpaper)
with_image = f"with image {new_wallpaper}"
# -----------------------------------------------------
# Set the new wallpaper
# -----------------------------------------------------
wallpaper_engine = "swww" # Default wallpaper engine
state("changing", "Changing wallpaper...", with_image)
print(":: Changing wallpaper...")
if wallpaper_engine == "swww":
print(":: Using swww")
cursor_pos = subprocess.getoutput('hyprctl cursorpos')
subprocess.run([
'swww', 'img', new_wallpaper,
'--transition-bezier', '.43,1.19,1,.4',
'--transition-fps', '60',
'--transition-type', transition_type,
'--transition-duration', '0.7',
'--transition-pos', cursor_pos.replace(",",",")
])
else:
print(":: Wallpaper Engine disabled")
# -----------------------------------------------------
# Generate colors
# -----------------------------------------------------
state("colors", "Generating colors...", with_image)
print(":: Generate colors")
_starts_with = (lambda x: str(x).startswith("-"))
GENERATOR.main(
color_scheme, new_wallpaper,
(hue_to_numeric_hex(int(custom_color.lstrip("-")))
if _starts_with(custom_color) else (
int(custom_color.lstrip('#'), 16)
if custom_color != "none"
else None
)),
scheme=GENERATOR.schemes[generation_scheme]
)
# -----------------------------------------------------
# Square image
# -----------------------------------------------------
square_task = asyncio.create_task(square_image(new_wallpaper))
# -----------------------------------------------------
# Png image
# -----------------------------------------------------
png_task = asyncio.create_task(png_image(new_wallpaper))
state("tasks", None, None)
await asyncio.gather(square_task, png_task)
state("finish", "Wallpaper procedure complete!", with_image)
async def png_image(wallpaper: str):
_from = (".jpg", "jpeg")
if not wallpaper.endswith(_from):
cmd = f"cp -f {wallpaper} {png}"
else:
with_image = f"with image {wallpaper}"
state(None, "Converting jpg to png...", with_image)
print(":: Converting jpg to png...")
cmd = f"magick {wallpaper} {png}"
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
print(f":: Error while processing image: {stderr.decode()}")
else:
print(":: JPG successfully converted to PNG!")
async def square_image(wallpaper):
with_image = f"with image {wallpaper}"
state(None, "Creating square version...", with_image)
print(":: Creating square version")
cmd = f"magick {wallpaper} -gravity Center -extent 1:1 {square}"
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
print(f":: Error while processing image: {stderr.decode()}")
else:
print(":: Square image created!")
if __name__ == "__main__":
acquire_lock()
try:
asyncio.run(main())
finally:
release_lock()
+262
View File
@@ -0,0 +1,262 @@
import os
import sys
import importlib.util
import argparse
import fcntl
import subprocess
import asyncio
import random as _random
import colorsys
import json
lock_file_path = '/tmp/wallpaper.lock'
def acquire_lock():
global lock_file
lock_file = open(lock_file_path, 'w')
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
lock_file.write(str(os.getpid()))
lock_file.flush()
except IOError:
print("Another instance of the script is already running.")
sys.exit(1)
def release_lock():
fcntl.flock(lock_file, fcntl.LOCK_UN)
lock_file.close()
os.remove(lock_file_path)
def hue_to_numeric_hex(hue):
hue = hue / 360.0
rgb = colorsys.hls_to_rgb(hue, 0.5, 1.0)
hex_color_str = '#{:02x}{:02x}{:02x}'.format(int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))
numeric_hex_color = int(hex_color_str.lstrip('#'), 16)
return numeric_hex_color
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-I', '--image', type=str, help="Image")
group.add_argument('-P', '--prev', help="Use last used wallpaper for color generation", action='store_true')
group.add_argument('-R', '--random', help="Random image from folder", action='store_true')
parser.add_argument('-n', '--notify', help="Send notifications", action='store_true')
parser.add_argument('--status', type=str, help="Status file", default="/tmp/wallpaper.status")
args = parser.parse_args()
random = args.random
prev = args.prev
image = args.image
notify = args.notify
status = args.status
HOME = os.path.expanduser("~")
module_path = f'{HOME}/dotfiles/material-colors'
sys.path.append(module_path)
module_name = 'generate'
file_path = f'{module_path}/{module_name}.py'
spec = importlib.util.spec_from_file_location(module_name, file_path)
GENERATOR = importlib.util.module_from_spec(spec) # type: ignore
spec.loader.exec_module(GENERATOR) # type: ignore
cache_file = f"{HOME}/.cache/current_wallpaper"
square = f"{HOME}/.cache/square_wallpaper.png"
png = f"{HOME}/.cache/current_wallpaper.png"
settings_file = f"{HOME}/dotfiles/ags/assets/settings.json"
# Read settings from the JSON file
with open(settings_file) as f:
settings = json.load(f)
color_scheme = settings.get("color-scheme")
custom_color = settings.get("custom-color")
generation_scheme = settings.get("generation-scheme")
swww_animation = settings.get("swww-anim")
wallpaper_engine = settings.get("wallpaper-engine")
def current_state(str: str):
with open(status, 'w') as f:
f.write(str)
def send_notify(label: str, desc: str):
if not notify:
return
subprocess.run(["notify-send", label, desc])
def state(name: str | None, label: str | None, desc: str | None):
if name is not None:
current_state(name)
if label is not None:
send_notify(label, desc or "")
def join(*args):
return os.path.join(*args)
async def main():
global color_scheme, custom_color
state("init", None, None)
new_wallpaper = f"{HOME}/Pictures/wallpapers/default.jpg"
if random:
files = [f for f in os.listdir(f"{HOME}/Pictures/wallpapers") if f.endswith(('.png', '.jpg', '.jpeg'))]
if files:
new_wallpaper = join(f"{HOME}/Pictures/wallpapers", _random.choice(files))
elif prev:
try:
with open(cache_file) as f:
new_wallpaper = f.read().strip()
except FileNotFoundError:
...
elif image is not None:
new_wallpaper = os.path.abspath(image)
print(f":: Wallpaper {new_wallpaper}")
with open(cache_file, 'w') as f:
f.write(new_wallpaper)
with_image = f"with image {new_wallpaper}"
# -----------------------------------------------------
# Set the new wallpaper
# -----------------------------------------------------
transition_type = swww_animation
# transition_type = "outer"
# transition_type = "random"
state("changing", "Changing wallpaper...", with_image)
print(":: Changing wallpaper...")
if wallpaper_engine == "swww":
print(":: Using swww")
cursor_pos = subprocess.getoutput('hyprctl cursorpos').replace(", ", ",")
subprocess.run([
'swww', 'img', new_wallpaper,
'--transition-bezier', '.43,1.19,1,.4',
'--transition-fps', '60',
'--transition-type', transition_type,
'--transition-duration', '0.7',
'--transition-pos', cursor_pos
])
elif wallpaper_engine == "hyprpaper":
print(":: Using hyprpaper")
subprocess.run(['killall', 'hyprpaper'])
hyprpaper_tpl_file = os.path.expanduser('~/dotfiles/.settings/hyprpaper.tpl')
with open(hyprpaper_tpl_file, 'r') as file:
wal_tpl = file.read()
output = wal_tpl.replace('WALLPAPER', new_wallpaper)
hyprpaper_conf_file = os.path.expanduser('~/dotfiles/hypr/hyprpaper.conf')
with open(hyprpaper_conf_file, 'w') as file:
file.write(output)
subprocess.run([
"hyprctl", "dispatch", "exec", "hyprpaper"
])
else:
print(":: Wallpaper Engine disabled")
# -----------------------------------------------------
# Generate colors
# -----------------------------------------------------
state("colors", "Generating colors...", with_image)
print(":: Generate colors")
_starts_with = (lambda x: str(x).startswith("-"))
GENERATOR.main(
color_scheme, new_wallpaper,
(hue_to_numeric_hex(int(custom_color.lstrip("-")))
if _starts_with(custom_color) else (
int(custom_color.lstrip('#'), 16)
if custom_color != "none"
else None
)),
scheme=GENERATOR.schemes[generation_scheme]
)
# -----------------------------------------------------
# Square image
# -----------------------------------------------------
square_task = asyncio.create_task(square_image(new_wallpaper))
# -----------------------------------------------------
# Png image
# -----------------------------------------------------
png_task = asyncio.create_task(png_image(new_wallpaper))
state("tasks", None, None)
await asyncio.gather(square_task, png_task)
state("finish", "Wallpaper procedure complete!", with_image)
async def png_image(wallpaper: str):
_from = (".jpg", "jpeg")
if not wallpaper.endswith(_from):
cmd = f"cp -f {wallpaper} {png}"
else:
with_image = f"with image {wallpaper}"
state(None, "Converting jpg to png...", with_image)
print(":: Converting jpg to png...")
cmd = f"magick {wallpaper} {png}"
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
print(f":: Error while processing image: {stderr.decode()}")
else:
print(":: JPG successfully converted to PNG!")
async def square_image(wallpaper):
with_image = f"with image {wallpaper}"
state(None, "Creating square version...", with_image)
print(":: Creating square version")
cmd = f"magick {wallpaper} -gravity Center -extent 1:1 {square}"
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
print(f":: Error while processing image: {stderr.decode()}")
else:
print(":: Square image created!")
if __name__ == "__main__":
acquire_lock()
try:
asyncio.run(main())
finally:
release_lock()
-2
View File
@@ -1,8 +1,6 @@
#!/bin/bash
source ~/dotfiles/hypr/scripts/Ui_cmd.sh
source ~/dotfiles/hypr/scripts/Music_cmd.sh
help() {
declare -F
+1 -1
View File
@@ -43,7 +43,7 @@ shotarea() {
local tmpfile=$(mktemp)
local area=$(slurp)
if [[ -z "$area" ]]; then
notify-send -u low -i "$iDIR/picture.png" 'No area selected'
notify-send -u low -i "$iDIR/cancel.svg" 'No area selected'
rm "$tmpfile"
return
fi
+3 -67
View File
@@ -3,30 +3,6 @@
notif="$HOME/dotfiles/hypr/assets/bell.png"
# For Keyboard Layout Switcher
######################################
# #
# Toggle Blur #
# #
######################################
toggle_blur (){
STATE=$(hyprctl -j getoption decoration:blur:passes | jq ".int")
if [ "${STATE}" == "2" ]; then
hyprctl keyword decoration:blur:size 2
hyprctl keyword decoration:blur:passes 1
notify-send -e -u low -i "$notif" "Less blur"
else
hyprctl keyword decoration:blur:size 5
hyprctl keyword decoration:blur:passes 2
notify-send -e -u low -i "$notif" "Normal blur"
fi
}
######################################
# #
# Toggle Animation #
@@ -77,32 +53,6 @@ change_layout() {
}
######################################
# #
# Auto Wallpaper Changer #
# #
######################################
auto_wall() {
wallDIR="$HOME/Pictures/wallpapers"
FPS=60
TYPE="random"
DURATION=1
BEZIER=".43,1.19,1,.4"
SWWW_PARAMS="--transition-fps ${FPS} --transition-type ${TYPE} --transition-duration ${DURATION} --transition-bezier ${BEZIER}"
focused_monitor=$(hyprctl monitors | awk '/^Monitor/{name=$2} /focused: yes/{print name}')
INTERVAL=1800 # This controls (in seconds) when to switch to the next image
while true; do
find "$wallDIR" -type f \( -name "*.jpg" -o -name "*.jpeg" -o -name "*.png" -o -name "*.gif" \) -print0 \
| shuf -z -n 1 \
| xargs -0 -I {} swww img -o $focused_monitor "{}" ${SWWW_PARAMS} &&
$RunCMD symlink
sleep $INTERVAL
done
}
######################################
# #
# GameMode #
@@ -122,23 +72,9 @@ gamemode() {
}
######################################
# #
# Toggle Opaque #
# #
######################################
enable_opaque() {
sleep 0.2
hyprctl setprop address:$(hyprctl -j activewindow | jq -r -c ".address") forceopaque 0 lock
}
disable_opaque() {
sleep 0.2
hyprctl setprop address:$(hyprctl -j activewindow | jq -r -c ".address") forceopaque 1 lock
}
######################################
# Keyboard Layout Switcher #
# #
# #
# Keyboard Layout Switcher #
# #
######################################
kb_changer() {
+18
View File
@@ -0,0 +1,18 @@
#!/bin/bash
# Path to your JSON file
JSON_FILE="$HOME/dotfiles/.settings/apps.json"
# Read the application type from the argument
APP_TYPE=$1
# Extract the corresponding application value from the JSON file using jq
APP=$(jq -r ".$APP_TYPE" "$JSON_FILE")
# Check if the application is defined in the JSON file
if [ "$APP" != "null" ]; then
# Open the specified application
$APP
else
echo "No application defined for $APP_TYPE in $JSON_FILE"
fi
+24
View File
@@ -0,0 +1,24 @@
#!/bin/bash
# Path to your settings JSON file
settings_file="$HOME/dotfiles/.settings/settings.json"
# Read wallpaper engine from the JSON file
wallpaper_engine=$(jq -r '.["wallpaper-engine"]' "$settings_file")
if [ "$wallpaper_engine" == "swww" ]; then
# swww
echo ":: Using swww"
swww-daemon
swww-daemon --format xrgb
sleep 0.5
python -O ~/dotfiles/hypr/scripts/wallpaper.py -P
elif [ "$wallpaper_engine" == "hyprpaper" ]; then
# hyprpaper
echo ":: Using hyprpaper"
sleep 0.5
python -O ~/dotfiles/hypr/scripts/wallpaper.py -P
else
echo ":: Wallpaper Engine disabled"
python -O ~/dotfiles/hypr/scripts/wallpaper.py -P
fi
+55 -18
View File
@@ -10,6 +10,8 @@ import colorsys
import json
lock_file_path = '/tmp/wallpaper.lock'
settings_file_path = os.path.expanduser('~/dotfiles/.settings/settings.json')
def acquire_lock():
global lock_file
@@ -22,18 +24,28 @@ def acquire_lock():
print("Another instance of the script is already running.")
sys.exit(1)
def release_lock():
fcntl.flock(lock_file, fcntl.LOCK_UN)
lock_file.close()
os.remove(lock_file_path)
def hue_to_numeric_hex(hue):
hue = hue / 360.0
rgb = colorsys.hls_to_rgb(hue, 0.5, 1.0)
hex_color_str = '#{:02x}{:02x}{:02x}'.format(int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))
hex_color_str = '#{:02x}{:02x}{:02x}'.format(
int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255)
)
numeric_hex_color = int(hex_color_str.lstrip('#'), 16)
return numeric_hex_color
def load_settings():
with open(settings_file_path, 'r') as file:
return json.load(file)
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-I', '--image', type=str, help="Image")
@@ -52,17 +64,6 @@ status = args.status
HOME = os.path.expanduser("~")
# Load configuration from JSON file
config_file = f"{HOME}/dotfiles/ags/assets/settings.json" # Path to your JSON configuration file
with open(config_file, 'r') as f:
config = json.load(f)
color_scheme = config.get("color-scheme", "dark")
custom_color = config.get("custom-color", "none")
generation_scheme = config.get("generation-scheme", "tonalSpot")
transition_type = config.get("swww-anim", "wipe")
module_path = f'{HOME}/dotfiles/material-colors'
sys.path.append(module_path)
@@ -77,28 +78,43 @@ cache_file = f"{HOME}/.cache/current_wallpaper"
square = f"{HOME}/.cache/square_wallpaper.png"
png = f"{HOME}/.cache/current_wallpaper.png"
def current_state(str: str):
def current_state(state_str: str):
with open(status, 'w') as f:
f.write(str)
f.write(state_str)
def send_notify(label: str, desc: str):
if not notify:
return
subprocess.run(["notify-send", label, desc])
def state(name: str | None, label: str | None, desc: str | None):
if name is not None:
current_state(name)
if label is not None:
send_notify(label, desc or "")
def join(*args):
return os.path.join(*args)
async def main():
global color_scheme, custom_color, generation_scheme, swww_animation, wallpaper_engine, hyprpaper_tpl
state("init", None, None)
new_wallpaper = f"{HOME}/Pictures/wallpapers/1.jpg"
settings = load_settings()
color_scheme = settings['color-scheme']
custom_color = settings['custom-color']
generation_scheme = settings['generation-scheme']
swww_animation = settings['swww-anim']
wallpaper_engine = settings['wallpaper-engine']
hyprpaper_tpl = settings['hyprpaper-tpl']
new_wallpaper = f"{HOME}/Picutres/wallpapers/default.jpg"
if random:
files = [f for f in os.listdir(f"{HOME}/Pictures/wallpapers") if f.endswith(('.png', '.jpg', '.jpeg'))]
@@ -123,14 +139,16 @@ async def main():
# -----------------------------------------------------
# Set the new wallpaper
# -----------------------------------------------------
wallpaper_engine = "swww" # Default wallpaper engine
transition_type = swww_animation
state("changing", "Changing wallpaper...", with_image)
print(":: Changing wallpaper...")
if wallpaper_engine == "swww":
print(":: Using swww")
cursor_pos = subprocess.getoutput('hyprctl cursorpos')
cursor_pos = subprocess.getoutput('hyprctl cursorpos').replace(", ", ",")
subprocess.run([
'swww', 'img', new_wallpaper,
@@ -138,8 +156,24 @@ async def main():
'--transition-fps', '60',
'--transition-type', transition_type,
'--transition-duration', '0.7',
'--transition-pos', cursor_pos.replace(",",",")
'--transition-pos', cursor_pos
])
elif wallpaper_engine == "hyprpaper":
print(":: Using hyprpaper")
subprocess.run(['killall', 'hyprpaper'])
output = hyprpaper_tpl.replace('WALLPAPER', new_wallpaper)
hyprpaper_conf_file = os.path.expanduser('~/dotfiles/hypr/hyprpaper.conf')
with open(hyprpaper_conf_file, 'w') as file:
file.write(output)
subprocess.run([
"hyprctl", "dispatch", "exec", "hyprpaper"
])
else:
print(":: Wallpaper Engine disabled")
@@ -175,6 +209,7 @@ async def main():
await asyncio.gather(square_task, png_task)
state("finish", "Wallpaper procedure complete!", with_image)
async def png_image(wallpaper: str):
_from = (".jpg", "jpeg")
if not wallpaper.endswith(_from):
@@ -196,6 +231,7 @@ async def png_image(wallpaper: str):
else:
print(":: JPG successfully converted to PNG!")
async def square_image(wallpaper):
with_image = f"with image {wallpaper}"
state(None, "Creating square version...", with_image)
@@ -213,6 +249,7 @@ async def square_image(wallpaper):
else:
print(":: Square image created!")
if __name__ == "__main__":
acquire_lock()
try:
@@ -0,0 +1,247 @@
import os
import sys
import importlib.util
import argparse
import fcntl
import subprocess
import asyncio
import random as _random
import colorsys
lock_file_path = '/tmp/wallpaper.lock'
def acquire_lock():
global lock_file
lock_file = open(lock_file_path, 'w')
try:
fcntl.flock(lock_file, fcntl.LOCK_EX | fcntl.LOCK_NB)
lock_file.write(str(os.getpid()))
lock_file.flush()
except IOError:
print("Another instance of the script is already running.")
sys.exit(1)
def release_lock():
fcntl.flock(lock_file, fcntl.LOCK_UN)
lock_file.close()
os.remove(lock_file_path)
def hue_to_numeric_hex(hue):
hue = hue / 360.0
rgb = colorsys.hls_to_rgb(hue, 0.5, 1.0)
hex_color_str = '#{:02x}{:02x}{:02x}'.format(int(rgb[0] * 255), int(rgb[1] * 255), int(rgb[2] * 255))
numeric_hex_color = int(hex_color_str.lstrip('#'), 16)
return numeric_hex_color
parser = argparse.ArgumentParser()
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument('-I', '--image', type=str, help="Image")
group.add_argument('-P', '--prev', help="Use last used wallpaper for color generation", action='store_true')
group.add_argument('-R', '--random', help="Random image from folder", action='store_true')
parser.add_argument('-n', '--notify', help="Send notifications", action='store_true')
parser.add_argument('--status', type=str, help="Status file", default="/tmp/wallpaper.status")
args = parser.parse_args()
random = args.random
prev = args.prev
image = args.image
notify = args.notify
status = args.status
HOME = os.path.expanduser("~")
module_path = f'{HOME}/dotfiles/material-colors'
sys.path.append(module_path)
module_name = 'generate'
file_path = f'{module_path}/{module_name}.py'
spec = importlib.util.spec_from_file_location(module_name, file_path)
GENERATOR = importlib.util.module_from_spec(spec) # type: ignore
spec.loader.exec_module(GENERATOR) # type: ignore
cache_file = f"{HOME}/.cache/current_wallpaper"
square = f"{HOME}/.cache/square_wallpaper.png"
png = f"{HOME}/.cache/current_wallpaper.png"
color_scheme_file = f"{HOME}/dotfiles/.settings/color-scheme"
custom_color_file = f"{HOME}/dotfiles/.settings/custom-color"
generation_scheme_file = f"{HOME}/dotfiles/.settings/generation-scheme"
swww_animation_file = f"{HOME}/dotfiles/.settings/swww-anim"
def current_state(str: str):
with open(status, 'w') as f:
f.write(str)
def send_notify(label: str, desc: str):
if not notify:
return
subprocess.run(["notify-send", label, desc])
def state(name: str | None, label: str | None, desc: str | None):
if name is not None:
current_state(name)
if label is not None:
send_notify(label, desc or "")
def join(*args):
return os.path.join(*args)
async def main():
global color_scheme, custom_color
state("init", None, None)
with open(color_scheme_file) as f:
color_scheme = f.read().strip()
with open(custom_color_file) as f:
custom_color = f.read().strip()
with open(generation_scheme_file) as f:
generation_scheme = f.read().strip()
with open(swww_animation_file) as f:
swww_animation = f.read().strip()
new_wallpaper = f"{HOME}/Pictures/wallpapers/1.jpg"
if random:
files = [f for f in os.listdir(f"{HOME}/Pictures/wallpapers") if f.endswith(('.png', '.jpg', '.jpeg'))]
if files:
new_wallpaper = join(f"{HOME}/Pictures/wallpapers", _random.choice(files))
elif prev:
try:
with open(cache_file) as f:
new_wallpaper = f.read().strip()
except FileNotFoundError:
...
elif image is not None:
new_wallpaper = os.path.abspath(image)
print(f":: Wallpaper {new_wallpaper}")
with open(cache_file, 'w') as f:
f.write(new_wallpaper)
with_image = f"with image {new_wallpaper}"
# -----------------------------------------------------
# Set the new wallpaper
# -----------------------------------------------------
transition_type = swww_animation
# transition_type = "outer"
# transition_type = "random"
wallpaper_engine = "swww" # Default wallpaper engine
state("changing", "Changing wallpaper...", with_image)
print(":: Changing wallpaper...")
if wallpaper_engine == "swww":
print(":: Using swww")
cursor_pos = subprocess.getoutput('hyprctl cursorpos')
subprocess.run([
'swww', 'img', new_wallpaper,
'--transition-bezier', '.43,1.19,1,.4',
'--transition-fps', '60',
'--transition-type', transition_type,
'--transition-duration', '0.7',
'--transition-pos', cursor_pos.replace(",",",")
])
else:
print(":: Wallpaper Engine disabled")
# -----------------------------------------------------
# Generate colors
# -----------------------------------------------------
state("colors", "Generating colors...", with_image)
print(":: Generate colors")
_starts_with = (lambda x: str(x).startswith("-"))
GENERATOR.main(
color_scheme, new_wallpaper,
(hue_to_numeric_hex(int(custom_color.lstrip("-")))
if _starts_with(custom_color) else (
int(custom_color.lstrip('#'), 16)
if custom_color != "none"
else None
)),
scheme=GENERATOR.schemes[generation_scheme]
)
# -----------------------------------------------------
# Square image
# -----------------------------------------------------
square_task = asyncio.create_task(square_image(new_wallpaper))
# -----------------------------------------------------
# Png image
# -----------------------------------------------------
png_task = asyncio.create_task(png_image(new_wallpaper))
state("tasks", None, None)
await asyncio.gather(square_task, png_task)
state("finish", "Wallpaper procedure complete!", with_image)
async def png_image(wallpaper: str):
_from = (".jpg", "jpeg")
if not wallpaper.endswith(_from):
cmd = f"cp -f {wallpaper} {png}"
else:
with_image = f"with image {wallpaper}"
state(None, "Converting jpg to png...", with_image)
print(":: Converting jpg to png...")
cmd = f"magick {wallpaper} {png}"
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
print(f":: Error while processing image: {stderr.decode()}")
else:
print(":: JPG successfully converted to PNG!")
async def square_image(wallpaper):
with_image = f"with image {wallpaper}"
state(None, "Creating square version...", with_image)
print(":: Creating square version")
cmd = f"magick {wallpaper} -gravity Center -extent 1:1 {square}"
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
if process.returncode != 0:
print(f":: Error while processing image: {stderr.decode()}")
else:
print(":: Square image created!")
if __name__ == "__main__":
acquire_lock()
try:
asyncio.run(main())
finally:
release_lock()