Skip to content

Instantly share code, notes, and snippets.

@kronn
Created November 9, 2018 09:22
Show Gist options
  • Save kronn/63bd520a214ea9114df231a5235bba22 to your computer and use it in GitHub Desktop.
Save kronn/63bd520a214ea9114df231a5235bba22 to your computer and use it in GitHub Desktop.
thin wrapper around xrandr to determine the primary output (among others)
#!/usr/bin/env ruby
# frozen_string_literal: true
# Detect the monitor setup
#
# rubocop:disable Metrics/LineLength,Lint/MissingCopEnableDirective
command = ARGV[0]
# subcommand = ARGV[1]
# value-object with high-end regex string-parsing power
class XrandrInfo
attr_reader :output, :primary, :width, :height
def initialize(xrandr_string)
matches = xrandr_string.match(
/^(?<output>\S+) connected(?<primary> primary)? (?<width>\d+)x(?<height>\d+)/
) || {}
@output = matches[:output]
@primary = matches[:primary] == ' primary'
@width = matches[:width].to_i
@height = matches[:height].to_i
end
def to_s
"<XrandrInfo output:#{@output} primary:#{@primary} dimensions:#{@width}x#{@height}>"
end
def width_class
case @width
when 0...1024 then 'tiny'
when 1024...1920 then 'small'
when 1920...3440 then 'medium'
when 3440...10_000 then 'wide'
end
end
def device
case @output
when 'eDP1' then :laptop
end
end
end
def rescan_monitors
`xrandr | grep ' connected'`
.each_line.map(&:chomp)
.map { |output| XrandrInfo.new(output) }
end
monitors = rescan_monitors
primary = monitors.find(&:primary)
puts case command
when 'width' then primary.width_class
when 'output' then primary.output
when 'set'
if monitors.size == 1 && primary.device == :laptop
system "xrandr --output #{primary.output} --mode 1600x900"
end
system '~/.fehbg'
"Resolution set: #{rescan_monitors.find(&:primary)}"
else primary
end
exit
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment