Class: Barabara::Modules::Volume

Inherits:
Object
  • Object
show all
Includes:
Wisper::Publisher
Defined in:
lib/barabara/modules/volume.rb

Constant Summary collapse

ICONS =

Class constants (Icons) here.

{
  'mute' => "\ue04f",
  'low'  => "\ue04e",
  'med'  => "\ue050",
  'max'  => "\ue05d"
}.freeze
CMD_WATCH =
'pactl subscribe'.freeze
CMD_SET =
'amixer -q set Master'.freeze

Instance Method Summary collapse

Constructor Details

#initializeVolume

Returns a new instance of Volume.



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/barabara/modules/volume.rb', line 17

def initialize
  options = GlobalConfig.config.module_config('volume')
  @colors = GlobalConfig.config.colors
  @icons = options['icons'] || ICONS

  @icon = 'mute'
  @color = :ac_text
  @mute = true
  @level = 0
  fetch
end

Instance Method Details

#downObject



73
74
75
76
# File 'lib/barabara/modules/volume.rb', line 73

def down
  spawn(CMD_SET + ' 2%- unmute')
  fetch
end

#fetchObject



50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/barabara/modules/volume.rb', line 50

def fetch
  sleep 0.01
  raw_data = `amixer get Master`
  keys = raw_data
           .match(/Front Left:.* \[(?<level>\d+)%\] \[(?<state>[onf]+)\]/)
           .named_captures

  @level = keys['level'].to_i
  @mute = keys['state'] == 'off'
  @color, @icon = parse
  self
end

#format_stringObject



78
79
80
81
82
83
84
# File 'lib/barabara/modules/volume.rb', line 78

def format_string
  if @mute
    '%%{F%<color>s}%<icon>s%%{F-}'
  else
    '%%{F%<color>s}%<icon>s %<level>s%%%%%%{F-}'
  end
end

#muteObject



63
64
65
66
# File 'lib/barabara/modules/volume.rb', line 63

def mute
  spawn(CMD_SET + ' toggle')
  fetch
end

#parseObject



29
30
31
32
33
34
35
36
37
# File 'lib/barabara/modules/volume.rb', line 29

def parse
  return [:in_text, 'mute'] if @mute

  case @level
  when 60..100 then [:ac_text, 'max']
  when 30..60 then  [:mi_text, 'med']
  when 0..30 then   [:in_text, 'low']
  end
end

#parse_line(line) ⇒ Object



46
47
48
# File 'lib/barabara/modules/volume.rb', line 46

def parse_line(line)
  publish(:event, 'volume', update) if line.match?(/^Event 'change' on sink/)
end

#renderObject



90
91
92
# File 'lib/barabara/modules/volume.rb', line 90

def render
  format(format_string, to_h)
end

#to_hObject



86
87
88
# File 'lib/barabara/modules/volume.rb', line 86

def to_h
  { icon: @icons[@icon], color: @colors[@color], level: @level }
end

#upObject



68
69
70
71
# File 'lib/barabara/modules/volume.rb', line 68

def up
  spawn(CMD_SET + ' 2%+ unmute')
  fetch
end

#updateObject



94
95
96
97
# File 'lib/barabara/modules/volume.rb', line 94

def update
  fetch
  render
end

#watchObject



39
40
41
42
43
44
# File 'lib/barabara/modules/volume.rb', line 39

def watch
  PTY.spawn(CMD_WATCH) do |read, _write, pid|
    read.each { |line| parse_line(line.chomp) }
    Process.wait pid
  end
end