Theme rework - see the Changelog
[rox-lithium.git] / battery.py
blob06514042723a156af2a31872cb58a4af63036094
1 """
2 battery.py - A Battery Status Monitor for ROX
3 (based largely on Baroque by Tilo Riemer)
4 """
6 ############################################################################
7 ##
8 ## $Id: baroque.py,v 1.13 2004/01/08 04:26:11 rds Exp $
9 ##
10 ## Copyright (C) 2002-2003 Rds <rds@rdsarts.com> and
11 ## Tilo Riemer <riemer@lincvs.org>
12 ## All rights reserved.
14 ## Baroque is a merge of BatMonitor and the old Baroque
16 ## Redistribution and use in source and binary forms, with or without
17 ## modification, are permitted provided that the following conditions
18 ## are met:
20 ## 1. Redistributions of source code must retain the above copyright
21 ## notice, this list of conditions and the following disclaimer.
22 ## 2. Redistributions in binary form must reproduce the above copyright
23 ## notice, this list of conditions and the following disclaimer in the
24 ## documentation and/or other materials provided with the distribution.
25 ## 3. The name of the author may not be used to endorse or promote products
26 ## derived from this software without specific prior written permission.
28 ## THIS SOFTWARE IS PROVIDED BY THE AUTHOR `AS IS'' AND ANY EXPRESS OR
29 ## IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
30 ## OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
31 ## IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
32 ## INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
33 ## NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34 ## DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35 ## THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36 ## (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
37 ## THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
39 ###############################################################################
41 # standard library modules
42 import sys, os, time, gtk, gobject, rox
43 from rox import applet, filer, tasks
44 from rox.options import Option
46 # globals
47 APP_NAME = 'Battery'
48 APP_DIR = rox.app_dir
49 APP_SIZE = [28, 28]
51 # Options.xml processing
52 from rox import Menu
53 rox.setup_app_options(APP_NAME, site='hayber.us')
54 Menu.set_save_name(APP_NAME, site='hayber.us')
56 #Options go here
57 WARN = Option('warn', True)
58 WARN_LEVEL = Option('warn_level', 10)
59 TIMER = Option('timeout', "1000")
60 THEME = Option('theme', 'Color')
62 #Enable notification of options changes
63 rox.app_options.notify()
65 BATT_TYPE = -1 # 0 = ACPI, 1 = APM
67 # Initalize the battery object
68 try:
69 import acpi
70 BATTERY = acpi.Acpi()
71 BATT_TYPE = 0
72 OFFLINE = acpi.OFFLINE
73 except (ImportError, NotImplementedError, EnvironmentError):
74 try:
75 import pmu #for PowerMac support
76 BATTERY = pmu.Pmu()
77 BATT_TYPE = 1
78 OFFLINE = pmu.OFFLINE
79 except (ImportError, NotImplementedError, EnvironmentError):
80 try:
81 import apm
82 BATTERY = apm.Apm()
83 BATT_TYPE = 1
84 OFFLINE = apm.OFFLINE
85 except (ImportError, NotImplementedError, EnvironmentError):
86 rox.croak(_("Sorry, but we could not load a Power Management module. Your system is not configured with power management support."))
89 class Battery(applet.Applet):
90 """A Battery Status Monitor Applet"""
92 warned = False
93 msg = 0
94 vertical = False
96 def __init__(self, id):
97 """Initialize applet."""
98 applet.Applet.__init__(self, id)
100 # load the applet icon
101 self.image = gtk.Image()
102 self.load_icons()
103 self.pixbuf = self.images[0]
104 self.image.set_from_pixbuf(self.pixbuf)
105 self.resize_image(8)
106 self.add(self.image)
108 self.vertical = self.get_panel_orientation() in ('Right', 'Left')
109 if self.vertical:
110 self.set_size_request(8, -1)
111 else:
112 self.set_size_request(-1, 8)
114 # set the tooltip
115 self.tooltips = gtk.Tooltips()
117 # menus
118 self.build_appmenu()
120 # event handling
121 self.add_events(gtk.gdk.BUTTON_PRESS_MASK)
122 self.connect('button-press-event', self.button_press)
123 self.connect('size-allocate', self.resize)
124 self.connect('delete_event', self.quit)
125 rox.app_options.add_notify(self.get_options)
127 # user adjustable timer to control how often hardware is polled
128 self.timer = gobject.timeout_add(int(TIMER.int_value) * 100, self.update_display)
130 # a fixed timer to toggle the tooltip between status and time remaining
131 gobject.timeout_add(5000, self.update_tooltip)
133 self.update_display()
134 self.update_tooltip()
135 self.show()
137 def load_icons(self):
138 """load the icons for the selected theme"""
139 theme = THEME.value
140 self.images = []
142 for name in [
143 'battery0',
144 'battery10', 'battery20', 'battery40', 'battery60',
145 'battery80', 'battery100',
146 'charging10', 'charging20', 'charging40', 'charging60',
147 'charging80', 'charging100',
149 self.images.append(gtk.gdk.pixbuf_new_from_file(os.path.join(rox.app_dir, 'themes', theme, name+'.svg')))
152 def update_display(self):
153 """Updates all the parts of our applet, and cleans it up if needed."""
154 BATTERY.update()
155 percent = BATTERY.percent()
157 if WARN.value == 'True':
158 if (BATTERY.charging_state() == OFFLINE and percent <= WARN_LEVEL.int_value):
159 if self.warned == False:
160 rox.info(_("Warning. Battery is currently at %d%%") % (BATTERY.percent(),))
161 self.warned = True
162 else:
163 self.warned = False
165 if percent == 0:
166 index = 0
167 elif percent < 20:
168 index = 1
169 elif percent < 40:
170 index = 2
171 elif percent < 60:
172 index = 3
173 elif percent < 80:
174 index = 4
175 elif percent < 100:
176 index = 5
177 else:
178 index = 6
180 if BATTERY.charging_state():
181 index += 6
183 pb = self.images[index]
184 self.pixbuf = pb
185 self.resize_image(self.size)
187 return 1 # to keep the timer going!
190 def update_tooltip(self):
191 self.tooltips.set_tip(self, self.status() + self.percent() + '%')
192 return 1 #to keep timer running
194 def status(self):
195 txt = _("Unknown")
196 BATTERY.update()
197 if BATTERY.charging_state() == 1:
198 txt = _("AC Online: ")
199 elif BATTERY.charging_state() == 2:
200 txt = _("Charging: ")
201 else:
202 # Discharing from the battery
203 if self.msg == 1:
204 self.msg = 0
205 txt = _("Battery: ")
206 else:
207 self.msg = 1
208 if BATT_TYPE == 1:
209 temp2 = BATTERY.time()
210 temp = int(temp2 / 60)
211 temp2 -= (temp * 60)
212 if temp < 0:
213 txt = _("Calculating... ")
214 else:
215 txt = "(%d:%02d) " % (temp, temp2)
216 else:
217 try:
218 temp = BATTERY.estimated_lifetime()
219 temp2 = int(60 * (temp - int(temp)))
220 txt = "(%d:%02d) " % (temp, temp2)
221 except ValueError:
222 txt = _("Charging")
223 return txt
225 def percent(self):
226 return str(BATTERY.percent())
228 def resize(self, widget, rectangle):
229 """Called when the panel sends a size."""
230 if self.vertical:
231 size = rectangle[2]
232 else:
233 size = rectangle[3]
234 if size != self.size:
235 self.resize_image(size)
237 def resize_image(self, size):
238 """Resize the application image."""
239 scaled_pixbuf = self.pixbuf.scale_simple(size, size, gtk.gdk.INTERP_BILINEAR)
240 self.image.set_from_pixbuf(scaled_pixbuf)
241 self.size = size
243 def button_press(self, window, event):
244 """Handle mouse clicks by popping up the matching menu."""
245 # if event.button == 1:
246 # self.run_it()
247 # if event.button == 2:
248 # self.checkit()
249 if event.button == 3:
250 self.appmenu.popup(self, event, self.position_menu)
252 def get_panel_orientation(self):
253 """ Return panel orientation and margin for displaying a popup menu.
254 Position in ('Top', 'Bottom', 'Left', 'Right').
256 pos = self.socket.property_get('_ROX_PANEL_MENU_POS', 'STRING', False)
257 if pos: pos = pos[2]
258 if pos:
259 side, margin = pos.split(',')
260 margin = int(margin)
261 else:
262 side, margin = None, 2
263 return side
265 def get_options(self, widget=None, rebuild=False, response=False):
266 """Used as the notify callback when options change."""
267 if THEME.has_changed:
268 self.load_icons()
269 self.update_display()
271 if TIMER.has_changed:
272 if self.timer: gobject.source_remove(self.timer)
273 self.timer = gobject.timeout_add(int(TIMER.int_value) * 100, self.update_display)
275 def show_options(self, button=None):
276 """Open the options edit dialog."""
277 rox.edit_options()
279 def get_info(self):
280 """Display an InfoWin self."""
281 from rox import InfoWin
282 InfoWin.infowin(APP_NAME)
284 def build_appmenu(self):
285 """Build the right-click app menu."""
286 items = []
287 items.append(Menu.Action(_('Info...'), 'get_info', '', gtk.STOCK_DIALOG_INFO))
288 items.append(Menu.Action(_('Options...'), 'show_options', '', gtk.STOCK_PREFERENCES))
289 items.append(Menu.Separator())
290 items.append(Menu.Action(_('Close'), 'quit', '', gtk.STOCK_CLOSE))
291 self.appmenu = Menu.Menu('other', items)
292 self.appmenu.attach(self, self)
294 def quit(self, *args):
295 """Quit applet and close everything."""
296 if self.timer: gobject.source_remove(self.timer)
297 self.destroy()