toggle_external_display.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. #!/usr/bin/env ruby
  2. xrandr = `xrandr`.to_s
  3. @common_monitors = { '3440x1440' => 'left', '2560x1440' => 'left' }
  4. @restart_background = ARGV.include?('--restart-background') || system('pgrep openbox -u $USER >/dev/null')
  5. @internal_monitor = xrandr.match(/((LVDS|eDP)\d*) connected/)[1]
  6. def restart_background
  7. if @restart_background
  8. system "$HOME/.conkyinit --restart >/dev/null 2>&1"
  9. system "$HOME/.fehbg"
  10. end
  11. end
  12. def disable_monitor(external_monitor)
  13. system "xrandr --output #{external_monitor} --off --output #{@internal_monitor} --auto --scale 1.0x1.0"
  14. restart_background
  15. end
  16. def enable_mirror(external_monitor, resolution)
  17. system "xrandr --output #{external_monitor} --mode #{resolution} --same-as #{@internal_monitor} --output #{@internal_monitor} --scale-from #{resolution}"
  18. restart_background
  19. end
  20. def enable_multihead(external_monitor, resolution, side)
  21. system "xrandr --output #{external_monitor} --mode #{resolution} --#{side}-of #{@internal_monitor}"
  22. restart_background
  23. end
  24. if xrandr =~ /((HDMI|[^e]DP)(\d*)) (dis)?connected \d+x\d+/
  25. disable_monitor($1)
  26. elsif xrandr =~ /((HDMI|[^e]DP)(\d*)) connected/
  27. ext_mon = $1
  28. resolutions = xrandr.sub(/.*#{ext_mon}.*?\n/m, '').scan(/\d{1,4}x\d{1,4}.*?(?=\s)/)
  29. resolutions = resolutions.sort_by { |res| x, y = res.split(/[^\d]/).map(&:to_f); -x*y }
  30. unless (common_resolutions = resolutions & @common_monitors.keys).empty?
  31. resolution = common_resolutions.first
  32. enable_multihead(ext_mon, resolution, @common_monitors[resolution])
  33. else
  34. enable_mirror(ext_mon, resolutions.first)
  35. end
  36. end