From 346e23108815cb2b82288167b2e2fc8d69c728cd Mon Sep 17 00:00:00 2001 From: Dag Odenhall Date: Sat, 8 Mar 2008 17:13:11 +0100 Subject: [PATCH] Split up in multiple files --- COPYING | 47 +++ LICENSE | 177 +++++++++++ README | 99 ++++++ TODO | 10 + amazing | 6 + amazing.rb | 648 ---------------------------------------- bin/amazing | 10 + lib/amazing.rb | 10 + lib/amazing/awesome.rb | 29 ++ lib/amazing/cli.rb | 180 +++++++++++ lib/amazing/options.rb | 67 +++++ lib/amazing/proc_file.rb | 37 +++ lib/amazing/widget.rb | 110 +++++++ lib/amazing/widgets.rb | 14 + lib/amazing/widgets/alsa.rb | 24 ++ lib/amazing/widgets/battery.rb | 24 ++ lib/amazing/widgets/clock.rb | 19 ++ lib/amazing/widgets/maildir.rb | 23 ++ lib/amazing/widgets/memory.rb | 28 ++ lib/amazing/widgets/raggle.rb | 31 ++ lib/amazing/x11.rb | 4 + lib/amazing/x11/display_name.rb | 39 +++ 22 files changed, 988 insertions(+), 648 deletions(-) create mode 100644 COPYING create mode 100644 LICENSE create mode 100644 README create mode 100644 TODO create mode 100755 amazing delete mode 100755 amazing.rb create mode 100755 bin/amazing create mode 100644 lib/amazing.rb create mode 100644 lib/amazing/awesome.rb create mode 100644 lib/amazing/cli.rb create mode 100644 lib/amazing/options.rb create mode 100644 lib/amazing/proc_file.rb create mode 100644 lib/amazing/widget.rb create mode 100644 lib/amazing/widgets.rb create mode 100644 lib/amazing/widgets/alsa.rb create mode 100644 lib/amazing/widgets/battery.rb create mode 100644 lib/amazing/widgets/clock.rb create mode 100644 lib/amazing/widgets/maildir.rb create mode 100644 lib/amazing/widgets/memory.rb create mode 100644 lib/amazing/widgets/raggle.rb create mode 100644 lib/amazing/x11.rb create mode 100644 lib/amazing/x11/display_name.rb diff --git a/COPYING b/COPYING new file mode 100644 index 0000000..7326761 --- /dev/null +++ b/COPYING @@ -0,0 +1,47 @@ += Academic Free License (“AFL”) v. 3.0 + +This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Academic Free License version 3.0 + +1. Grant of Copyright License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + + * a) to reproduce the Original Work in copies, either alone or as part of a collective work; + + * b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + + * c) to distribute or communicate copies of the Original Work and Derivative Works to the public, under any license of your choice that does not contradict the terms and conditions, including Licensor’s reserved rights and remedies, in this Academic Free License; + + * d) to perform the Original Work publicly; and + + * e) to display the Original Work publicly. + +2. Grant of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + +3. Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + +4. Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor’s trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + +5. External Deployment. The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + +6. Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + +7. Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + +8. Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + +9. Acceptance and Termination. If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including “fair use” or “fair dealing”). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + +10. Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + +11. Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + +12. Attorneys’ Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + +13. Miscellaneous. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + +14. Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +15. Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + +16. Modification of This License. This License is Copyright © 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Academic Free License" or "AFL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..7e090b8 --- /dev/null +++ b/LICENSE @@ -0,0 +1,177 @@ +Academic Free License ("AFL") v. 3.0 + +This Academic Free License (the "License") applies to any original work of +authorship (the "Original Work") whose owner (the "Licensor") has placed +the following licensing notice adjacent to the copyright notice for the +Original Work: + + Licensed under the Academic Free License version 3.0 + + 1) Grant of Copyright License. Licensor grants You a worldwide, + royalty-free, non-exclusive, sublicensable license, for the duration of + the copyright, to do the following: + + a) to reproduce the Original Work in copies, either alone or as part of + a collective work; + + b) to translate, adapt, alter, transform, modify, or arrange the + Original Work, thereby creating derivative works ("Derivative Works") + based upon the Original Work; + + c) to distribute or communicate copies of the Original Work and + Derivative Works to the public, under any license of your choice that + does not contradict the terms and conditions, including Licensor's + reserved rights and remedies, in this Academic Free License; + + d) to perform the Original Work publicly; and + + e) to display the Original Work publicly. + + 2) Grant of Patent License. Licensor grants You a worldwide, royalty-free, + non-exclusive, sublicensable license, under patent claims owned or + controlled by the Licensor that are embodied in the Original Work as + furnished by the Licensor, for the duration of the patents, to make, use, + sell, offer for sale, have made, and import the Original Work and + Derivative Works. + + 3) Grant of Source Code License. The term "Source Code" means the preferred + form of the Original Work for making modifications to it and all available + documentation describing how to modify the Original Work. Licensor agrees + to provide a machine-readable copy of the Source Code of the Original Work + along with each copy of the Original Work that Licensor distributes. + Licensor reserves the right to satisfy this obligation by placing a + machine-readable copy of the Source Code in an information repository + reasonably calculated to permit inexpensive and convenient access by You + for as long as Licensor continues to distribute the Original Work. + + 4) Exclusions From License Grant. Neither the names of Licensor, nor the + names of any contributors to the Original Work, nor any of their + trademarks or service marks, may be used to endorse or promote products + derived from this Original Work without express prior permission of the + Licensor. Except as expressly stated herein, nothing in this License + grants any license to Licensor's trademarks, copyrights, patents, trade + secrets or any other intellectual property. No patent license is granted + to make, use, sell, offer for sale, have made, or import embodiments of + any patent claims other than the licensed claims defined in Section 2. No + license is granted to the trademarks of Licensor even if such marks are + included in the Original Work. Nothing in this License shall be + interpreted to prohibit Licensor from licensing under terms different from + this License any Original Work that Licensor otherwise would have a right + to license. + + 5) External Deployment. The term "External Deployment" means the use, + distribution, or communication of the Original Work or Derivative Works in + any way such that the Original Work or Derivative Works may be used by + anyone other than You, whether those works are distributed or communicated + to those persons or made available as an application intended for use over + a network. As an express condition for the grants of license hereunder, + You must treat any External Deployment by You of the Original Work or a + Derivative Work as a distribution under section 1(c). + + 6) Attribution Rights. You must retain, in the Source Code of any Derivative + Works that You create, all copyright, patent, or trademark notices from + the Source Code of the Original Work, as well as any notices of licensing + and any descriptive text identified therein as an "Attribution Notice." + You must cause the Source Code for any Derivative Works that You create to + carry a prominent Attribution Notice reasonably calculated to inform + recipients that You have modified the Original Work. + + 7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that + the copyright in and to the Original Work and the patent rights granted + herein by Licensor are owned by the Licensor or are sublicensed to You + under the terms of this License with the permission of the contributor(s) + of those copyrights and patent rights. Except as expressly stated in the + immediately preceding sentence, the Original Work is provided under this + License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or + implied, including, without limitation, the warranties of + non-infringement, merchantability or fitness for a particular purpose. + THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This + DISCLAIMER OF WARRANTY constitutes an essential part of this License. No + license to the Original Work is granted by this License except under this + disclaimer. + + 8) Limitation of Liability. Under no circumstances and under no legal + theory, whether in tort (including negligence), contract, or otherwise, + shall the Licensor be liable to anyone for any indirect, special, + incidental, or consequential damages of any character arising as a result + of this License or the use of the Original Work including, without + limitation, damages for loss of goodwill, work stoppage, computer failure + or malfunction, or any and all other commercial damages or losses. This + limitation of liability shall not apply to the extent applicable law + prohibits such limitation. + + 9) Acceptance and Termination. If, at any time, You expressly assented to + this License, that assent indicates your clear and irrevocable acceptance + of this License and all of its terms and conditions. If You distribute or + communicate copies of the Original Work or a Derivative Work, You must + make a reasonable effort under the circumstances to obtain the express + assent of recipients to the terms of this License. This License conditions + your rights to undertake the activities listed in Section 1, including + your right to create Derivative Works based upon the Original Work, and + doing so without honoring these terms and conditions is prohibited by + copyright law and international treaty. Nothing in this License is + intended to affect copyright exceptions and limitations (including "fair + use" or "fair dealing"). This License shall terminate immediately and You + may no longer exercise any of the rights granted to You by this License + upon your failure to honor the conditions in Section 1(c). + +10) Termination for Patent Action. This License shall terminate + automatically and You may no longer exercise any of the rights granted to + You by this License as of the date You commence an action, including a + cross-claim or counterclaim, against Licensor or any licensee alleging + that the Original Work infringes a patent. This termination provision + shall not apply for an action alleging patent infringement by combinations + of the Original Work with other software or hardware. + +11) Jurisdiction, Venue and Governing Law. Any action or suit relating to + this License may be brought only in the courts of a jurisdiction wherein + the Licensor resides or in which Licensor conducts its primary business, + and under the laws of that jurisdiction excluding its conflict-of-law + provisions. The application of the United Nations Convention on Contracts + for the International Sale of Goods is expressly excluded. Any use of the + Original Work outside the scope of this License or after its termination + shall be subject to the requirements and penalties of copyright or patent + law in the appropriate jurisdiction. This section shall survive the + termination of this License. + +12) Attorneys' Fees. In any action to enforce the terms of this License or + seeking damages relating thereto, the prevailing party shall be entitled + to recover its costs and expenses, including, without limitation, + reasonable attorneys' fees and costs incurred in connection with such + action, including any appeal of such action. This section shall survive + the termination of this License. + +13) Miscellaneous. If any provision of this License is held to be + unenforceable, such provision shall be reformed only to the extent + necessary to make it enforceable. + +14) Definition of "You" in This License. "You" throughout this License, + whether in upper or lower case, means an individual or a legal entity + exercising rights under, and complying with all of the terms of, this + License. For legal entities, "You" includes any entity that controls, is + controlled by, or is under common control with you. For purposes of this + definition, "control" means (i) the power, direct or indirect, to cause + the direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + +15) Right to Use. You may use the Original Work in all ways not otherwise + restricted or conditioned by this License or by law, and Licensor promises + not to interfere with or be responsible for such uses by You. + +16) Modification of This License. This License is Copyright (C) 2005 Lawrence + Rosen. Permission is granted to copy, distribute, or communicate this + License without modification. Nothing in this License permits You to + modify this License as applied to the Original Work or to Derivative + Works. However, You may modify the text of this License and copy, + distribute or communicate your modified version (the "Modified License") + and apply it to other original works of authorship subject to the + following conditions: (i) You may not indicate in any way that your + Modified License is the "Academic Free License" or "AFL" and you may not + use those names in the name of your Modified License; (ii) You must + replace the notice specified in the first paragraph above with the notice + "Licensed under " or with a notice of your + own that is not confusingly similar to the notice in this License; and + (iii) You may not claim that your original works are open source software + unless your Modified License has been approved by Open Source Initiative + (OSI) and You comply with its license review and certification process. diff --git a/README b/README new file mode 100644 index 0000000..b6d0c1c --- /dev/null +++ b/README @@ -0,0 +1,99 @@ += amazing + +an amazing widget manager for an awesome window manager + + Usage: amazing [options] + -c, --config FILE Configuration file (~/.amazing.yml) + -s, --screen ID Screen ID (0) + -l, --log-level LEVEL Severity threshold (info) + -i, --include SCRIPT Include a widgets script + -u, --update WIDGET Update a widget and exit + -w, --list-widgets List available widgets + -h, --help You're looking at it + +== Widgets + +* Battery: Remaining battery power in percentage +* Maildir: Mail count in maildirs +* ALSA: Various data for the ALSA mixer +* Raggle: Unread posts in raggle +* Memory: Various memory related data +* Clock: Displays date and time + +== Configuration + + include: + - list + - of + - scripts + screens: + - list + - of + - screens + widgets: + identifier: + type: WidgetName + every: seconds + format: ruby code + options: + widget: foo + specific: bar + +== Example + + widgets: + pb_bat: + type: Battery + every: 10 + tb_time: + type: Clock + every: 1 + options: + time_format: %T + tb_mail: + type: Maildir + options: + directories: + - Mail/**/new + - Mail/inbox/cur + +In this example tb_mail doesn't have an "every" setting and is instead +updated manually with amazing -u tb_mail, perhaps in cron after fetching +new mail via fdm, getmail, fetchmail or similar. A good idea is also to +update after closing your MUA such as Mutt which could be done with +shell functions, example: + + mutt() { + mutt $* + amazing -u tb_mail + } + +== Writing widgets + +TODO: describe this more completely + +Example widget: + + class Clock < Widget + description "Displays date and time" + dependency "some/library", "how to get the library (url, gem name...)" + option :time_format, "Time format as described in DATE(1)", "%R" + field :time, "Formatted time" + default "@time" + + init do + @time = Time.now.strftime(@time_format) + raise WidgetError, "An error occured!" if some_error? + end + end + +The ProcFile class can be used for parsing /proc files: + + cpuinfo = ProcFile.new("cpuinfo") + cpuinfo[1]["model name"] + #=> "AMD Turion(tm) 64 X2 Mobile Technology TL-50" + +== Copying + + Copyright (C) 2008 Dag Odenhall + Licensed under the Academic Free License version 3.0 diff --git a/TODO b/TODO new file mode 100644 index 0000000..4cd4df4 --- /dev/null +++ b/TODO @@ -0,0 +1,10 @@ += Todo + +* Maybe auto-include scripts from ~/.amazing/something +* Self-documenting widgets (list fields and options) (done in widgets) +* Some widgets need to support multiple data sources +* Some way to do alerts, e.g. "blinking" +* Make widget configuration screen specific +* Support widgets with multiple bars and graphs (maybe wait for 2.3) +* Maybe keep custom widget options at same level as other options +* More widgets, duh diff --git a/amazing b/amazing new file mode 100755 index 0000000..1cdd052 --- /dev/null +++ b/amazing @@ -0,0 +1,6 @@ +#!/bin/sh + +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +ruby -I `dirname $0`/lib `dirname $0`/bin/amazing $* diff --git a/amazing.rb b/amazing.rb deleted file mode 100755 index f51d713..0000000 --- a/amazing.rb +++ /dev/null @@ -1,648 +0,0 @@ -#!/usr/bin/env ruby - -# -# = amazing -# -# an amazing widget manager for an awesome window manager -# -# Usage: amazing [options] -# -c, --config FILE Configuration file (~/.amazing.yml) -# -s, --screen ID Screen ID (0) -# -l, --log-level LEVEL Severity threshold (info) -# -i, --include SCRIPT Include a widgets script -# -u, --update WIDGET Update a widget and exit -# -w, --list-widgets List available widgets -# -h, --help You're looking at it -# -# == Widgets -# -# * Battery: Remaining battery power in percentage -# * Maildir: Mail count in maildirs -# * ALSA: Various data for the ALSA mixer -# * Raggle: Unread posts in raggle -# * Memory: Various memory related data -# * Clock: Displays date and time -# -# == Configuration -# -# include: -# - list -# - of -# - scripts -# screens: -# - list -# - of -# - screens -# widgets: -# identifier: -# type: WidgetName -# every: seconds -# format: ruby code -# options: -# widget: foo -# specific: bar -# -# == Example -# -# widgets: -# pb_bat: -# type: Battery -# every: 10 -# tb_time: -# type: Clock -# every: 1 -# options: -# time_format: %T -# tb_mail: -# type: Maildir -# options: -# directories: -# - Mail/**/new -# - Mail/inbox/cur -# -# In this example tb_mail doesn't have an "every" setting and is instead -# updated manually with amazing -u tb_mail, perhaps in cron after fetching -# new mail via fdm, getmail, fetchmail or similar. A good idea is also to -# update after closing your MUA such as Mutt which could be done with -# shell functions, example: -# -# mutt() { -# mutt $* -# amazing -u tb_mail -# } -# -# == Writing widgets -# -# TODO: describe this more completely -# -# Example widget: -# -# class Clock < Widget -# description "Displays date and time" -# dependency "some/library", "how to get the library (url, gem name...)" -# option :time_format, "Time format as described in DATE(1)", "%R" -# field :time, "Formatted time" -# default "@time" -# -# init do -# @time = Time.now.strftime(@time_format) -# raise WidgetError, "An error occured!" if some_error? -# end -# end -# -# The ProcFile class can be used for parsing /proc files: -# -# cpuinfo = ProcFile.new("cpuinfo") -# cpuinfo[1]["model name"] -# #=> "AMD Turion(tm) 64 X2 Mobile Technology TL-50" -# -# == Todo -# -# * Maybe auto-include scripts from ~/.amazing/something -# * Self-documenting widgets (list fields and options) (done in widgets) -# * Some widgets need to support multiple data sources -# * Some way to do alerts, e.g. "blinking" -# * Make widget configuration screen specific -# * Support widgets with multiple bars and graphs (maybe wait for 2.3) -# * Maybe keep custom widget options at same level as other options -# * More widgets, duh -# -# == Copying -# -# Copyright (C) 2008 Dag Odenhall -# Licensed under the Academic Free License version 3.0 -# http://www.rosenlaw.com/AFL3.0.htm -# - -require 'optparse' -require 'logger' -require 'yaml' -require 'timeout' -require 'thread' -require 'socket' - -module Amazing - - module X11 - - # Raised by DisplayName#new if called with empty argument, or without - # argument and ENV["DISPLAY"] is empty. - class EmptyDisplayName < ArgumentError - end - - # Raised by DisplayName#new if format of argument or ENV["DISPLAY"] is - # invalid. - class InvalidDisplayName < ArgumentError - end - - # Parse an X11 display name - # - # display = DisplayName.new("hostname:displaynumber.screennumber") - # display.hostname #=> "hostname" - # display.display #=> "displaynumber" - # display.screen #=> "screennumber" - # - # Without arguments, reads ENV["DISPLAY"]. With empty argument or - # DISPLAY environment, raises EmptyDisplayName. With invalid display name - # format, raises InvalidDisplayName. - class DisplayName - attr_reader :hostname, :display, :screen - - def initialize(display_name=ENV["DISPLAY"]) - raise EmptyDisplayName, "No display name supplied" if ["", nil].include? display_name - @hostname, @display, @screen = display_name.scan(/^(.*):(\d+)(?:\.(\d+))?$/)[0] - raise InvalidDisplayName, "Invalid display name" if @display.nil? - @hostname = "localhost" if @hostname.empty? - @screen = "0" unless @screen - end - end - end - - # Communicate with awesome - # - # awesome = Awesome.new - # awesome.widget_tell(widget_id, "Hello, world") - # awesome = Awesome.new(1) - # awesome.tag_view(3) - # Awesome.new.client_zoom - class Awesome - attr_accessor :screen, :display - - def initialize(screen=0, display=0) - @screen = screen.to_i - @display = display - @socket = Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM, 0) - @socket.connect(Socket.sockaddr_un("#{ENV["HOME"]}/.awesome_ctl.#@display")) - end - - def method_missing(method, *args) - @socket.write("#@screen #{method} #{args.join(' ')}\n") - end - end - - # Parse a /proc file - # - # cpuinfo = ProcFile.new("cpuinfo") - # cpuinfo[1]["model name"] - # #=> "AMD Turion(tm) 64 X2 Mobile Technology TL-50" - class ProcFile - include Enumerable - - def initialize(file) - file = "/proc/#{file}" if file[0] != ?/ - @list = [{}] - File.readlines(file).each do |line| - if sep = line.index(":") - @list[-1][line[0..sep-1].strip] = line[sep+1..-1].strip - else - @list << {} - end - end - @list.pop if @list[-1].empty? - end - - def each - @list.each do |section| - yield section - end - end - - def [](section) - @list[section] - end - end - - # Raised by widgets, and is then rescued and logged - class WidgetError < Exception - end - - # Parent class for widget construction, example: - # - # class Clock < Widget - # description "Displays date and time" - # dependency "some/library", "how to get the library (url, gem name...)" - # option :time_format, "Time format as described in DATE(1)", "%R" - # field :time, "Formatted time" - # default "@time" - # - # init do - # @time = Time.now.strftime(@time_format) - # raise WidgetError, "An error occured!" if some_error? - # end - # end - class Widget - def initialize(identifier=nil, format=nil, opts={}) - self.class.dependencies.each do |name, description| - begin - require name - rescue LoadError - raise WidgetError, "Missing dependency #{name.inspect}#{if description then " [#{description}]" end}" - end - end - @identifier, @format = identifier, format - self.class.options.each do |key, value| - value = opts[key.to_s] || value[:default] - instance_variable_set "@#{key}".to_sym, value - end - self.class.fields.each do |key, value| - instance_variable_set "@#{key}".to_sym, value[:default] - end - instance_eval(&self.class.init) if self.class.init - end - - def self.description(description=nil) - if description - @description = description - else - @description - end - end - - def self.dependency(name, description=nil) - @dependencies ||= {} - @dependencies[name] = description - end - - def self.dependencies - @dependencies || {} - end - - def self.option(name, description=nil, default=nil) - @options ||= {} - @options[name] = {:description => description, :default => default} - end - - def self.options - @options || {} - end - - def self.field(name, description=nil, default=nil) - @fields ||= {} - @fields[name] = {:description => description, :default => default} - end - - def self.fields - @fields || {} - end - - def self.default(format=nil, &block) - if format - @default = format - elsif block - @default = block - else - @default - end - end - - def self.init(&block) - if block - @init = block - else - @init - end - end - - def formatize - if @format - instance_eval(@format) - else - case self.class.default - when Proc - instance_eval(&self.class.default) - when String - instance_eval(self.class.default) - end - end - end - end - - module Widgets - class ALSA < Widget - description "Various data for the ALSA mixer" - option :mixer, "ALSA mixer name", "Master" - field :volume, "Volume in percentage", 0 - default "@volume" - - init do - IO.popen("amixer get #@mixer", IO::RDONLY) do |am| - out = am.read - volumes = out.scan(/\[(\d+)%\]/).flatten - volumes.each {|vol| @volume += vol.to_i } - @volume = @volume / volumes.size - end - end - end - - class Battery < Widget - description "Remaining battery power in percentage" - option :battery, "Battery number", 1 - field :percentage, "Power percentage", 0 - default "@percentage" - - init do - batinfo = ProcFile.new("acpi/battery/BAT#@battery/info")[0] - batstate = ProcFile.new("acpi/battery/BAT#@battery/state")[0] - remaining = batstate["remaining capacity"].to_i - lastfull = batinfo["last full capacity"].to_i - @percentage = (remaining * 100) / lastfull.to_f - end - end - - class Clock < Widget - description "Displays date and time" - option :time_format, "Time format as described in DATE(1)", "%R" - field :time, "Formatted time" - default "@time" - - init do - @time = Time.now.strftime(@time_format) - end - end - - class Maildir < Widget - description "Mail count in maildirs" - option :directories, "Globs of maildirs" # TODO: does a default make sense? - field :count, "Ammount of mail in searched directories", 0 - default "@count" - - init do - raise WidgetError, "No directories configured" unless @directories - @directories.each do |glob| - glob = "#{ENV["HOME"]}/#{glob}" if glob[0] != ?/ - @count += Dir["#{glob}/*"].size - end - end - end - - class Memory < Widget - description "Various memory related data" - field :total, "Total kilobytes of memory", 0 - field :free, "Free kilobytes of memory", 0 - field :buffers, nil, 0 # TODO: description - field :cached, nil, 0 # TODO: description - field :usage, "Percentage of used memory", 0 - default "@usage" - - init do - meminfo = ProcFile.new("meminfo")[0] - @total = meminfo["MemTotal"].to_i - @free = meminfo["MemFree"].to_i - @buffers = meminfo["Buffers"].to_i - @cached = meminfo["Cached"].to_i - @usage = ((@total - @free - @cached - @buffers) * 100) / @total.to_f - end - end - - class Raggle < Widget - description "Unread posts in raggle" - dependency "pstore", "Ruby standard library" - option :feed_list_path, "Path to feeds list", ".raggle/feeds.yaml" - option :feed_cache_path, "Path to feeds cache", ".raggle/feed_cache.store" - field :count, "Ammount of unread posts", 0 - default "@count" - - init do - @feed_list_path = "#{ENV["HOME"]}/#@feed_list_path" if @feed_list_path[0] != ?/ - feeds = YAML.load_file(@feed_list_path) - @feed_cache_path = "#{ENV["HOME"]}/#{@feed_cache_path}" if @feed_cache_path[0] != ?/ - cache = PStore.new(@feed_cache_path) - cache.transaction(false) do - feeds.each do |feed| - cache[feed["url"]].each do |item| - @count += 1 unless item["read?"] - end - end - end - end - end - end - - # Parse and manage command line options - class Options - include Enumerable - - def initialize(args) - @options = {} - @options[:config] = "#{ENV["HOME"]}/.amazing.yml" - @options[:screens] = [] - @options[:loglevel] = "info" - @options[:include] = [] - @options[:update] = [] - @args = args - @parser = OptionParser.new do |opts| - opts.on("-c", "--config FILE", "Configuration file (~/.amazing.yml)") do |config| - @options[:config] = config - end - opts.on("-s", "--screen ID", "Screen ID (0)") do |screen| - @options[:screens] << screen - end - opts.on("-l", "--log-level LEVEL", "Severity threshold (info)") do |level| - @options[:loglevel] = level - end - opts.on("-i", "--include SCRIPT", "Include a widgets script") do |script| - @options[:include] << script - end - opts.on("-u", "--update WIDGET", "Update a widget and exit") do |widget| - @options[:update] << widget - end - opts.on("-w", "--list-widgets", "List available widgets") do - @options[:listwidgets] = true - end - opts.on("-h", "--help", "You're looking at it") do - @options[:help] = true - end - end - end - - def each - @options.keys.each do |key| - yield key - end - end - - def parse(args=@args) - @parser.parse!(args) - end - - def help - @parser.help - end - - def [](option) - @options[option] - end - - def []=(option, value) - @options[option] = value - end - end - - # Command line interface runner - # - # CLI.run(ARGV) - class CLI - def initialize(args) - @args = args - @log = Logger.new(STDOUT) - @options = Options.new(@args) - begin - @display = X11::DisplayName.new - rescue X11::EmptyDisplayName => e - @log.warn("#{e.message}, falling back on :0") - @display = X11::DisplayName.new(":0") - rescue X11::InvalidDisplayName => e - @log.fatal("#{e.message}, exiting") - exit 1 - end - end - - def run - trap("SIGINT") do - @log.fatal("Received SIGINT, exiting") - exit - end - @options.parse - show_help if @options[:help] - set_loglevel - parse_config - load_scripts - list_widgets if @options[:listwidgets] - setup_screens - wait_for_sockets - explicit_updates unless @options[:update].empty? - update_non_interval - count = 0 - loop do - @config["widgets"].each do |widget_name, settings| - if settings["every"] && count % settings["every"] == 0 - update_widget(widget_name) - end - end - count += 1 - sleep 1 - end - end - - private - - def show_help - puts @options.help - exit - end - - def set_loglevel - begin - @log.level = Logger.const_get(@options[:loglevel].upcase) - rescue NameError - @log.error("Unsupported log level #{@options[:loglevel].inspect}") - @log.level = Logger::INFO - end - end - - def load_scripts - scripts = @options[:include] - @config["include"].each do |script| - script = "#{File.dirname(@options[:config])}/#{script}" if script[0] != ?/ - scripts << script - end - scripts.each do |script| - if File.exist?(script) - Widgets.module_eval(File.read(script)) - else - @log.error("No such widget script #{script.inspect}") - end - end - end - - def list_widgets - Widgets.constants.each do |widget| - if description = Widgets.const_get(widget).description - puts "#{widget}: #{description}" - else - puts widget - end - end - exit - end - - def parse_config - @log.debug("Parsing configuration file") - begin - @config = YAML.load_file(@options[:config]) - rescue - @log.fatal("Unable to parse configuration file, exiting") - exit 1 - end - @config["include"] ||= [] - @config["screens"] ||= [] - end - - def setup_screens - @screens = {} - @options[:screens].each do |screen| - @screens[screen.to_i] = Awesome.new(screen, @display.display) - end - if @screens.empty? - @config["screens"].each do |screen| - @screens[screen] = Awesome.new(screen, @display.display) - end - end - @screens[0] = Awesome.new if @screens.empty? - end - - def wait_for_sockets - @log.debug("Waiting for awesome control socket for display #{@display.display}") - begin - Timeout.timeout(30) do - sleep 1 until File.exist?("#{ENV["HOME"]}/.awesome_ctl.#{@display.display}") - @log.debug("Got socket for display #{@display.display}") - end - rescue Timeout::Error - @log.fatal("Socket for display #{@display.display} not created within 30 seconds, exiting") - exit 1 - end - end - - def update_non_interval - @config["widgets"].each do |widget_name, settings| - next if settings["every"] - update_widget(widget_name) - end - end - - def explicit_updates - @config["widgets"].each_key do |widget_name| - next unless @options[:update].include? widget_name - update_widget(widget_name, false) - end - exit - end - - def update_widget(widget_name, threaded=true) - settings = @config["widgets"][widget_name] - begin - @screens.each do |screen, awesome| - @log.debug("Updating widget #{widget_name} of type #{settings["type"]} on screen #{screen}") - opts = settings["options"] || {} - field = settings["field"] || "default" - update = Proc.new do - widget = Widgets.const_get(settings["type"]).new(widget_name, settings["format"], opts) - awesome.widget_tell(widget_name, widget.formatize) - end - if threaded - Thread.new &update - else - update.call - end - end - rescue WidgetError => e - @log.error(settings["type"]) { e.message } - end - end - end -end - -if $0 == __FILE__ - Amazing::CLI.new(ARGV).run -end diff --git a/bin/amazing b/bin/amazing new file mode 100755 index 0000000..a9ead3c --- /dev/null +++ b/bin/amazing @@ -0,0 +1,10 @@ +#!/usr/bin/env ruby + +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/cli' + +if $0 == __FILE__ + Amazing::CLI.new(ARGV).run +end diff --git a/lib/amazing.rb b/lib/amazing.rb new file mode 100644 index 0000000..c11bf47 --- /dev/null +++ b/lib/amazing.rb @@ -0,0 +1,10 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/x11' +require 'amazing/awesome' +require 'amazing/proc_file' +require 'amazing/widget' +require 'amazing/widgets' +require 'amazing/options' +require 'amazing/cli' diff --git a/lib/amazing/awesome.rb b/lib/amazing/awesome.rb new file mode 100644 index 0000000..0287f88 --- /dev/null +++ b/lib/amazing/awesome.rb @@ -0,0 +1,29 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'socket' + +module Amazing + + # Communicate with awesome + # + # awesome = Awesome.new + # awesome.widget_tell(widget_id, "Hello, world") + # awesome = Awesome.new(1) + # awesome.tag_view(3) + # Awesome.new.client_zoom + class Awesome + attr_accessor :screen, :display + + def initialize(screen=0, display=0) + @screen = screen.to_i + @display = display + @socket = Socket.new(Socket::AF_UNIX, Socket::SOCK_DGRAM, 0) + @socket.connect(Socket.sockaddr_un("#{ENV["HOME"]}/.awesome_ctl.#@display")) + end + + def method_missing(method, *args) + @socket.write("#@screen #{method} #{args.join(' ')}\n") + end + end +end diff --git a/lib/amazing/cli.rb b/lib/amazing/cli.rb new file mode 100644 index 0000000..3f88745 --- /dev/null +++ b/lib/amazing/cli.rb @@ -0,0 +1,180 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'logger' +require 'amazing/options' +require 'amazing/x11/display_name' +require 'yaml' +require 'amazing/widget' +require 'amazing/proc_file' +require 'amazing/widgets' +require 'amazing/awesome' +require 'timeout' +require 'thread' + +module Amazing + + # Command line interface runner + # + # CLI.run(ARGV) + class CLI + def initialize(args) + @args = args + @log = Logger.new(STDOUT) + @options = Options.new(@args) + begin + @display = X11::DisplayName.new + rescue X11::EmptyDisplayName => e + @log.warn("#{e.message}, falling back on :0") + @display = X11::DisplayName.new(":0") + rescue X11::InvalidDisplayName => e + @log.fatal("#{e.message}, exiting") + exit 1 + end + end + + def run + trap("SIGINT") do + @log.fatal("Received SIGINT, exiting") + exit + end + @options.parse + show_help if @options[:help] + set_loglevel + parse_config + load_scripts + list_widgets if @options[:listwidgets] + setup_screens + wait_for_sockets + explicit_updates unless @options[:update].empty? + update_non_interval + count = 0 + loop do + @config["widgets"].each do |widget_name, settings| + if settings["every"] && count % settings["every"] == 0 + update_widget(widget_name) + end + end + count += 1 + sleep 1 + end + end + + private + + def show_help + puts @options.help + exit + end + + def set_loglevel + begin + @log.level = Logger.const_get(@options[:loglevel].upcase) + rescue NameError + @log.error("Unsupported log level #{@options[:loglevel].inspect}") + @log.level = Logger::INFO + end + end + + def load_scripts + scripts = @options[:include] + @config["include"].each do |script| + script = "#{File.dirname(@options[:config])}/#{script}" if script[0] != ?/ + scripts << script + end + scripts.each do |script| + if File.exist?(script) + Widgets.module_eval(File.read(script)) + else + @log.error("No such widget script #{script.inspect}") + end + end + end + + def list_widgets + Widgets.constants.each do |widget| + if description = Widgets.const_get(widget).description + puts "#{widget}: #{description}" + else + puts widget + end + end + exit + end + + def parse_config + @log.debug("Parsing configuration file") + begin + @config = YAML.load_file(@options[:config]) + rescue + @log.fatal("Unable to parse configuration file, exiting") + exit 1 + end + @config["include"] ||= [] + @config["screens"] ||= [] + end + + def setup_screens + @screens = {} + @options[:screens].each do |screen| + @screens[screen.to_i] = Awesome.new(screen, @display.display) + end + if @screens.empty? + @config["screens"].each do |screen| + @screens[screen] = Awesome.new(screen, @display.display) + end + end + @screens[0] = Awesome.new if @screens.empty? + end + + def wait_for_sockets + @log.debug("Waiting for awesome control socket for display #{@display.display}") + begin + Timeout.timeout(30) do + sleep 1 until File.exist?("#{ENV["HOME"]}/.awesome_ctl.#{@display.display}") + @log.debug("Got socket for display #{@display.display}") + end + rescue Timeout::Error + @log.fatal("Socket for display #{@display.display} not created within 30 seconds, exiting") + exit 1 + end + end + + def update_non_interval + @config["widgets"].each do |widget_name, settings| + next if settings["every"] + update_widget(widget_name) + end + end + + def explicit_updates + @config["widgets"].each_key do |widget_name| + next unless @options[:update].include? widget_name + update_widget(widget_name, false) + end + exit + end + + def update_widget(widget_name, threaded=true) + settings = @config["widgets"][widget_name] + begin + @screens.each do |screen, awesome| + @log.debug("Updating widget #{widget_name} of type #{settings["type"]} on screen #{screen}") + opts = settings["options"] || {} + field = settings["field"] || "default" + update = Proc.new do + widget = Widgets.const_get(settings["type"]).new(widget_name, settings["format"], opts) + awesome.widget_tell(widget_name, widget.formatize) + end + if threaded + Thread.new &update + else + update.call + end + end + rescue WidgetError => e + @log.error(settings["type"]) { e.message } + end + end + end +end diff --git a/lib/amazing/options.rb b/lib/amazing/options.rb new file mode 100644 index 0000000..ca994ce --- /dev/null +++ b/lib/amazing/options.rb @@ -0,0 +1,67 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'optparse' + +module Amazing + + # Parse and manage command line options + class Options + include Enumerable + + def initialize(args) + @options = {} + @options[:config] = "#{ENV["HOME"]}/.amazing.yml" + @options[:screens] = [] + @options[:loglevel] = "info" + @options[:include] = [] + @options[:update] = [] + @args = args + @parser = OptionParser.new do |opts| + opts.on("-c", "--config FILE", "Configuration file (~/.amazing.yml)") do |config| + @options[:config] = config + end + opts.on("-s", "--screen ID", "Screen ID (0)") do |screen| + @options[:screens] << screen + end + opts.on("-l", "--log-level LEVEL", "Severity threshold (info)") do |level| + @options[:loglevel] = level + end + opts.on("-i", "--include SCRIPT", "Include a widgets script") do |script| + @options[:include] << script + end + opts.on("-u", "--update WIDGET", "Update a widget and exit") do |widget| + @options[:update] << widget + end + opts.on("-w", "--list-widgets", "List available widgets") do + @options[:listwidgets] = true + end + opts.on("-h", "--help", "You're looking at it") do + @options[:help] = true + end + end + end + + def each + @options.keys.each do |key| + yield key + end + end + + def parse(args=@args) + @parser.parse!(args) + end + + def help + @parser.help + end + + def [](option) + @options[option] + end + + def []=(option, value) + @options[option] = value + end + end +end diff --git a/lib/amazing/proc_file.rb b/lib/amazing/proc_file.rb new file mode 100644 index 0000000..3b921fc --- /dev/null +++ b/lib/amazing/proc_file.rb @@ -0,0 +1,37 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +module Amazing + + # Parse a /proc file + # + # cpuinfo = ProcFile.new("cpuinfo") + # cpuinfo[1]["model name"] + # #=> "AMD Turion(tm) 64 X2 Mobile Technology TL-50" + class ProcFile + include Enumerable + + def initialize(file) + file = "/proc/#{file}" if file[0] != ?/ + @list = [{}] + File.readlines(file).each do |line| + if sep = line.index(":") + @list[-1][line[0..sep-1].strip] = line[sep+1..-1].strip + else + @list << {} + end + end + @list.pop if @list[-1].empty? + end + + def each + @list.each do |section| + yield section + end + end + + def [](section) + @list[section] + end + end +end diff --git a/lib/amazing/widget.rb b/lib/amazing/widget.rb new file mode 100644 index 0000000..5a0a056 --- /dev/null +++ b/lib/amazing/widget.rb @@ -0,0 +1,110 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +module Amazing + + # Raised by widgets, and is then rescued and logged + class WidgetError < Exception + end + + # Parent class for widget construction, example: + # + # class Clock < Widget + # description "Displays date and time" + # dependency "some/library", "how to get the library (url, gem name...)" + # option :time_format, "Time format as described in DATE(1)", "%R" + # field :time, "Formatted time" + # default "@time" + # + # init do + # @time = Time.now.strftime(@time_format) + # raise WidgetError, "An error occured!" if some_error? + # end + # end + class Widget + def initialize(identifier=nil, format=nil, opts={}) + self.class.dependencies.each do |name, description| + begin + require name + rescue LoadError + raise WidgetError, "Missing dependency #{name.inspect}#{if description then " [#{description}]" end}" + end + end + @identifier, @format = identifier, format + self.class.options.each do |key, value| + value = opts[key.to_s] || value[:default] + instance_variable_set "@#{key}".to_sym, value + end + self.class.fields.each do |key, value| + instance_variable_set "@#{key}".to_sym, value[:default] + end + instance_eval(&self.class.init) if self.class.init + end + + def self.description(description=nil) + if description + @description = description + else + @description + end + end + + def self.dependency(name, description=nil) + @dependencies ||= {} + @dependencies[name] = description + end + + def self.dependencies + @dependencies || {} + end + + def self.option(name, description=nil, default=nil) + @options ||= {} + @options[name] = {:description => description, :default => default} + end + + def self.options + @options || {} + end + + def self.field(name, description=nil, default=nil) + @fields ||= {} + @fields[name] = {:description => description, :default => default} + end + + def self.fields + @fields || {} + end + + def self.default(format=nil, &block) + if format + @default = format + elsif block + @default = block + else + @default + end + end + + def self.init(&block) + if block + @init = block + else + @init + end + end + + def formatize + if @format + instance_eval(@format) + else + case self.class.default + when Proc + instance_eval(&self.class.default) + when String + instance_eval(self.class.default) + end + end + end + end +end diff --git a/lib/amazing/widgets.rb b/lib/amazing/widgets.rb new file mode 100644 index 0000000..e604bef --- /dev/null +++ b/lib/amazing/widgets.rb @@ -0,0 +1,14 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/widgets/alsa' +require 'amazing/widgets/battery' +require 'amazing/widgets/clock' +require 'amazing/widgets/maildir' +require 'amazing/widgets/memory' +require 'amazing/widgets/raggle' + +module Amazing + module Widgets + end +end diff --git a/lib/amazing/widgets/alsa.rb b/lib/amazing/widgets/alsa.rb new file mode 100644 index 0000000..f653ea5 --- /dev/null +++ b/lib/amazing/widgets/alsa.rb @@ -0,0 +1,24 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/widget' + +module Amazing + module Widgets + class ALSA < Widget + description "Various data for the ALSA mixer" + option :mixer, "ALSA mixer name", "Master" + field :volume, "Volume in percentage", 0 + default "@volume" + + init do + IO.popen("amixer get #@mixer", IO::RDONLY) do |am| + out = am.read + volumes = out.scan(/\[(\d+)%\]/).flatten + volumes.each {|vol| @volume += vol.to_i } + @volume = @volume / volumes.size + end + end + end + end +end diff --git a/lib/amazing/widgets/battery.rb b/lib/amazing/widgets/battery.rb new file mode 100644 index 0000000..8a2a8f4 --- /dev/null +++ b/lib/amazing/widgets/battery.rb @@ -0,0 +1,24 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/widget' +require 'amazing/proc_file' + +module Amazing + module Widgets + class Battery < Widget + description "Remaining battery power in percentage" + option :battery, "Battery number", 1 + field :percentage, "Power percentage", 0 + default "@percentage" + + init do + batinfo = ProcFile.new("acpi/battery/BAT#@battery/info")[0] + batstate = ProcFile.new("acpi/battery/BAT#@battery/state")[0] + remaining = batstate["remaining capacity"].to_i + lastfull = batinfo["last full capacity"].to_i + @percentage = (remaining * 100) / lastfull.to_f + end + end + end +end diff --git a/lib/amazing/widgets/clock.rb b/lib/amazing/widgets/clock.rb new file mode 100644 index 0000000..febcaf3 --- /dev/null +++ b/lib/amazing/widgets/clock.rb @@ -0,0 +1,19 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/widget' + +module Amazing + module Widgets + class Clock < Widget + description "Displays date and time" + option :time_format, "Time format as described in DATE(1)", "%R" + field :time, "Formatted time" + default "@time" + + init do + @time = Time.now.strftime(@time_format) + end + end + end +end diff --git a/lib/amazing/widgets/maildir.rb b/lib/amazing/widgets/maildir.rb new file mode 100644 index 0000000..c3257a9 --- /dev/null +++ b/lib/amazing/widgets/maildir.rb @@ -0,0 +1,23 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/widget' + +module Amazing + module Widgets + class Maildir < Widget + description "Mail count in maildirs" + option :directories, "Globs of maildirs" # TODO: does a default make sense? + field :count, "Ammount of mail in searched directories", 0 + default "@count" + + init do + raise WidgetError, "No directories configured" unless @directories + @directories.each do |glob| + glob = "#{ENV["HOME"]}/#{glob}" if glob[0] != ?/ + @count += Dir["#{glob}/*"].size + end + end + end + end +end diff --git a/lib/amazing/widgets/memory.rb b/lib/amazing/widgets/memory.rb new file mode 100644 index 0000000..55df5b3 --- /dev/null +++ b/lib/amazing/widgets/memory.rb @@ -0,0 +1,28 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/widget' +require 'amazing/proc_file' + +module Amazing + module Widgets + class Memory < Widget + description "Various memory related data" + field :total, "Total kilobytes of memory", 0 + field :free, "Free kilobytes of memory", 0 + field :buffers, nil, 0 # TODO: description + field :cached, nil, 0 # TODO: description + field :usage, "Percentage of used memory", 0 + default "@usage" + + init do + meminfo = ProcFile.new("meminfo")[0] + @total = meminfo["MemTotal"].to_i + @free = meminfo["MemFree"].to_i + @buffers = meminfo["Buffers"].to_i + @cached = meminfo["Cached"].to_i + @usage = ((@total - @free - @cached - @buffers) * 100) / @total.to_f + end + end + end +end diff --git a/lib/amazing/widgets/raggle.rb b/lib/amazing/widgets/raggle.rb new file mode 100644 index 0000000..a625abf --- /dev/null +++ b/lib/amazing/widgets/raggle.rb @@ -0,0 +1,31 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/widget' + +module Amazing + module Widgets + class Raggle < Widget + description "Unread posts in raggle" + dependency "pstore", "Ruby standard library" + option :feed_list_path, "Path to feeds list", ".raggle/feeds.yaml" + option :feed_cache_path, "Path to feeds cache", ".raggle/feed_cache.store" + field :count, "Ammount of unread posts", 0 + default "@count" + + init do + @feed_list_path = "#{ENV["HOME"]}/#@feed_list_path" if @feed_list_path[0] != ?/ + feeds = YAML.load_file(@feed_list_path) + @feed_cache_path = "#{ENV["HOME"]}/#{@feed_cache_path}" if @feed_cache_path[0] != ?/ + cache = PStore.new(@feed_cache_path) + cache.transaction(false) do + feeds.each do |feed| + cache[feed["url"]].each do |item| + @count += 1 unless item["read?"] + end + end + end + end + end + end +end diff --git a/lib/amazing/x11.rb b/lib/amazing/x11.rb new file mode 100644 index 0000000..d4de1c9 --- /dev/null +++ b/lib/amazing/x11.rb @@ -0,0 +1,4 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +require 'amazing/x11/display_name' diff --git a/lib/amazing/x11/display_name.rb b/lib/amazing/x11/display_name.rb new file mode 100644 index 0000000..d0e28b6 --- /dev/null +++ b/lib/amazing/x11/display_name.rb @@ -0,0 +1,39 @@ +# Copyright (C) 2008 Dag Odenhall +# Licensed under the Academic Free License version 3.0 + +module Amazing + module X11 + + # Raised by DisplayName#new if called with empty argument, or without + # argument and ENV["DISPLAY"] is empty. + class EmptyDisplayName < ArgumentError + end + + # Raised by DisplayName#new if format of argument or ENV["DISPLAY"] is + # invalid. + class InvalidDisplayName < ArgumentError + end + + # Parse an X11 display name + # + # display = DisplayName.new("hostname:displaynumber.screennumber") + # display.hostname #=> "hostname" + # display.display #=> "displaynumber" + # display.screen #=> "screennumber" + # + # Without arguments, reads ENV["DISPLAY"]. With empty argument or + # DISPLAY environment, raises EmptyDisplayName. With invalid display name + # format, raises InvalidDisplayName. + class DisplayName + attr_reader :hostname, :display, :screen + + def initialize(display_name=ENV["DISPLAY"]) + raise EmptyDisplayName, "No display name supplied" if ["", nil].include? display_name + @hostname, @display, @screen = display_name.scan(/^(.*):(\d+)(?:\.(\d+))?$/)[0] + raise InvalidDisplayName, "Invalid display name" if @display.nil? + @hostname = "localhost" if @hostname.empty? + @screen = "0" unless @screen + end + end + end +end -- 2.11.4.GIT