# # calculator.py : A calculator module for the deskbar applet. # # Copyright (C) 2006 by Callum McKenzie # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. # # Authors: Callum McKenzie # from gettext import gettext as _ import deskbar.Handler, deskbar.Match import deskbar.Categories import cgi # This is evil since I strongly suspect this isn't meant to be public API. # However, I can't see a better way. deskbar.Categories.CATEGORIES["calculator"] = { "name" : _("Calculator") } HANDLERS = { "CalculatorHandler" : { "name" : _("Calculator"), "description" : _("Calculate simple equations"), "version" : "1.0", } } class CalculatorMatch (deskbar.Match.Match): def get_name (self, text=None): # I really think that deskbar should be doing the # escaping for us. escapedtext = cgi.escape (text) return { "name" : self.name, "escapedtext" : escapedtext } def get_verb (self): """We print out the entire equation.""" return "%(escapedtext)s = %(name)s" def get_category (self): return "calculator" class CalculatorHandler (deskbar.Handler.Handler): # This white list includes all the python mathemetical operators which # aren't comparison operators. Unfortunately >> contains >, so some slip # through. In fact the only missing operator in =. # What you get is a set of simple arithmetic and bitwise operators. No # math functions like abs, sqrt, sin, cos, etc. because I couldn't # think of a convenient way to check for them. whitelist = ".0123456789+-*/%<>&|^~() " def __init__ (self): deskbar.Handler.Handler.__init__ (self, "gtk-add") def query (self, query): """We evaluate the equation by first checking if all the characters are in our white list and then passing the result to python for evaluation. Any errors are ignored.""" try: for c in query: if c not in CalculatorHandler.whitelist: return [] answer = eval (query) return [ CalculatorMatch (self, name=answer)] except: return []