feat: modernize color-tool with multiple formats, HSL support, and embedded picker

- Added --output flag supporting hex, rgb, hsl, rgba, hsla, hexa, and 'all' formats
- Implemented HSL/HSLA conversion using internal Python logic
- Added --[no-] prefix support for all toggleable flags (json, name, swatch, copy, notify, pick)
- Embedded KDE Plasma color picker Python script within the main bash script for portability
- Refactored argument parsing to implement a robust priority system (CLI > Desktop Config > Default Config)
- Improved validation to catch invalid output formats before triggering the color picker
- Updated installation logic to generate all necessary components and sample configuration
- Fixed swatch formatting when outputting JSON
- Refined desktop mode behavior and configurability
This commit is contained in:
2026-04-27 22:40:55 -04:00
parent 6c2c42d3e5
commit 5c87e382de
3 changed files with 297 additions and 221 deletions
+3 -3
View File
@@ -2,6 +2,6 @@
.remember .remember
.gemini* .gemini*
.claude* .claude*
CLAUDE.md #CLAUDE.md
GEMINI.md #GEMINI.md
AGENTS.md #AGENTS.md
+294 -198
View File
@@ -7,29 +7,42 @@ set -euo pipefail
# Resolve the real directory of this script so we can find bundled helpers # Resolve the real directory of this script so we can find bundled helpers
SCRIPT_DIR="$(dirname "$(readlink -f "$0")")" SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
PICKER_SCRIPT="$SCRIPT_DIR/wl-colorpicker-plasma.py"
CONFIG_FILE="$HOME/.config/color-tool/config.toml" CONFIG_FILE="$HOME/.config/color-tool/config.toml"
# ── Mode flags (toggled by CLI arguments or config file) ────────────────────── # ── Initial Defaults ──────────────────────────────────────────────────────────
json_mode=0 # --json: output as JSON # Hardcoded base defaults
alpha_mode=0 # --alpha: include alpha channel (8-digit hex) json_mode=0
name_mode=0 # --name: fetch color name via thecolorapi.com alpha_mode=0
copy_mode=0 # --copy: copy result to clipboard name_mode=0
desktop_mode=0 # --desktop: silent GUI mode (implies pick + copy + notify) copy_mode=0
notify_mode=0 # internal: show desktop notification after copy desktop_mode=0
config_pick=0 # config: auto-launch picker when invoked with no arguments notify_mode=0
swatch_mode=0
config_pick=0
output_formats="hex"
# Desktop-mode defaults (overridden by [desktop] config section) # Desktop-specific defaults (initially same as base, can be overridden by config)
desktop_json=0 desktop_json=0
desktop_alpha=0 desktop_alpha=0
desktop_name=0 desktop_name=0
desktop_notify=1 desktop_notify=1
desktop_copy=1
desktop_output="hex"
# ── Config ──────────────────────────────────────────────────────────────────── # Track which settings were explicitly set via CLI flags to ensure they override config
cli_json=""
cli_alpha=""
cli_name=""
cli_copy=""
cli_notify=""
cli_swatch=""
cli_pick=""
cli_output=""
# ── Config Loader ─────────────────────────────────────────────────────────────
# Parse ~/.config/color-tool/config.toml and apply [defaults] and [desktop] values. # Parse ~/.config/color-tool/config.toml and apply [defaults] and [desktop] values.
# Only boolean true/false keys are supported; unknown keys are silently ignored.
load_config() { load_config() {
[[ ! -f "$CONFIG_FILE" ]] && return 0 [[ ! -f "$CONFIG_FILE" ]] && return 0
@@ -44,21 +57,26 @@ load_config() {
continue continue
fi fi
# key = value — use if/then/fi so each branch always exits 0 (safe under set -e) # key = value
if [[ "$line" =~ ^[[:space:]]*([A-Za-z_]+)[[:space:]]*=[[:space:]]*([^[:space:]]+) ]]; then if [[ "$line" =~ ^[[:space:]]*([A-Za-z_]+)[[:space:]]*=[[:space:]]*([^[:space:]]+) ]]; then
key="${BASH_REMATCH[1]}" key="${BASH_REMATCH[1]}"
val="${BASH_REMATCH[2],,}" val="${BASH_REMATCH[2],,}"
val="${val#\"}" ; val="${val%\"}" val="${val#\"}" ; val="${val%\"}"
case "$section:$key" in case "$section:$key" in
defaults:json) if [[ "$val" == "true" ]]; then json_mode=1; fi ;; defaults:json) [[ "$val" == "true" ]] && json_mode=1 || json_mode=0 ;;
defaults:alpha) if [[ "$val" == "true" ]]; then alpha_mode=1; fi ;; defaults:alpha) [[ "$val" == "true" ]] && alpha_mode=1 || alpha_mode=0 ;;
defaults:name) if [[ "$val" == "true" ]]; then name_mode=1; fi ;; defaults:name) [[ "$val" == "true" ]] && name_mode=1 || name_mode=0 ;;
defaults:copy) if [[ "$val" == "true" ]]; then copy_mode=1; fi ;; defaults:copy) [[ "$val" == "true" ]] && copy_mode=1 || copy_mode=0 ;;
defaults:pick) if [[ "$val" == "true" ]]; then config_pick=1; fi ;; defaults:pick) [[ "$val" == "true" ]] && config_pick=1 || config_pick=0 ;;
desktop:json) if [[ "$val" == "true" ]]; then desktop_json=1; else desktop_json=0; fi ;; defaults:notify) [[ "$val" == "true" ]] && notify_mode=1 || notify_mode=0 ;;
desktop:alpha) if [[ "$val" == "true" ]]; then desktop_alpha=1; else desktop_alpha=0; fi ;; defaults:swatch) [[ "$val" == "true" ]] && swatch_mode=1 || swatch_mode=0 ;;
desktop:name) if [[ "$val" == "true" ]]; then desktop_name=1; else desktop_name=0; fi ;; defaults:output) output_formats="$val" ;;
desktop:notify) if [[ "$val" == "true" ]]; then desktop_notify=1; else desktop_notify=0; fi ;; desktop:json) [[ "$val" == "true" ]] && desktop_json=1 || desktop_json=0 ;;
desktop:alpha) [[ "$val" == "true" ]] && desktop_alpha=1 || desktop_alpha=0 ;;
desktop:name) [[ "$val" == "true" ]] && desktop_name=1 || desktop_name=0 ;;
desktop:notify) [[ "$val" == "true" ]] && desktop_notify=1 || desktop_notify=0 ;;
desktop:copy) [[ "$val" == "true" ]] && desktop_copy=1 || desktop_copy=0 ;;
desktop:output) desktop_output="$val" ;;
esac esac
fi fi
done < "$CONFIG_FILE" done < "$CONFIG_FILE"
@@ -74,44 +92,37 @@ show_help() {
local yellow='\033[33m' local yellow='\033[33m'
local mag='\033[35m' local mag='\033[35m'
# Render an inline color swatch for a hex code
swatch() {
local h="${1#\#}"
printf "\033[48;2;%d;%d;%dm \033[0m" $((16#${h:0:2})) $((16#${h:2:2})) $((16#${h:4:2}))
}
printf "\n" printf "\n"
# Title: "color" in a rainbow gradient, "-tool" in bold # Title: "color" in a rainbow gradient, "-tool" in bold
printf " ${bold}\033[38;2;255;80;80mc\033[38;2;255;160;0mo\033[38;2;220;210;0ml\033[38;2;80;200;80mo\033[38;2;80;160;255mr${reset}${bold}-tool${reset}" printf " ${bold}\033[38;2;255;80;80mc\033[38;2;255;160;0mo\033[38;2;220;210;0ml\033[38;2;80;200;80mo\033[38;2;80;160;255mr${reset}${bold}-tool${reset}"
printf " ${dim}— pick, convert, and format colors${reset}\n\n" printf " ${dim}— pick, convert, and format colors${reset}\n\n"
printf " ${bold}${yellow}Usage${reset} ${cyan}${0##*/}${reset} ${dim}[OPTIONS]${reset} [HEX_COLOR ...]\n\n" printf " ${bold}${yellow}Usage${reset} ${cyan}${0##*/}${reset} ${dim}[OPTIONS]${reset} [COLOR ...]\n\n"
printf " ${bold}${yellow}Options${reset}\n" printf " ${bold}${yellow}Options${reset}\n"
printf " ${bold}${cyan}--pick${reset} Open the KDE Plasma color picker ${dim}(requires KDE + Wayland)${reset}\n" printf " ${bold}${cyan}--[no-]pick${reset} Open the KDE Plasma color picker ${dim}(requires KDE + Wayland)${reset}\n"
printf " ${bold}${cyan}--alpha${reset} Interpret 8-digit hex codes ${dim}(RRGGBBAA)${reset} and include alpha channel\n" printf " ${bold}${cyan}--output${reset} ${dim}FMT${reset} Format(s) to output: ${cyan}hex, rgb, hsl, rgba, hsla, hexa, all${reset} ${dim}(comma-separated)${reset}\n"
printf " ${bold}${cyan}--json${reset} Output in JSON format\n" printf " ${bold}${cyan}--[no-]json${reset} Output as a JSON table of selected formats\n"
printf " ${bold}${cyan}--name${reset} Fetch nearest color name from thecolorapi.com ${dim}(requires curl, jq)${reset}\n" printf " ${bold}${cyan}--[no-]name${reset} Fetch nearest color name from thecolorapi.com ${dim}(requires curl, jq)${reset}\n"
printf " ${bold}${cyan}--copy${reset} Copy result to clipboard ${dim}(wl-copy preferred, xclip as fallback)${reset}\n" printf " ${bold}${cyan}--[no-]swatch${reset} Include a color swatch in the terminal output\n"
printf " ${bold}${cyan}--[no-]copy${reset} Copy result to clipboard ${dim}(wl-copy preferred, xclip as fallback)${reset}\n"
printf " ${bold}${cyan}--[no-]notify${reset} Show desktop notification ${dim}(on by default in --desktop)${reset}\n"
printf " ${bold}${cyan}--desktop${reset} GUI mode: pick → copy → notify ${dim}(for app menu / .desktop launcher)${reset}\n" printf " ${bold}${cyan}--desktop${reset} GUI mode: pick → copy → notify ${dim}(for app menu / .desktop launcher)${reset}\n"
printf " ${bold}${cyan}--install${reset} Install to ~/.local/share/color-tool/ and symlink into ~/.local/bin/\n" printf " ${bold}${cyan}--install${reset} Install to ~/.local/share/color-tool/ and symlink into ~/.local/bin/\n"
printf " ${bold}${cyan}--help${reset}, ${bold}${cyan}-h${reset} Show this help message\n\n" printf " ${bold}${cyan}--help${reset}, ${bold}${cyan}-h${reset} Show this help message\n\n"
printf " ${bold}${yellow}Examples${reset}\n" printf " ${bold}${yellow}Examples${reset}\n"
printf " ${cyan}${0##*/}${reset} ${mag}\"#534145\"${reset} $(swatch "#534145") ${mag}\"#433f43\"${reset} $(swatch "#433f43")\n" printf " ${cyan}${0##*/}${reset} ${mag}\"#534145\"${reset} --swatch\n"
printf " ${dim}echo${reset} ${mag}\"#123456\"${reset} $(swatch "#123456") ${dim}|${reset} ${cyan}${0##*/}${reset}\n" printf " ${cyan}${0##*/}${reset} --pick --output rgb,hsl --json\n"
printf " ${cyan}${0##*/}${reset} ${bold}${cyan}--pick${reset} ${bold}${cyan}--json${reset} ${bold}${cyan}--copy${reset}\n" printf " ${cyan}${0##*/}${reset} \"rgb(255, 100, 0)\" --output hex,hsla\n\n"
printf " ${cyan}${0##*/}${reset} ${bold}${cyan}--pick${reset} ${bold}${cyan}--alpha${reset} ${bold}${cyan}--json${reset} ${bold}${cyan}--name${reset} ${bold}${cyan}--copy${reset}\n\n"
printf " ${bold}${yellow}Config${reset} ${dim}~/.config/color-tool/config.toml${reset}\n" printf " ${bold}${yellow}Config${reset} ${dim}~/.config/color-tool/config.toml${reset}\n"
printf " ${dim}[defaults]${reset} keys: ${cyan}json alpha name copy pick${reset}\n" printf " ${dim}[defaults]${reset} keys: ${cyan}output json swatch name copy pick notify${reset}\n"
printf " ${dim}[desktop]${reset} keys: ${cyan}json alpha name notify${reset} ${dim}(copy + pick always on)${reset}\n\n" printf " ${dim}[desktop]${reset} keys: ${cyan}output json name notify copy${reset} ${dim}(pick always on)${reset}\n\n"
} }
# ── Environment detection ───────────────────────────────────────────────────── # ── Environment detection ─────────────────────────────────────────────────────
# Confirm the session is KDE Plasma on Wayland before invoking the color picker.
# KWin's ColorPicker DBus service is only present in this specific environment.
check_kde_wayland() { check_kde_wayland() {
if [[ -z "${WAYLAND_DISPLAY:-}" ]]; then if [[ -z "${WAYLAND_DISPLAY:-}" ]]; then
echo "Error: color picker requires a Wayland session (WAYLAND_DISPLAY is not set)" >&2 echo "Error: color picker requires a Wayland session (WAYLAND_DISPLAY is not set)" >&2
@@ -124,11 +135,8 @@ check_kde_wayland() {
fi fi
} }
# ── Clipboard ───────────────────────────────────────────────────────────────── # ── Clipboard & Notifications ─────────────────────────────────────────────────
# Write text to the system clipboard.
# Prefers wl-copy (native Wayland); falls back to xclip (X11, often Wayland-bridged).
# Prints a warning and exits non-zero if neither tool is available.
copy_to_clipboard() { copy_to_clipboard() {
local text="$1" local text="$1"
if command -v wl-copy &>/dev/null; then if command -v wl-copy &>/dev/null; then
@@ -142,42 +150,68 @@ copy_to_clipboard() {
fi fi
} }
# ── Color picker ──────────────────────────────────────────────────────────────
# Launch the bundled KDE Plasma color picker and echo the selected hex color.
# Validates the environment before invoking the Python/Qt DBus helper.
run_color_picker() {
if [[ ! -f "$PICKER_SCRIPT" ]]; then
echo "Error: picker script not found: $PICKER_SCRIPT" >&2
return 1
fi
check_kde_wayland || return 1
python3 "$PICKER_SCRIPT"
}
# ── Desktop mode ─────────────────────────────────────────────────────────────
# Apply [desktop] config values as active mode flags; always enable pick and copy.
apply_desktop_config() {
json_mode=$desktop_json
alpha_mode=$desktop_alpha
name_mode=$desktop_name
notify_mode=$desktop_notify
copy_mode=1
config_pick=1
}
# Show a desktop notification with the copied value (non-fatal if notify-send absent).
notify_result() { notify_result() {
local value="$1" local value="$1"
command -v notify-send &>/dev/null || return 0 command -v notify-send &>/dev/null || return 0
notify-send -i "color-picker" "color-tool" "Copied to clipboard: $value" || true notify-send -i "color-picker" "color-tool" "$value" || true
} }
# ── PATH suggestion ─────────────────────────────────────────────────────────── # ── Color picker ──────────────────────────────────────────────────────────────
# Generate the internal Python helper for KDE Plasma color picking
generate_picker_script() {
local target="$1"
cat > "$target" <<'EOF'
#!/usr/bin/python3
from PyQt6.QtDBus import QDBusConnection, QDBusMessage, QDBusPendingReply, QDBusPendingCallWatcher
from PyQt6.QtCore import QCoreApplication
from PyQt6.QtGui import QColor
import sys
def colorPicked():
reply = QDBusPendingReply(call)
if reply.isError():
print(reply.error().message(), file=sys.stderr)
else:
print(QColor(reply.argumentAt(0)[0]).name())
app = QCoreApplication(sys.argv)
msg = QDBusMessage.createMethodCall("org.kde.KWin", "/ColorPicker", "org.kde.kwin.ColorPicker", "pick")
call = QDBusConnection.sessionBus().asyncCall(msg)
watcher = QDBusPendingCallWatcher(call, app)
watcher.finished.connect(colorPicked)
watcher.waitForFinished()
EOF
chmod +x "$target"
}
run_color_picker() {
check_kde_wayland || return 1
local picker_path="$SCRIPT_DIR/wl-colorpicker-plasma.py"
local cleanup=0
if [[ ! -f "$picker_path" ]]; then
picker_path=$(mktemp /tmp/wl-colorpicker-XXXXXX.py)
generate_picker_script "$picker_path"
cleanup=1
fi
local picked
picked=$(python3 "$picker_path")
local exit_code=$?
[[ $cleanup -eq 1 ]] && rm -f "$picker_path"
if [[ $exit_code -eq 0 ]]; then
echo "$picked"
else
return 1
fi
}
# ── Installation Helpers ──────────────────────────────────────────────────────
# Print the appropriate "add to PATH" instruction for the user's current shell.
# Detects fish via $SHELL or the parent process; falls back to showing both syntaxes.
suggest_path_add() { suggest_path_add() {
local bin_dir="$1" is_fish=0 local bin_dir="$1" is_fish=0
[[ "${SHELL:-}" == */fish ]] && is_fish=1 [[ "${SHELL:-}" == */fish ]] && is_fish=1
@@ -194,10 +228,6 @@ suggest_path_add() {
fi fi
} }
# ── Installation ──────────────────────────────────────────────────────────────
# Copy the script and helper into ~/.local/share/color-tool/ and symlink only
# the main binary into ~/.local/bin/. The picker script stays out of PATH.
do_install() { do_install() {
local data_dir="$HOME/.local/share/color-tool" local data_dir="$HOME/.local/share/color-tool"
local bin_dir="$HOME/.local/bin" local bin_dir="$HOME/.local/bin"
@@ -205,22 +235,12 @@ do_install() {
local src_script local src_script
src_script="$(readlink -f "$0")" src_script="$(readlink -f "$0")"
if [[ ! -f "$PICKER_SCRIPT" ]]; then
echo "Error: helper script not found: $PICKER_SCRIPT" >&2
echo " Run --install from the directory containing wl-colorpicker-plasma.py" >&2
exit 1
fi
mkdir -p "$data_dir" "$bin_dir" mkdir -p "$data_dir" "$bin_dir"
cp "$src_script" "$data_dir/color-tool" cp "$src_script" "$data_dir/color-tool"
chmod +x "$data_dir/color-tool" chmod +x "$data_dir/color-tool"
cp "$PICKER_SCRIPT" "$data_dir/wl-colorpicker-plasma.py" generate_picker_script "$data_dir/wl-colorpicker-plasma.py"
# -f replaces any existing symlink or stale file without prompting
ln -sf "$data_dir/color-tool" "$bin_link" ln -sf "$data_dir/color-tool" "$bin_link"
# Seed a sample config only if one doesn't already exist (preserve user edits on reinstall)
local config_dir="$HOME/.config/color-tool" local config_dir="$HOME/.config/color-tool"
local config_file="$config_dir/config.toml" local config_file="$config_dir/config.toml"
mkdir -p "$config_dir" mkdir -p "$config_dir"
@@ -231,17 +251,22 @@ do_install() {
[defaults] [defaults]
# Set any option to true to enable it by default when using the terminal # Set any option to true to enable it by default when using the terminal
json = false # output in JSON format output = "hex" # default output format(s): hex, rgb, hsl, rgba, hsla, hexa, all
alpha = false # include alpha channel (8-digit hex) json = false # output in JSON format
name = false # fetch color name from thecolorapi.com alpha = false # include alpha channel (8-digit hex)
copy = false # copy result to clipboard swatch = false # show color swatch in terminal
pick = false # auto-launch color picker when invoked with no arguments name = false # fetch color name from thecolorapi.com
copy = false # copy result to clipboard
pick = false # auto-launch color picker when invoked with no arguments
notify = false # show desktop notification
[desktop] [desktop]
# Defaults for --desktop mode (launched from the app menu; copy is always enabled) # Defaults for --desktop mode (launched from the app menu; copy is always enabled by default)
json = false # copy JSON format instead of hex output = "hex" # format to copy
json = false # copy JSON format instead of plain text
alpha = false # include alpha channel alpha = false # include alpha channel
name = false # fetch color name (requires network) name = false # fetch color name (requires network)
copy = true # copy result to clipboard
notify = true # show desktop notification with the copied value notify = true # show desktop notification with the copied value
EOF EOF
printf " config %s (sample created)\n" "$config_file" printf " config %s (sample created)\n" "$config_file"
@@ -249,21 +274,6 @@ EOF
printf " config %s\n" "$config_file" printf " config %s\n" "$config_file"
fi fi
generate_desktop_file
printf "Installed:\n"
printf " data %s/\n" "$data_dir"
printf " bin %s -> %s\n" "$bin_link" "$data_dir/color-tool"
# Warn when the bin dir is not yet on PATH so the user knows what to add
if [[ ":$PATH:" != *":$bin_dir:"* ]]; then
printf "\nNote: %s is not in your PATH.\n" "$bin_dir"
suggest_path_add "$bin_dir"
fi
}
# Write a .desktop entry so color-tool appears in the app menu.
generate_desktop_file() {
local app_dir="$HOME/.local/share/applications" local app_dir="$HOME/.local/share/applications"
local desktop_file="$app_dir/color-tool.desktop" local desktop_file="$app_dir/color-tool.desktop"
local bin_path="$HOME/.local/bin/color-tool" local bin_path="$HOME/.local/bin/color-tool"
@@ -282,127 +292,213 @@ Terminal=false
NoDisplay=false NoDisplay=false
EOF EOF
printf " app %s\n" "$desktop_file" printf " app %s\n" "$desktop_file"
printf "Installed:\n"
printf " data %s/\n" "$data_dir"
printf " bin %s -> %s\n" "$bin_link" "$data_dir/color-tool"
if [[ ":$PATH:" != *":$bin_dir:"* ]]; then
printf "\nNote: %s is not in your PATH.\n" "$bin_dir"
suggest_path_add "$bin_dir"
fi
} }
# ── Color conversion ────────────────────────────────────────────────────────── # ── Color conversion ──────────────────────────────────────────────────────────
# Convert a hex color to RGB/RGBA and print the result. get_all_formats() {
# Also copies a clean (no ANSI) value to clipboard when copy_mode is enabled. local input="$1"
hex_to_rgba() { python3 -c "
local hex="$1" import colorsys, json, sys, re
local clean_hex="${hex#\#}"
# Accept 6-digit (#RRGGBB) or 8-digit (#RRGGBBAA); pad 6-digit with full opacity def parse_input(val):
if [[ "$clean_hex" =~ ^[0-9A-Fa-f]{6}$ ]]; then val = val.strip().lower()
clean_hex="${clean_hex}FF" hex_match = re.match(r'^#?([0-9a-f]{3}|[0-9a-f]{6}|[0-9a-f]{8})$', val)
elif [[ "$clean_hex" =~ ^[0-9A-Fa-f]{8}$ ]]; then if hex_match:
: # already RRGGBBAA h = hex_match.group(1)
else if len(h) == 3: h = ''.join([c*2 for c in h])
echo "Invalid hex color: $hex" >&2 if len(h) == 6: h += 'ff'
return 1 return int(h[0:2], 16), int(h[2:4], 16), int(h[4:6], 16), int(h[6:8], 16)
fi rgba_match = re.match(r'^rgba?\(?(\d+),\s*(\d+),\s*(\d+)(?:,\s*([\d.]+))?\)?$', val)
if rgba_match:
r, g, b = map(int, rgba_match.groups()[:3])
r, g, b = max(0, min(255, r)), max(0, min(255, g)), max(0, min(255, b))
a = float(rgba_match.group(4)) if rgba_match.group(4) else 1.0
return r, g, b, int(max(0, min(1, a)) * 255)
hsla_match = re.match(r'^hsla?\(?(\d+),\s*(\d+)%?,\s*(\d+)%?(?:,\s*([\d.]+))?\)?$', val)
if hsla_match:
h, s, l = map(int, hsla_match.groups()[:3])
h, s, l = h % 360, max(0, min(100, s)), max(0, min(100, l))
a = float(hsla_match.group(4)) if hsla_match.group(4) else 1.0
r, g, b = colorsys.hls_to_rgb(h/360.0, l/100.0, s/100.0)
return int(r*255), int(g*255), int(b*255), int(max(0, min(1, a)) * 255)
return None
local r=$((16#${clean_hex:0:2})) res = parse_input('''$input''')
local g=$((16#${clean_hex:2:2})) if not res: sys.exit(1)
local b=$((16#${clean_hex:4:2})) r, g, b, a = res
local a=$((16#${clean_hex:6:2})) h, l, s = colorsys.rgb_to_hls(r/255.0, g/255.0, b/255.0)
local name="" clip_value="" formats = {
'hex': f'#{r:02x}{g:02x}{b:02x}',
'hexa': f'#{r:02x}{g:02x}{b:02x}{a:02x}',
'rgb': f'rgb({r}, {g}, {b})',
'rgba': f'rgba({r}, {g}, {b}, {round(a/255.0, 2)})',
'hsl': f'hsl({round(h*360)}, {round(s*100)}%, {round(l*100)}%)',
'hsla': f'hsla({round(h*360)}, {round(s*100)}%, {round(l*100)}%, {round(a/255.0, 2)})',
'_raw': {'r': r, 'g': g, 'b': b, 'a': a}
}
print(json.dumps(formats))
"
}
# Optionally resolve a human-readable name via the public thecolorapi.com API validate_output_formats() {
local formats="$1"
local valid_fmts=("hex" "hexa" "rgb" "rgba" "hsl" "hsla")
IFS=',' read -ra ADDR <<< "$formats"
for fmt in "${ADDR[@]}"; do
[[ "$fmt" == "all" ]] && continue
local is_valid=0
for v in "${valid_fmts[@]}"; do [[ "$fmt" == "$v" ]] && is_valid=1 && break; done
if [[ $is_valid -eq 0 ]]; then
echo "Error: Invalid output format: $fmt" >&2
echo "Valid formats: ${valid_fmts[*]}, all" >&2
return 1
fi
done
return 0
}
process_color() {
local input="$1"
local formats_json
formats_json=$(get_all_formats "$input") || { echo "Error: Invalid color: $input" >&2; return 1; }
local name=""
if [[ $name_mode -eq 1 ]]; then if [[ $name_mode -eq 1 ]]; then
name=$(curl -s "https://www.thecolorapi.com/id?hex=${clean_hex:0:6}" | jq -r '.name.value // empty') local hex_for_api
hex_for_api=$(echo "$formats_json" | jq -r '.hex' | tr -d '#')
name=$(curl -s "https://www.thecolorapi.com/id?hex=$hex_for_api" | jq -r '.name.value // empty')
fi fi
# Build clip_value (always; desktop mode needs it even without terminal output) local selected_fmts=()
local valid_fmts=("hex" "hexa" "rgb" "rgba" "hsl" "hsla")
IFS=',' read -ra ADDR <<< "$output_formats"
for fmt in "${ADDR[@]}"; do
if [[ "$fmt" == "all" ]]; then
selected_fmts=("${valid_fmts[@]}")
break
else
selected_fmts+=("$fmt")
fi
done
local display_parts=()
local json_obj="{}"
for fmt in "${selected_fmts[@]}"; do
local val
val=$(echo "$formats_json" | jq -r ".$fmt // empty")
if [[ -n "$val" ]]; then
display_parts+=("$val")
json_obj=$(echo "$json_obj" | jq --arg k "$fmt" --arg v "$val" '. + {($k): $v}')
fi
done
[[ -n "$name" ]] && json_obj=$(echo "$json_obj" | jq --arg v "$name" '. + {"name": $v}')
local output_text
if [[ $json_mode -eq 1 ]]; then if [[ $json_mode -eq 1 ]]; then
if [[ $alpha_mode -eq 1 ]]; then output_text="$json_obj"
clip_value=$(printf '{"hex":"#%s","rgba":[%d,%d,%d,%d]}' "$clean_hex" "$r" "$g" "$b" "$a")
else
clip_value=$(printf '{"hex":"#%s","rgb":[%d,%d,%d]}' "${clean_hex:0:6}" "$r" "$g" "$b")
fi
[[ -n "$name" ]] && clip_value="${clip_value%\}}$(printf ',"name":"%s"}' "$name")"
elif [[ $alpha_mode -eq 1 ]]; then
clip_value="#${clean_hex}"
else else
clip_value="#${clean_hex:0:6}" output_text=$(IFS=' ' ; echo "${display_parts[*]}")
[[ -n "$name" ]] && output_text="$output_text ($name)"
fi fi
# Terminal output — skipped in desktop mode (no terminal to write to)
if [[ $desktop_mode -eq 0 ]]; then if [[ $desktop_mode -eq 0 ]]; then
if [[ $json_mode -eq 1 ]]; then if [[ $swatch_mode -eq 1 ]]; then
echo "$clip_value" local r g b
else r=$(echo "$formats_json" | jq -r '._raw.r')
if [[ $alpha_mode -eq 1 ]]; then g=$(echo "$formats_json" | jq -r '._raw.g')
printf "\033[2mHEX:\033[0m #%s \033[2m→ RGBA(\033[0m%3d, %3d, %3d, %3d\033[2m)\033[0m → \033[48;2;%d;%d;%dm \033[0m" \ b=$(echo "$formats_json" | jq -r '._raw.b')
"$clean_hex" "$r" "$g" "$b" "$a" "$r" "$g" "$b" if [[ $json_mode -eq 1 ]]; then printf "\033[48;2;${r};${g};${b}m \033[0m\n"
else else printf "\033[48;2;${r};${g};${b}m \033[0m "; fi
printf "\033[2mHEX:\033[0m #%s \033[2m→ RGB(\033[0m%3d, %3d, %3d\033[2m)\033[0m → \033[48;2;%d;%d;%dm \033[0m" \
"${clean_hex:0:6}" "$r" "$g" "$b" "$r" "$g" "$b"
fi
[[ -n "$name" ]] && printf " \033[2m→ Name:\033[0m %s" "$name"
echo
fi fi
echo -e "$output_text"
fi fi
# Non-fatal: warn if clipboard copy fails (e.g. no clipboard utility installed) [[ $copy_mode -eq 1 ]] && copy_to_clipboard "$output_text" || true
[[ $copy_mode -eq 1 ]] && copy_to_clipboard "$clip_value" || true [[ $notify_mode -eq 1 ]] && notify_result "$output_text" || true
[[ $notify_mode -eq 1 ]] && notify_result "$clip_value" || true
} }
# ── Argument parsing ────────────────────────────────────────────────────────── # ── Argument parsing ──────────────────────────────────────────────────────────
# Apply config defaults before processing CLI args so flags can still override them
load_config load_config
args=() args=()
do_pick=0
# First pass: collect CLI overrides
while [[ $# -gt 0 ]]; do while [[ $# -gt 0 ]]; do
case "$1" in case "$1" in
--help | -h) --help|-h) show_help; exit 0 ;;
show_help --output) cli_output="$2"; shift ;;
exit 0 --json) cli_json=1 ;;
;; --no-json) cli_json=0 ;;
--pick) --alpha) cli_alpha=1; cli_output="hexa" ;;
# Run the picker immediately; its output (a hex string) is queued for conversion --no-alpha)cli_alpha=0 ;;
picked="$(run_color_picker)" || exit 1 --name) cli_name=1 ;;
[[ -n "$picked" ]] && args+=("$picked") --no-name) cli_name=0 ;;
;; --swatch) cli_swatch=1 ;;
--json) json_mode=1 ;; --no-swatch)cli_swatch=0 ;;
--alpha) alpha_mode=1 ;; --copy) cli_copy=1 ;;
--name) name_mode=1 ;; --no-copy) cli_copy=0 ;;
--copy) copy_mode=1 ;; --notify) cli_notify=1 ;;
--desktop) desktop_mode=1; apply_desktop_config ;; --no-notify)cli_notify=0 ;;
--install) do_install; exit 0 ;; --pick) cli_pick=1 ;;
-*) --no-pick) cli_pick=0 ;;
echo "Unknown option: $1" >&2 --desktop) desktop_mode=1 ;;
exit 1 --install) do_install; exit 0 ;;
;; -*) echo "Unknown option: $1" >&2; exit 1 ;;
*) *) args+=("$1") ;;
args+=("$1")
;;
esac esac
shift shift
done done
# Collect any hex values piped via stdin # Apply final hierarchy: CLI Flags > Desktop Config (if --desktop) > Default Config
if [[ ! -t 0 ]]; then if [[ $desktop_mode -eq 1 ]]; then
while read -r line; do json_mode=${cli_json:-$desktop_json}
[[ -n "$line" ]] && args+=("$line") alpha_mode=${cli_alpha:-$desktop_alpha}
done name_mode=${cli_name:-$desktop_name}
notify_mode=${cli_notify:-$desktop_notify}
output_formats=${cli_output:-$desktop_output}
copy_mode=${cli_copy:-$desktop_copy}
do_pick=${cli_pick:-1}
swatch_mode=${cli_swatch:-0} # swatch usually off in desktop mode
else
json_mode=${cli_json:-$json_mode}
alpha_mode=${cli_alpha:-$alpha_mode}
name_mode=${cli_name:-$name_mode}
notify_mode=${cli_notify:-$notify_mode}
output_formats=${cli_output:-$output_formats}
copy_mode=${cli_copy:-$copy_mode}
do_pick=${cli_pick:-0}
swatch_mode=${cli_swatch:-$swatch_mode}
fi fi
# No colors collected: auto-pick if config requests it, otherwise show help # Validation
if [[ ${#args[@]} -eq 0 ]]; then validate_output_formats "$output_formats" || exit 1
# Stdin support
[[ ! -t 0 ]] && while read -r line; do [[ -n "$line" ]] && args+=("$line"); done
# Execution
if [[ $do_pick -eq 1 ]]; then
picked="$(run_color_picker)" || exit 1
[[ -n "$picked" ]] && args+=("$picked")
elif [[ ${#args[@]} -eq 0 ]]; then
if [[ $config_pick -eq 1 ]]; then if [[ $config_pick -eq 1 ]]; then
picked="$(run_color_picker)" || exit 1 picked="$(run_color_picker)" || exit 1
[[ -n "$picked" ]] && args+=("$picked") [[ -n "$picked" ]] && args+=("$picked")
elif [[ -t 0 ]]; then elif [[ -t 0 ]]; then
show_help show_help; exit 0
exit 0
fi fi
fi fi
# ── Execution ───────────────────────────────────────────────────────────────── for color in "${args[@]}"; do process_color "$color"; done
for hex in "${args[@]}"; do
hex_to_rgba "$hex"
done
-20
View File
@@ -1,20 +0,0 @@
#!/usr/bin/python3
from PyQt6.QtDBus import QDBusConnection, QDBusMessage, QDBusPendingReply, QDBusPendingCallWatcher
from PyQt6.QtCore import QCoreApplication
from PyQt6.QtGui import QColor
import sys
def colorPicked():
reply = QDBusPendingReply(call)
if reply.isError():
print(reply.error().message())
else:
print(QColor(reply.argumentAt(0)[0]).name())
app = QCoreApplication(sys.argv)
msg = QDBusMessage.createMethodCall("org.kde.KWin", "/ColorPicker", "org.kde.kwin.ColorPicker", "pick")
call = QDBusConnection.sessionBus().asyncCall(msg)
watcher = QDBusPendingCallWatcher(call, app)
watcher.finished.connect(colorPicked)
watcher.waitForFinished()