#!/usr/bin/env bash

# (c) Copyright 2024 Mick Amadio <01micko@gmail.com> GPL3
# requires yad, dc, ppmtoxpm, grim, slurp, expr (coreutils)
#241124 sfs : rus 
yad --version |grep -E '^0' && export gtk=gtk || export gtk=yad
if [ "$LANG" != "ru_RU.UTF-8" ];then
t1="Click the Select button then place the cursor 
on screen where you want to fetch the color"
t2=Select
t3="Copy and paste color found\n to your application:"
else
t1="Нажмите кнопку \"Выбрать\", затем
нажмите на экране в том месте,
где вы хотите получить код цвета."
t2=Выбрать
t3="$t1
Скопируйте и вставьте\n код в ваше приложение:"
fi
# simple hex to decimal conversion
find_color() {
    printf "%d" "0x${1}"
}

yad_error() {
    yad --title=error --window-icon="dialog-error" --name="dialog-error" \
     --text="Error: $1" \
      --button="Close!dialog-error":1
    exit 1
}

# uses pnmtoxpm to make a 1px xpm image
get_col() {
    col=$(grim -g "$(slurp -p)" -t ppm - | ppmtoxpm1061 | while read -r a b c; do [ "$b" == 'c' ] && echo ${c%\"*}; done)
    echo $col
}

# parses an rgb color to hex from rgb.txt
parse_rgb() {
    incol="$1"    
    while read -r r g b c1 c2; do
        colsearch="$c1 $c2"
        chars=${#incol}
        val=$(expr match "${colsearch,,}" "${incol,,}")
        if [[ $chars -eq $val ]];then
            printf "%s%x" '#' "$r"
            printf "%x" "$g"
            printf "%x" "$b"
            break        
        fi
    done < ${2}
}

# shows our selected hex, rgb() and float notation colors
return_gui() {
    col_in="$1"
    # we might get a word color like 'gray20' or 'ghost white'
    if [[ "${col_in:0:1}" == [[:alpha:]] ]];then
        [[ -r "$HOME/.config/colpick.conf" ]] && \
            . $HOME/.config/colpick.conf
        rgb_txt=$rgb_txt
        # may not be installed if X not installed
        [[ -z "$rgb_txt" ]] && \
        rgb_txt=/etc/X11/rgb.txt
        # last resort, has no spaces in names, camel case
        [[ -z "$rgb_txt" ]] && \
        rgb_txt=/usr/share/netpbm/rgb.txt 
        [[ -z "$rgb_txt" ]] && return 1
        # we got here we try to parse the color
        col_in=$(parse_rgb "$col_in" "$rgb_txt")
    fi
    echo -e '<?xml version="1.0" encoding="UTF-8"?>
<svg xmlns="http://www.w3.org/2000/svg" version="1.1"  height="48px" width="48px" viewBox="0 0 48 48">
  <path d="m 0 0 48 0 0 48 -48 0 z" style="fill:'$col_in';stroke:none;"/>
</svg>' > $TEMPDIR/col.svg
    BCOL=${col_in/\#/}
    BR=${BCOL:0:2}; BG=${BCOL:2:2}; BB=${BCOL:4:2};
    BHR=$(find_color $BR)
    BHG=$(find_color $BG)
    BHB=$(find_color $BB)
    ZC='rgb('$BHR','$BHG','$BHB')'
    BHR=$(dc -e'3k '$BHR' 255 / p')
    BHG=$(dc -e'3k '$BHG' 255 / p')
    BHB=$(dc -e'3k '$BHB' 255 / p')
    X=''
    [[ ${BHR:0:1} = '.' ]] && X=0
    [[ ${BHG:0:1} = '.' ]] && X=0
    [[ ${BHB:0:1} = '.' ]] && X=0
    ZF=''$X$BHR' '$X$BHG' '$X$BHB''
    ret=$(yad --title="Color Picker" --name="select-color" --form \
    --image="$TEMPDIR/col.svg" --text="$t3" \
    --field="Color Hex" "$col_in" \
    --field="Color RGB" "$ZC" \
    --field="Color sRGB" "$ZF" \
    --Xbutton="Перезапустить!gtk-refresh":1 \
    --button="$t2!preferences-desktop-cursors!$t1":'bash -c "get_col && kill -USR1 $YAD_PID"' \
    --button=$gtk-close:1)
#    --Xbutton="OK!gtk-ok":0
#echo "www $?" #;exit
[ "$?" = "0" ] && return_gui $ret || exit
#$0 &
    return 0
}

export -f find_color get_col return_gui yad_error parse_rgb

# this script is wayland dependant
[[ -n "$WAYLAND_DISPLAY" ]] || {
    yad_error "Error: This applicatiom <b>must</b> be run in a wayland session."
    exit 1
}

ver=0.1

export TEMPDIR
TEMPDIR=$(mktemp -d /tmp/colpickXXXX)

# cleanup
trap "rm -rf $TEMPDIR" EXIT

return_gui $ret
exit
# main gui
ret=$(yad --title="Color Picker $ver" --name="select-color" \
    --text="$t1" \
    --buttons-layout=center \
    --button="$t2!preferences-desktop-cursors!$t1":'bash -c "get_col && kill -USR1 $YAD_PID"')
[[ $? -ne 0 ]] && exit
return_gui $ret || {
    yad_error "Sorry no rgb.txt found.\
\nYou can put one in your config. See <b>man wly_colpick</b>"
}
