Commit 63adfc34 authored by phob1an's avatar phob1an 🎧
Browse files

restart the repo

parent 0e611460
#!/usr/bin/python3
"""Culla generates a desktop theme using colours
from the current wallpaper"""
import sys
import os
import subprocess
import time
import colorsys
from PIL import Image
import colorgram
#Template for our Plasma theme
plasma_colors = """[Colors:Window]
ForegroundNormal=bbb
BackgroundNormal=aaa
ForegroundNegative=212,84,0
[Colors:Selection]
BackgroundNormal=ddd
[Colors:Complimentary]
BackgroundNormal=255,0,0
ForegroundNormal=0,255,0
[Colors:Button]
ForegroundNormal=eee
BackgroundNormal=fff
DecorationFocus=ddd
DecorationHover=0,255,0
[Colors:View]
ForegroundNormal=bbb
BackgroundNormal=ccc
DecorationHover=ddd"""
def notify_user(message):
""" Simple notification to show something's happening """
icon_path = os.path.expanduser('~/.local/share/pixmaps/cullax.png')
icon = '--icon={}'.format(icon_path)
try:
subprocess.run(['notify-send',
icon,
'--expire-time=3000',
message])
except:
pass
def color_triplet(h, l, s):
r, g, b = colorsys.hls_to_rgb(h, l, s)
if r > 1.0:
r = 1.0
r = int(r * 255)
if g > 1.0:
g = 1.0
g = int(g * 255)
if b > 1.0:
r = 1.0
b = int(b * 255)
return ','.join([str(r), str(g), str(b)])
# ---- CullaX ----
# Try sending a notification to show we're working
notify_user("CullaX - Beautifying Desktop ;) ")
# Raise flag when finding correct session in plasmarc
flag = False
# Holder for current activity ID
activity = ""
try:
with open(os.path.expanduser(
'~/.config/plasma-org.kde.plasma.desktop-appletsrc')) as f:
plasmaconfig = f.readlines()
except:
sys.exit('Unable to find plasma config.')
try:
with open(os.path.expanduser('~/.config/kactivitymanagerdrc')) as f:
activityrc = f.readlines()
except:
print('Unable to find kactivity manager rc. Presuming only default activity.')
activityrc = None
flag = True # There is only default activity
# Retrieve current activity
if activityrc is not None:
a = [a for a in activityrc if 'current' in a]
a = a[0].split('=')
activity = a[1].rstrip()
# Flag if wallpaper is found
found = False
# Find current activity then grab next Image= key
for line in plasmaconfig:
if activity in line:
flag = True
if 'Image=' in line and flag:
found = True
break
if not found:
notify_user(
"""You need to set your own wallpaper\n\
before I can work."""
)
sys.exit("I didn't find your wallpaper. Have you set one yet?")
#tmp, wallpaper = line.split('//')
line = line[6:]
if line[0] == 'f':
line = line[7:]
wallpaper = line.strip()
if not os.path.exists(wallpaper):
notify_user("I can't your wallpaper."
.format(wallpaper))
sys.exit("I think the wallpaper is {0} but I can't find it."
.format(wallpaper))
# Resize and write to temp file - massive speedup
tmp_img = Image.open(wallpaper.rstrip())
tmp_img = tmp_img.resize((256, 256))
tmp_img_path = os.path.expanduser('~/.cullax.png')
tmp_img.save(tmp_img_path)
colors = colorgram.extract(tmp_img_path, 6)
sat = 0
hb,sb,lb = [ c/255.0 for c in colors[0].hsl ]
colors.sort(key=lambda c: c.hsl.s)
h,s,l = [ c/255.0 for c in colors[len(colors) - 1].hsl ]
# Cleanup temp file
os.remove(tmp_img_path)
# Remove hue for b/w images
if s < 0.011:
s = 0.0
h = 0.0
#l_midlight = (1.0 - l) / 4.0 + l
panel_background = color_triplet(hb, 0.15, 0.1)
panel_header = color_triplet(hb, 0.3, 0.2)
#button_foreground = color_triplet(h, 0.85, s)
foreground = "252,252,252"
#foreground = color_triplet(h, 0.98, 1)
button_foreground = "252,252,252"
highlight_color = color_triplet(h, 0.88, 1)
midlight = color_triplet(h, 0.5, 0.5)
print(panel_background)
# Write the colorscheme
plasma_colors = plasma_colors.replace('aaa', panel_background)
plasma_colors = plasma_colors.replace('bbb', foreground)
plasma_colors = plasma_colors.replace('ddd', highlight_color)
plasma_colors = plasma_colors.replace('eee', button_foreground)
plasma_colors = plasma_colors.replace('fff', midlight)
plasma_colors = plasma_colors.replace('ccc', panel_header)
try:
with open(os.path.expanduser(
'~/.local/share/plasma/desktoptheme/CullaX/colors'), 'w') as f:
f.write(plasma_colors)
except:
sys.exit("Unable to open Culla Plasma colors. Is it installed?")
# Call kwriteconfig5 to change Plasma theme
try:
subprocess.run(['kwriteconfig5', '--file=plasmarc',
'--group=Theme', '--key=name', 'Default'])
# Do this too quickly and Plasma won't reload
time.sleep(0.8)
subprocess.run(['kwriteconfig5', '--file=plasmarc',
'--group=Theme', '--key=name', 'CullaX'])
except IOError as e:
sys.exit(e)
# ---- Set Global Colours ----
try:
subprocess.run(['kwriteconfig5', '--file=kdeglobals',
'--group=Colors:Selection',
'--key=BackgroundNormal', midlight])
subprocess.run(['kwriteconfig5', '--file=kdeglobals',
'--group=Colors:View',
'--key=DecorationFocus',
midlight])
#subprocess.run(['kwriteconfig5', '--file=kdeglobals',
#'--group=WM',
#'--key=activeBackground',
#midlight_color])
#subprocess.run(['kwriteconfig5', '--file=kdeglobals',
#'--group=WM',
#'--key=activeForeground',
#foreground])
except IOError as e:
sys.exit(e)
#!/usr/bin/python3
"""Culla generates a desktop theme using colours
from the current wallpaper"""
import sys
import os
import subprocess
import time
import colorsys
#import dbus
from PIL import Image
import cv2
import numpy as np
from skimage import io
#Template for our Plasma theme
plasma_colors = """[Colors:Window]
ForegroundNormal=bbb
BackgroundNormal=aaa
[Colors:Selection]
BackgroundNormal=ddd
[Colors:Button]
ForegroundNormal=bbb
BackgroundNormal=ddd
DecorationFocus=ddd
DecorationHover=eee
[Colors:Compilmentary]
BackgroundNormal=224,4,4
ForegroundNormal=224,4,22
[Colors:View]
ForegroundNormal=bbb
BackgroundNormal=ccc
DecorationHover=ddd"""
# https://stackoverflow.com/questions/43111029/how-to-find-the-average-colour-of-an-image-in-python-with-opencv/43111221
def get_dominant_color(image):
img = io.imread(image)[:, :, :3]
pixels = np.float32(img.reshape(-1, 3))
n_colors = 6
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 200, .1)
flags = cv2.KMEANS_RANDOM_CENTERS
_, labels, palette = cv2.kmeans(pixels, n_colors, None, criteria, 10, flags)
_, counts = np.unique(labels, return_counts=True)
return palette[np.argmax(counts)]
def get_average(image):
""" Get the average of all pixels munged together"""
img = io.imread(image)[:, :, :3]
return img.mean(axis=0).mean(axis=0)
def notify_user(message):
""" Simple notification to show something's happening """
icon_path = os.path.expanduser('~/.local/share/pixmaps/cullax.png')
icon = '--icon={}'.format(icon_path)
try:
subprocess.run(['notify-send',
icon,
'--expire-time=3000',
message])
except:
pass
def color_triplet(h, l, s):
r, g, b = colorsys.hls_to_rgb(h, l, s)
if r > 1.0:
r = 1.0
r = int(r * 255)
if g > 1.0:
g = 1.0
g = int(g * 255)
if b > 1.0:
r = 1.0
b = int(b * 255)
return ','.join([str(r), str(g), str(b)])
#def aurorae(active):
#"""Open decoration template, substitue our colour
#then write decoration.svg"""
#try:
#with open(os.path.expanduser(
#'~/.local/share/aurorae/themes/CullaX/decoration-template.svg')) as f:
#auroraetemplate = f.read()
#except IOError:
#sys.exit("Unable to find Aurorae template.")
#r, g, b = active.split(',')
#hex_colour = f'#{int(r):02x}{int(g):02x}{int(b):02x}'
#auroraetemplate = auroraetemplate.replace('TEMPLAT', hex_colour)
##auroraetemplate = auroraetemplate.replace('TEMPLA2', '#f7f7f7')
#try:
#with open(os.path.expanduser(
#'~/.local/share/aurorae/themes/CullaX/decoration.svg'), 'w') as f:
#f.write(auroraetemplate)
#except IOError:
#sys.exit("Fatal. Unable to write aurorae decoration.")
#session_bus = dbus.SessionBus()
#if [k for k in session_bus.list_names() if 'KWin' in k]:
#proxy = session_bus.get_object('org.kde.KWin', '/KWin')
#subprocess.run(['kbuildsycoca5'], stderr=subprocess.DEVNULL)
#subprocess.run(['kwriteconfig5', '--file=kwinrc',
#'--group=org.kde.kdecoration2',
#'--key=theme', '__aurorae__svg__CullaX'])
#proxy.reconfigure()
#else:
#sys.exit('Unable to find KWin. Is it running?')
# ---- CullaX ----
engine = 0
if len(sys.argv) > 1:
print("PP")
engine = 1
# Try sending a notification to show we're working
notify_user("CullaX - Reticulating Splines")
# Raise flag when finding correct session in plasmarc
flag = False
# Holder for current activity ID
activity = ""
try:
with open(os.path.expanduser(
'~/.config/plasma-org.kde.plasma.desktop-appletsrc')) as f:
plasmaconfig = f.readlines()
except:
sys.exit('Unable to find plasma config.')
try:
with open(os.path.expanduser('~/.config/kactivitymanagerdrc')) as f:
activityrc = f.readlines()
except:
print('Unable to find kactivity manager rc. Presuming only default activity.')
activityrc = None
flag = True #There is only default activity
#Retrieve current activity
if activityrc is not None:
a = [a for a in activityrc if 'current' in a]
a = a[0].split('=')
activity = a[1].rstrip()
#Flag if wallpaper is found
found = False
#Find current activity then grab next Image= key
for line in plasmaconfig:
if activity in line:
flag = True
if 'Image=' in line and flag:
found = True
break
if not found:
notify_user(
"""You need to set your own wallpaper\n\
before I can work."""
)
sys.exit("I didn't find your wallpaper. Have you set one yet?")
#tmp, wallpaper = line.split('//')
line = line[6:]
if line[0] == 'f':
line = line[7:]
#print(line)
wallpaper = line.strip()
if not os.path.exists(wallpaper):
sys.exit("I think the wallpaper is {0} but I can't find it. Exiting."
.format(wallpaper))
# Resize to 256x256 - massive speedup
tmp_img = Image.open(wallpaper.rstrip())
tmp_img = tmp_img.resize((384, 384))
tmp_img_path = os.path.expanduser('~/.cullax.png')
tmp_img.save(tmp_img_path)
# Get dominant and average colors
dominant_color = get_dominant_color(tmp_img_path)
avg_color = get_average(tmp_img_path)
h_base, l_base, s_base = colorsys.rgb_to_hls(dominant_color[0]/255.0,
dominant_color[1]/255.0,
dominant_color[2]/255.0)
h_avg, l_avg, s_avg = colorsys.rgb_to_hls(avg_color[0]/255.0,
avg_color[1]/255.0,
avg_color[2]/255.0)
print("DOM scikit", h_base, l_base, s_base)
#print("AVG ", h_avg, l_avg, s_avg)
#print(dominant_color[0], dominant_color[1], dominant_color[2])
if engine == 1:
import colorgram
color_list = colorgram.extract(tmp_img_path, 6)
dominant_color = color_list[0]
print(dominant_color)
h_base, l_base, s_base = colorsys.rgb_to_hls(dominant_color.rgb[0]/255.0,
dominant_color.rgb[1]/255.0,
dominant_color.rgb[2]/255.0)
print("DOM colorgram", h_base, l_base, s_base)
pil_image = tmp_img.resize((1,1))
print("PIL ", pil_image.getpixel((0,0)))
# Cleanup temp image
os.remove(tmp_img_path)
#sys.exit()
# Lighten if too dark
l_midlight = l_base
if l_base < 0.3:
l_midlight = (l_base + 0.3) / 2.0
if l_base > 0.7:
l_midlight = (l_base + 0.7) / 2.0
# Remove hue for b/w images
if s_base < 0.011:
s_base = 0.0
h_base = 0.0
# Flip hues for light images
if l_avg > 0.67:
panel_background = color_triplet(h_base, 0.98, s_base)
foreground = color_triplet(h_base, 0.25, 0.05)
midlight_color = color_triplet(h_base, l_midlight, s_base)
highlight_color = color_triplet(h_base, 0.6, 0.5)
focus_decoration_color = color_triplet(h_base, 0.7, 0.4)
else:
panel_background = color_triplet(h_base, 0.05, s_base / 2)
highlight_color = color_triplet(h_base, 0.65, s_base)
midlight_color = color_triplet(h_base, l_base, s_base)
foreground = color_triplet(h_base, 0.98, 0.95)
# Write the colorscheme
plasma_colors = plasma_colors.replace('aaa', panel_background)
plasma_colors = plasma_colors.replace('bbb', foreground)
plasma_colors = plasma_colors.replace('ccc', midlight_color)
plasma_colors = plasma_colors.replace('ddd', midlight_color)
plasma_colors = plasma_colors.replace('eee', highlight_color)
try:
with open(os.path.expanduser(
'~/.local/share/plasma/desktoptheme/CullaX/colors'), 'w') as f:
f.write(plasma_colors)
except:
sys.exit("Unable to open Culla Plasma colors. Is it installed?")
# Call kwriteconfig5 to change Plasma theme
try:
subprocess.run(['kwriteconfig5', '--file=plasmarc',
'--group=Theme', '--key=name', 'Default'])
#Do this too quickly and Plasma won't change
time.sleep(0.5)
subprocess.run(['kwriteconfig5', '--file=plasmarc',
'--group=Theme', '--key=name', 'CullaX'])
except IOError as e:
sys.exit(e)
# ---- Set Global Colours ----
try:
subprocess.run(['kwriteconfig5', '--file=kdeglobals',
'--group=Colors:Selection',
'--key=BackgroundNormal', midlight_color])
subprocess.run(['kwriteconfig5', '--file=kdeglobals',
'--group=Colors:View',
'--key=DecorationFocus',
midlight_color])
subprocess.run(['kwriteconfig5', '--file=kdeglobals',
'--group=WM',
'--key=activeBackground',
midlight_color])
#subprocess.run(['kwriteconfig5', '--file=kdeglobals',
#'--group=WM',
#'--key=activeForeground',
#foreground])
except IOError as e:
sys.exit(e)
## If Culla window dec is active, update it
#aur_theme = subprocess.run(['kreadconfig5', '--file=kwinrc',
#'--group=org.kde.kdecoration2', '--key=theme'], \
#stdout=subprocess.PIPE)
#if b'CullaX' in aur_theme.stdout:
#aurorae(focus_decoration_color)
[Buildset]
BuildItems=@Variant(\x00\x00\x00\t\x00\x00\x00\x00\x01\x00\x00\x00\x0b\x00\x00\x00\x00\x01\x00\x00\x00\x0c\x00C\x00u\x00l\x00l\x00a\x00X)
[Project]
VersionControlSupport=
[Project]
Manager=KDevGenericManager
Name=CullaX
'''
Documentation, License etc.
@package CullaX
'''
This diff is collapsed.
## CullaX
CullaX will generate a dark Plasma theme based on your current wallpaper. It uses [colorgram.py](https://github.com/obskyr/colorgram.py)
### Installation
Firstly, install colorgram.py.
```
sudo pip install colorgram.py
```
To install, just run ```./install.sh``` which will install the Plasma theme, a menu entry and the CullaX script. The menu entry should appear under the Settings submenu.
*Note: you need to set your own wallpaper before using CullaX.*
If there's any interest, I'll add a light theme, a window decoration and maybe a settings panel.
\ No newline at end of file
[Desktop Entry]
Type=Application
Version=1.0
Name=CullaX
GenericName=CullaX
NoDisplay=false
Comment=Colourise the desktop
Exec=~/.local/bin/CullaX.py
Icon=cullax
Terminal=false
MimeType=
Categories=Settings;DesktopSettings;
Encoding=UTF-8
StartupNotify=False
cullax.png

1.19 KB

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
xmlns:dc="http://purl.org/dc/elements/1.1/"
xmlns:cc="http://creativecommons.org/ns#"
xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:svg="http://www.w3.org/2000/svg"
xmlns="http://www.w3.org/2000/svg"
xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
version="1.1"
viewBox="0 0 68 68"
width="68"
height="68"
id="svg4"
sodipodi:docname="cullax.svg"
inkscape:version="0.92.4 (5da689c313, 2019-01-14)">
<metadata
id="metadata10">
<rdf:RDF>
<cc:Work
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
</metadata>
<defs
id="defs8">
<inkscape:perspective
sodipodi:type="inkscape:persp3d"
inkscape:vp_x="0 : 128 : 1"
inkscape:vp_y="0 : 1000 : 0"
inkscape:vp_z="256 : 128 : 1"
inkscape:persp3d-origin="128 : 85.333333 : 1"
id="perspective827" />
</defs>
<sodipodi:namedview