Class: Xrandr::Parser

Inherits:
Object
  • Object
show all
Defined in:
lib/xrandr.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data = `xrandr --query`) ⇒ Parser

Returns a new instance of Parser.



43
44
45
# File 'lib/xrandr.rb', line 43

def initialize(data = `xrandr --query`)
  @data = data
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



42
43
44
# File 'lib/xrandr.rb', line 42

def data
  @data
end

Instance Method Details

#parseObject



47
48
49
50
51
# File 'lib/xrandr.rb', line 47

def parse
  screens_data, outputs_data = data.split("\n").group_by {|line| line.start_with?('Screen') }.values

  [ parse_screens(screens_data), parse_outputs(outputs_data) ]
end

#parse_mode(data) ⇒ Object



98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/xrandr.rb', line 98

def parse_mode(data)
  matches = data.lstrip.match(/^(?<resolution>\d+x\d+i?) +(?<rate>[\d\.]+)(?<current>[\* ])(?<preferred>[\+ ]).*/)

  resolution = matches[:resolution].gsub 'i', '' if matches[:resolution]
  args = {
          resolution: resolution,
          rate: matches[:rate],
          current: matches[:current] == '*',
          preferred: matches[:preferred] == '+',
         }

  Mode.new args
end

#parse_modes(modes) ⇒ Object



92
93
94
95
96
# File 'lib/xrandr.rb', line 92

def parse_modes(modes)
  modes.map do |data|
    parse_mode data
  end
end

#parse_output(data) ⇒ Object



64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
# File 'lib/xrandr.rb', line 64

def parse_output(data)
  data, *modes = data

  args = {
          name:       /[a-zA-Z0-9\-\_]+/,
          connected:  /connected|disconnected/,
          primary:    /primary/,
          resolution: /\d+x\d+\+\d+\+\d+/,
          info:       /\([^\)]+\)/,
          dimensions: /[0-9+]+mm x [0-9]+mm/,
         }
  .map {|token, regex| [token, data.scan(regex).first] }
  .to_h

  # split resolution and position values split all values, coherce to integers, split the array in halfs, assign each half)
  args[:resolution], args[:position] = args[:resolution].split(/x|\+/).each_slice(2).map {|v| v.join('x') }  if args[:resolution]

  # Coherce parameters
  args[:connected] = args[:connected] == 'connected'
  args[:primary]   = args[:primary] == 'primary'

  # Parse modes

  args[:modes] = args[:connected] ? parse_modes(modes) : []

  Output.new args
end

#parse_outputs(data) ⇒ Object



55
56
57
58
59
60
61
62
# File 'lib/xrandr.rb', line 55

def parse_outputs(data)
  # join output info line with each of its modes
  data = data.slice_when {|before, after| !after.start_with?(' ')}

  data.map do |output_data|
    parse_output(output_data)
  end
end

#parse_screens(data) ⇒ Object

TODO



53
# File 'lib/xrandr.rb', line 53

def parse_screens(data); []; end