Threadify property runs
[amazing.git] / lib / amazing / cli.rb
blob9c1d90509668ff541a7896cb2b41f12d9425d301
1 # Copyright (C) 2008 Dag Odenhall <dag.odenhall@gmail.com>
2 # Licensed under the Academic Free License version 3.0
4 require 'logger'
5 require 'amazing/options'
6 require 'amazing/x11/display_name'
7 require 'amazing/config'
8 require 'amazing/string'
9 require 'amazing/widget'
10 require 'amazing/proc_file'
11 require 'amazing/widgets'
12 require 'amazing/awesome'
13 require 'timeout'
14 require 'fileutils'
15 require 'thread'
17 module Amazing
19   # Command line interface runner
20   #
21   #   CLI.run(ARGV)
22   class CLI
23     def initialize(args)
24       @args = args
25       @log = Logger.new(STDOUT)
26       @options = Options.new(@args)
27       begin
28         @display = X11::DisplayName.new
29       rescue X11::EmptyDisplayName => e
30         @log.warn("#{e.message}, falling back on :0")
31         @display = X11::DisplayName.new(":0")
32       rescue X11::InvalidDisplayName => e
33         @log.fatal("#{e.message}, exiting")
34         exit 1
35       end
36       @threads = []
37     end
39     def run
40       at_exit do
41         remove_pid
42         Thread.list.each {|t| t.exit }
43       end
44       trap("SIGINT") do
45         @log.fatal("Received SIGINT, exiting")
46         exit
47       end
48       @options.parse
49       show_help if @options[:help]
50       set_loglevel
51       stop_process(true) if @options[:stop]
52       load_scripts
53       list_widgets if @options[:listwidgets]
54       test_widget if @options[:test]
55       parse_config
56       wait_for_sockets
57       @awesome = Awesome.new(@display.display)
58       explicit_updates unless @options[:update] == []
59       stop_process
60       save_pid
61       update_non_interval
62       @config[:awesome].each do |awesome|
63         awesome[:widgets].each do |widget|
64           if widget[:interval]
65             @threads << Thread.new(awesome, widget) do |awesome, widget|
66               iteration = 1
67               loop do
68                 Thread.new { update_widget(awesome[:screen], awesome[:statusbar], widget, iteration) }
69                 iteration += 1
70                 sleep widget[:interval]
71               end
72             end
73           end
74         end
75       end
76       @threads.each {|t| t.join }
77     end
79     private
81     def show_help
82       puts @options.help
83       exit
84     end
86     def set_loglevel
87       begin
88         @log.level = Logger.const_get(@options[:loglevel].upcase)
89       rescue NameError
90         @log.error("Unsupported log level #{@options[:loglevel].inspect}")
91         @log.level = Logger::INFO
92       end
93     end
95     def stop_process(quit=false)
96       begin
97         Process.kill("SIGINT", File.read("#{ENV["HOME"]}/.amazing/pids/#{@display.display}.pid").to_i) 
98         @log.warn("Killed older process") unless quit
99       rescue
100       end
101       exit if quit
102     end
104     def load_scripts
105       scripts = @options[:include]
106       if @options[:autoinclude]
107         scripts << Dir["#{ENV["HOME"]}/.amazing/widgets/*"]
108       end
109       scripts.flatten.each do |script|
110         if File.exist?(script)
111           @log.debug("Loading script #{script.inspect}")
112           begin
113             Widgets.module_eval(File.read(script), script)
114           rescue SyntaxError => e
115             @log.error("Bad syntax in #{script} at line #{e.to_s.scan(/:(\d+)/)}")
116           end
117         else
118           @log.error("No such widget script #{script.inspect}")
119         end
120       end
121     end
123     def parse_config
124       @log.debug("Parsing configuration file")
125       begin
126         @config = Config.new(@options[:config])
127       rescue
128         @log.fatal("Unable to parse configuration file, exiting")
129         exit 1
130       end
131     end
133     def list_widgets
134       if @options[:listwidgets] == true
135         longest_widget_name = Widgets.constants.inject {|a,b| a.length > b.length ? a : b }.length
136         Widgets.constants.sort.each do |widget|
137           widget_class = Widgets.const_get(widget)
138           puts "%-#{longest_widget_name}s : %s" % [widget, widget_class.description]
139         end
140       else
141         widget_class = Widgets.const_get(@options[:listwidgets].camel_case)
142         puts
143         puts "#{@options[:listwidgets].camel_case} - #{widget_class.description}"
144         puts
145         dependencies = widget_class.dependencies
146         unless dependencies.empty?
147           longest_dependency_name = dependencies.keys.inject {|a,b| a.to_s.length > b.to_s.length ? a : b }.to_s.length
148           longest_dependency_name = 10 if longest_dependency_name < 10
149           longest_description = dependencies.values.inject {|a,b| a.length > b.length ? a : b }.length
150           longest_description = 11 if longest_description < 11
151           puts " %-#{longest_dependency_name}s | DESCRIPTION" % "DEPENDENCY"
152           puts "-" * (longest_dependency_name + longest_description + 5)
153           dependencies.keys.sort.each do |dependency|
154             puts " %-#{longest_dependency_name}s | #{dependencies[dependency]}" % dependency
155           end
156           puts
157         end
158         options = widget_class.options
159         unless options.empty?
160           longest_option_name = options.keys.inject {|a,b| a.to_s.length > b.to_s.length ? a : b }.to_s.length
161           longest_option_name = 6 if longest_option_name < 6
162           longest_description = options.values.inject {|a,b| a[:description].length > b[:description].length ? a : b }[:description].length
163           longest_description = 11 if longest_description < 11
164           longest_default = options.values.inject {|a,b| a[:default].inspect.length > b[:default].inspect.length ? a : b }[:default].inspect.length
165           longest_default = 7 if longest_default < 7
166           puts " %-#{longest_option_name}s | %-#{longest_description}s | DEFAULT" % ["OPTION", "DESCRIPTION"]
167           puts "-" * (longest_option_name + longest_description + longest_default + 8)
168           options.keys.sort_by {|option| option.to_s }.each do |option|
169             puts " %-#{longest_option_name}s | %-#{longest_description}s | %s" % [option, options[option][:description], options[option][:default].inspect]
170           end
171           puts
172         end
173         fields = widget_class.fields
174         unless fields.empty?
175           longest_field_name = fields.keys.inject {|a,b| a.to_s.length > b.to_s.length ? a : b }.to_s.length
176           longest_field_name = 5 if longest_field_name < 5
177           longest_description = fields.values.inject {|a,b| a[:description].length > b[:description].length ? a : b }[:description].length
178           longest_description = 11 if longest_description < 11
179           longest_default = fields.values.inject {|a,b| a[:default].inspect.length > b[:default].inspect.length ? a : b }[:default].inspect.length
180           longest_default = 7 if longest_default < 7
181           puts " %-#{longest_field_name + 1}s | %-#{longest_description}s | DEFAULT" % ["FIELD", "DESCRIPTION"]
182           puts "-" * (longest_field_name + longest_description + longest_default + 9)
183           fields.keys.sort_by {|field| field.to_s }.each do |field|
184             puts " @%-#{longest_field_name}s | %-#{longest_description}s | %s" % [field, fields[field][:description], fields[field][:default].inspect]
185           end
186           puts
187         end
188       end
189       exit
190     end
192     def test_widget
193       widget = Widgets.const_get(@options[:test].camel_case)
194       settings = YAML.load("{#{ARGV[0]}}")
195       instance = widget.new(settings)
196       longest_field_name = widget.fields.merge({:default => nil}).keys.inject {|a,b| a.to_s.length > b.to_s.length ? a : b }.to_s.length
197       puts "@%-#{longest_field_name}s = %s" % [:default, instance.instance_variable_get(:@default).inspect]
198       widget.fields.keys.sort_by {|field| field.to_s }.each do |field|
199         puts "@%-#{longest_field_name}s = %s" % [field, instance.instance_variable_get("@#{field}".to_sym).inspect]
200       end
201       exit
202     end
204     def wait_for_sockets
205       @log.debug("Waiting for awesome control socket for display #{@display.display}")
206       begin
207         Timeout.timeout(30) do
208           sleep 1 until File.exist?("#{ENV["HOME"]}/.awesome_ctl.#{@display.display}")
209           @log.debug("Got socket for display #{@display.display}")
210         end
211       rescue Timeout::Error
212         @log.fatal("Socket for display #{@display.display} not created within 30 seconds, exiting")
213         exit 1
214       end
215     end
217     def explicit_updates
218       @config[:awesome].each do |awesome|
219         awesome[:widgets].each do |widget|
220           locator = "%s/%s/%s" % [widget[:identifier], awesome[:statusbar], awesome[:screen]]
221           next unless @options[:update] == :all || @options[:update].include?(locator)
222           @threads << Thread.new(awesome, widget) do |awesome, widget|
223             update_widget(awesome[:screen], awesome[:statusbar], widget)
224           end
225         end
226       end
227       @threads.each {|t| t.join }
228       exit
229     end
231     def save_pid
232       path = "#{ENV["HOME"]}/.amazing/pids"
233       FileUtils.makedirs(path)
234       File.open("#{path}/#{@display.display}.pid", "w+") do |f|
235         f.write($$)
236       end
237     end
239     def remove_pid
240       File.delete("#{ENV["HOME"]}/.amazing/pids/#{@display.display}.pid") rescue Errno::ENOENT
241     end
243     def update_non_interval
244       @config[:awesome].each do |awesome|
245         awesome[:widgets].each do |widget|
246           next if widget[:interval]
247           @threads << Thread.new(awesome, widget) do |awesome, widget|
248             update_widget(awesome[:screen], awesome[:statusbar], widget)
249           end
250         end
251       end
252       @threads.each {|t| t.join }
253     end
255     def update_widget(screen, statusbar, widget, iteration=0)
256       @log.debug("Updating widget #{widget[:identifier]} of type #{widget[:module]} on screen #{screen}")
257       begin
258         mod = Widgets.const_get(widget[:module]).new(widget.merge(:iteration => iteration))
259         if widget[:properties].empty?
260           Thread.new { @awesome.widget_tell(screen, statusbar, widget[:identifier], widget[:property], mod.formatize) }
261         end
262         widget[:properties].each do |property, format|
263           Thread.new { @awesome.widget_tell(screen, statusbar, widget[:identifier], property, mod.formatize(format)) }
264         end
265       rescue WidgetError => e
266         @log.error(widget[:module]) { e.message }
267       end
268     end
269   end