1
0

detect-monitor.sh 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #!/usr/bin/env bash
  2. # Klimbim Software collection, A bag full of things
  3. # Copyright (C) 2011-2023 Johannes 'Banana' Keßler
  4. #
  5. # This program is free software: you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation, either version 3 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. # 2018 http://www.bananas-playground.net
  18. # detect on which monitor the current active window is
  19. # limitation are with negative position coordinates.
  20. # needs the following applications
  21. # xdotool
  22. # xwininfo
  23. # xrandr
  24. OFFSET_RE="[\+\-]([-0-9]+)[\+\-]([-0-9]+)"
  25. # Get the window position
  26. window_id=$(xdotool getactivewindow)
  27. posx=$(xwininfo -id $window_id | awk '/Absolute upper-left X:/ { print $4 }')
  28. posy=$(xwininfo -id $window_id | awk '/Absolute upper-left Y:/ { print $4 }')
  29. # Subtract any offsets caused by window decorations and panels
  30. x_offset=$(xwininfo -id $window_id | awk '/Relative upper-left X:/ { print $4 }')
  31. y_offset=$(xwininfo -id $window_id | awk '/Relative upper-left Y:/ { print $4 }')
  32. posx=$((posx - x_offset))
  33. posy=$((posy - y_offset))
  34. # Loop through each screen and compare the offset with the window
  35. # coordinates.
  36. while read name width height xoff yoff
  37. do
  38. if [ "$posx" -ge "$xoff" \
  39. -a "$posy" -ge "$yoff" \
  40. -a "$posx" -lt "$(($xoff+$width))" \
  41. -a "$posy" -lt "$(($yoff+$height))" ]
  42. then
  43. monitor=$name
  44. fi
  45. done < <(xrandr | grep -w connected |
  46. sed -r "s/^([^ ]*).*\b([-0-9]+)x([-0-9]+)$OFFSET_RE.*$/\1 \2 \3 \4 \5/" |
  47. sort -nk4,5)
  48. # If we found a monitor, echo it out, otherwise print an error.
  49. if [ ! -z "$monitor" ]
  50. then
  51. echo $monitor
  52. exit 0
  53. else
  54. echo "Couldn't find any monitor for the current window." >&2
  55. echo "Or the top left pos is moved out of the screen and thus a negative pos." >&2
  56. exit 1
  57. fi