#!/bin/bash
####################################################################################
#                                                                                  #
#   This script will catch mouse click and scroll events                           #
#                                                                                  #
#   Depends on: xinput, xdotool, xprop, xwininfo, wmctrl, playerctl                #
#                                                                                  #
#                                                                     version 2.6  #
####################################################################################

# DEBUG
#   0 = off
#   1 = windowid & name
#   2 = x,y position mouse on conky
debug="0"

# MOUSE_UNDER_WINDOW Loop delay
#   Too small will increase cpu load and X errors, but faster window detection
#   Too high will slow down window detection, but less cpu load and no X errors
muwloopdelay="0.2"

# MOUSE EVENT Loop delay
#   Too small will increase cpu load, but faster sensivity
#   Too high will slow down sensivity but decreases cpu load
mkloopdelay="0.01"


###################################################################################
#####################  DO NOT EDIT AFTER THIS LINE !  #############################
###################################################################################


if [ "$1" != "goclickevents" ]; then
   echo -e "\n\e[31mERROR:\e[m Click_events can not start outside of conky!\n"
   exit 1
fi

source "./player.ini"

# Check if all dependencies are installed
  if [ "$(which xinput)" = "" ]; then echo -e "\e[31mERROR\e[m 'xinput' not installed!\n"; exit 1; fi
  if [ "$(which xdotool)" = "" ]; then echo -e "\e[31mERROR\e[m 'xdotool' not installed!\n"; exit 1; fi
  if [ "$(which xprop)" = "" ]; then echo -e "\e[31mERROR\e[m 'xprop' not installed!\n"; exit 1; fi
  if [ "$(which xwininfo)" = "" ]; then echo -e "\e[31mERROR\e[m 'xwininfo' not installed!\n"; exit 1; fi
  if [ "$(which wmctrl)" = "" ]; then echo -e "\e[31mERROR\e[m 'wmctrl' not installed!\n"; exit 1; fi
  if [ "$(which playerctl)" = "" ]; then echo -e "\e[31mERROR\e[m 'playerctl' not installed!\n"; exit 1; fi


# Let the conkies start first before we go search for the window
  sleep 3
  echo -e "\e[32mINFO\e[m  [click_events] Click events are activated.  (BASH)" >/dev/stderr

# Get own_window_title (windowname) of vu-meters.conky
# Since that is the top layer we need mouse event from that conky
  WNAME=$(grep 'own_window_title' "./vu-meters.conky" | xargs | cut -d' ' -f3 | sed s/,*$//g)



# Functions for media button click and release
function click_on() {
   touch "./tempfiles/buttonclick"
   ./buttons gobuttons $1
}
function click_off() {
   sleep 0.4
   rm -f "./tempfiles/buttonclick"
   ./buttons gobuttons $1
}



# Routine that checks in a loop if mouse is over the conky window
function mouse_over_window() {
   # Get window ID from window below mouse
   WINDOW_UNDER_MOUSE=$(xdotool getmouselocation --shell | grep WINDOW | cut -d= -f2)
   # Only continue if ID is greater then 0
   until [ "$WINDOW_UNDER_MOUSE" -gt "0" ]
   do
         WINDOW_UNDER_MOUSE=$(xdotool getmouselocation --shell | grep WINDOW | cut -d= -f2)
   done
   # Get window name that correspond to the ID
   WIN_NAME=$(xprop -id $WINDOW_UNDER_MOUSE WM_NAME 2>/dev/null | cut -d'"' -f2)

   # For test purpose uncomment below line
   if [ "$debug" = "1" ]; then echo "1) $WINDOW_UNDER_MOUSE = $WIN_NAME"; fi

   # Check if window name is active
   while [ "$(wmctrl -l | grep "\<$WNAME\>" | awk '{print $NF}')" != "WIN_NAME" ]
   do
              # Get window ID from window below mouse
              WINDOW_UNDER_MOUSE=$(xdotool getmouselocation --shell | grep WINDOW | cut -d= -f2)
              # Only continue if ID is greater then 0
              until [ "$WINDOW_UNDER_MOUSE" -gt "0" ]
              do
                    WINDOW_UNDER_MOUSE=$(xdotool getmouselocation --shell | grep WINDOW | cut -d= -f2)
              done
              # Get window name that correspond to the ID
              WIN_NAME=$(xprop -id $WINDOW_UNDER_MOUSE WM_NAME 2>/dev/null | cut -d'"' -f2)

              # For test purpose uncomment below line
              if [ "$debug" = "1" ]; then echo "2) $WINDOW_UNDER_MOUSE = $WIN_NAME"; fi

              # If mouse is over correct window then enable mouse events and skip this itteration of loop
              if [ "$WIN_NAME" = "$WNAME" ]; then
                 touch "./tempfiles/do_event"
                 continue
              else
                 # If not, disable mouse events
                 rm -f "./tempfiles/do_event"
              fi

              # Sleep before we do the next itteration
              sleep $muwloopdelay

   done
}
mouse_over_window &



# Start mouse events loop
  while read -r mousekey
  do

        # Small delay or loop will go bezerk on cpu load and hard to kill
        sleep $mkloopdelay

        # If do_event file does not exist, then we are not over the correct window, so skip itteration untill we are
        if ! [ -f "./tempfiles/do_event" ]; then
          continue
        fi

        # Coordinates of conky window
        WX=$(xwininfo -name "$WNAME" | grep "Absolute upper-left X" 2>/dev/null | awk '{print $4}')
        WY=$(xwininfo -name "$WNAME" | grep "Absolute upper-left Y" 2>/dev/null | awk '{print $4}')

        # Get mouse location
        eval $(xdotool getmouselocation --shell) # 2>/dev/null)

        # Calculate mouse location within conky window
        export REL_X=$((X - WX))
        export REL_Y=$((Y - WY))

        # DEBUG X,Y mouse location output to terminal. This to locate where you want the click x,y coordinates
        if [ "$debug" = "2" ]; then  echo "REL_X=$REL_X  -  REL_Y=$REL_Y" >/dev/stderr; fi

        # Get mouse event from xinput
        action=$(echo "$mousekey" | awk '{print $2}')
        button=$(echo "$mousekey" | awk '{print $3}')

        ### LEFT CLICK
        if [ "$action" = "press" ] && [ "$button" = "1" ]; then

            # Check if new update, if so make coverart click window shorter
            if [ -f ./tempfiles/new_update ]; then
               # If on COVERART
               if [[ $REL_X -ge 23 && $REL_X -le 142 && $REL_Y -ge 19 && $REL_Y -le 121 ]]; then
                  xdg-open "./coverart/coverart.png" &
               fi
               # If on NEW UPDATE
               if [[ $REL_X -ge 23 && $REL_X -le 142 && $REL_Y -ge 122 && $REL_Y -le 138 ]]; then
                  xdg-open https://www.cobrasoft.nl/download/conky/musicplayer
               fi
            else
               # If on COVERART
               if [[ $REL_X -ge 23 && $REL_X -le 142 && $REL_Y -ge 19 && $REL_Y -le 138 ]]; then
                  xdg-open "./coverart/coverart.png" &
               fi
            fi

            # If on right top corner to stop conky
            if [[ $REL_X -ge 395 && $REL_X -le 405 && $REL_Y -ge 0 && $REL_Y -le 10 ]]; then
               ./stop &
               exit 0
            fi

            # If on button PREV
            if [[ $REL_X -ge 27 && $REL_X -le 52 && $REL_Y -ge 149 && $REL_Y -le 174 ]]; then
               click_on prev
               playerctl -p $player previous
               click_off prev
            fi

            # If on button PLAY
            if [[ $REL_X -ge 56 && $REL_X -le 81 && $REL_Y -ge 149 && $REL_Y -le 174 ]]; then
               # Check status of player from tempfile and don't leave loop empty handed!
               while :
               do
                    playerstat=$(cat "./tempfiles/playerstatus")
                    if [ "$playerstat" != "" ]; then
                       if [ "$playerstat" = "No players found" ]; then playerstat="Stopped"; fi
                       break
                    fi
               done
               if [ "$playerstat" = "Playing" ]; then
                  click_on pause
                  click_off pause
                  playerctl -p $player play-pause
               elif [ "$playerstat" = "Paused" ] || [ "$playerstat" = "Stopped" ]; then
                  click_on play
                  click_off play
                  playerctl -p $player play-pause
               fi
            fi

            # If on button STOP
            if [[ $REL_X -ge 85 && $REL_X -le 110 && $REL_Y -ge 149 && $REL_Y -le 174 ]]; then
               click_on stop
               playerctl -p $player stop
               click_off stop
            fi

            # If on button NEXT
            if [[ $REL_X -ge 114 && $REL_X -le 139 && $REL_Y -ge 149 && $REL_Y -le 174 ]]; then
               click_on next
               playerctl -p $player next
               click_off next
            fi


        ### SCROLL UP
        elif [ "$action" = "press" ] && [ "$button" = "4" ]; then
            # On VU meter
            if [[ $REL_X -ge 154 && $REL_X -le 399 && $REL_Y -ge 103 && $REL_Y -le 168 ]]; then
               playerctl -p $player volume 0.02+
            fi

            # On time bar
            if [[ $REL_X -ge 158 && $REL_X -le 377 && $REL_Y -ge 80 && $REL_Y -le 90 ]]; then
               playerctl -p $player position 4+
            fi


        ### SCROLL DOWN
        elif [ "$action" = "press" ] && [ "$button" = "5" ]; then
            # On VU meter
            if [[ $REL_X -ge 154 && $REL_X -le 399 && $REL_Y -ge 103 && $REL_Y -le 168 ]]; then
               playerctl -p $player volume 0.02-
            fi

            # On time bar
            if [[ $REL_X -ge 158 && $REL_X -le 377 && $REL_Y -ge 80 && $REL_Y -le 90 ]]; then
               playerctl -p $player position 4-
            fi


        fi # End of click events

  done < <(xinput test "$mouseid")  # End mouse events loop

exit 0
