root / pykoticon / trunk / bin / pykoticon @ 79

Revision 79, 18.2 kB (checked in by jerome, 19 years ago)

Don't create a taskbar icon if the underlying wxPython doesn't feature
such a facility

  • Property svn:keywords set to Id
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# PyKotIcon - Windows System Tray Icon for PyKota
5#
6# (c) 2003-2004 Jerome Alet <alet@librelogiciel.com>
7# This program is free software; you can redistribute it and/or modify
8# it under the terms of the GNU General Public License as published by
9# the Free Software Foundation; either version 2 of the License, or
10# (at your option) any later version.
11#
12# This program is distributed in the hope that it will be useful,
13# but WITHOUT ANY WARRANTY; without even the implied warranty of
14# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15# GNU General Public License for more details.
16#
17# You should have received a copy of the GNU General Public License
18# along with this program; if not, write to the Free Software
19# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
20#
21# $Id$
22#
23#
24
25import sys
26import os
27import urllib
28import urllib2
29import locale
30import gettext
31
32if sys.platform == "win32" :
33    isWindows = 1
34    try :
35        import win32api
36    except ImportError :   
37        raise ImportError, "Mark Hammond's Win32 Extensions are missing. Please install them."
38    else :   
39        iconsdir = "."
40else :       
41    isWindows = 0
42    iconsdir = "/usr/share/pykoticon"   # TODO : change this
43    import pwd
44   
45try :   
46    import wxPython.wx
47    import wx
48    import wx.grid as gridlib
49    hasWxPython = 1
50except ImportError :   
51    hasWxPython = 0
52    raise ImportError, "wxPython is missing. Please install it."
53   
54#DUMPYKOTA_URL = "http://cgi.librelogiciel.com/cgi-bin/dumpykota.cgi"
55DUMPYKOTA_URL = "http://servmediup.unice.fr/cgi-bin/dumpykota.cgi"
56
57def getCurrentUserName() :
58    """Retrieves the current user's name."""
59    if isWindows :
60        return win32api.GetUserName()
61    else :   
62        try :
63            return pwd.getpwuid(os.geteuid())[0]
64        except :
65            return "** Unknown **"
66       
67class Printer :
68    """A class for PyKota Printers."""
69    def __init__(self, printername, priceperpage, priceperjob):
70        """Initialize printer datas."""
71        self.PrinterName = printername
72        try :
73            self.PricePerPage = float(priceperpage)
74        except (ValueError, TypeError) :
75            self.PricePerPage = 0.0
76        try :
77            self.PricePerJob = float(priceperjob)
78        except (ValueError, TypeError) :
79            self.PricePerJob = 0.0
80
81class UserQuota :
82    """A class for PyKota User Print Quota entries."""
83    def __init__(self, printername, pagecount, softlimit, hardlimit, datelimit):
84        """Initialize user print quota datas."""
85        self.PrinterName = printername
86        try :
87            self.PageCounter = int(pagecount)
88        except (ValueError, TypeError) :
89            self.PageCounter = 0
90        try :
91            self.SoftLimit = int(softlimit)
92        except (ValueError, TypeError) :
93            self.SoftLimit = None
94        try :
95            self.HardLimit = int(hardlimit)
96        except (ValueError, TypeError) :
97            self.HardLimit = None
98        self.DateLimit = datelimit
99       
100class User :
101    """A class for PyKota users."""
102    def __init__(self, username, userinfo, userquotas, printers) :
103        """Initialize user datas."""
104        self.UserName = username
105        self.LimitBy = userinfo["limitby"][0].lower()
106        try :
107            self.Balance = float(userinfo["balance"][0])
108        except (ValueError, TypeError) :
109            self.Balance = 0.0
110        try :
111            self.LifeTimePaid = float(userinfo["lifetimepaid"][0])
112        except (ValueError, TypeError) :
113            self.LifeTimePaid = 0.0
114        self.Printers = {}   
115        self.Quotas = {}
116        for i in range(len(userquotas["printername"])) :
117            printername = userquotas["printername"][i]
118            try :
119                pindex = printers["printername"].index(printername)
120            except (ValueError, KeyError) :
121                pass
122            else :   
123                self.Printers[printername] = Printer(printername, \
124                                              printers["priceperpage"][pindex],\
125                                              printers["priceperjob"][pindex])
126            pagecounter = userquotas["pagecounter"][i]
127            softlimit = userquotas["softlimit"][i]
128            hardlimit = userquotas["hardlimit"][i]
129            datelimit = userquotas["datelimit"][i]
130            self.Quotas[printername] = UserQuota(printername, pagecounter, \
131                                                   softlimit, hardlimit, \
132                                                              datelimit)
133           
134class CGINetworkInterface :
135    """A class for all network interactions."""
136    def __init__(self, cgiurl, authname=None, authpw=None) :
137        """Initialize CGI connection datas."""
138        self.cgiurl = cgiurl
139        self.authname = authname
140        self.authpw = authpw
141       
142    def retrieveDatas(self, arguments, fieldnames) :
143        """Retrieve datas from the CGI script."""
144        args = { "report" : 1,
145                 "format" : "csv",
146               } 
147        args.update(arguments)           
148        answer = {}
149        try :           
150            url = "%s?%s" % (self.cgiurl, urllib.urlencode(args))
151            u = urllib2.urlopen(url)
152            lines = u.readlines()
153        except IOError, msg :   
154            raise IOError, _("Unable to retrieve %s : %s") % (url, msg)
155        else :   
156            u.close()
157            try :
158                lines = [ line.strip().split(",") for line in lines ]
159                fields = [field[1:-1] for field in lines[0]]
160                indices = [fields.index(fname) for fname in fieldnames]
161                answer = dict([ (fieldname, \
162                                  [ line[fields.index(fieldname)][1:-1] \
163                                    for line in lines[1:] ]) \
164                                for fieldname in fieldnames ])
165            except :   
166                raise ValueError, _("Invalid datas retrieved from %s") % url
167        return answer
168       
169    def getPrinters(self) :
170        """Retrieve the printer's names."""
171        arguments = { "report" : 1,
172                      "format" : "csv",
173                      "datatype" : "printers",
174                    } 
175        return self.retrieveDatas(arguments, ["printername", "priceperpage", \
176                                              "priceperjob"])
177       
178    def getUser(self, username) :
179        """Retrieve the user's information."""
180        arguments = { "datatype" : "users",
181                      "filter" : "username=%s" % username,
182                    } 
183        return self.retrieveDatas(arguments, ("limitby", "balance", \
184                                                         "lifetimepaid"))
185       
186    def getUserPQuotas(self, username) :
187        """Retrieve the user's print quota information."""
188        arguments = { "datatype" : "upquotas",
189                      "filter" : "username=%s" % username,
190                    } 
191        return self.retrieveDatas(arguments, ("printername", "pagecounter", \
192                                              "softlimit", "hardlimit", \
193                                              "datelimit"))
194                                             
195    def getUserInfo(self, username) :
196        """Retrieves the user account and quota information."""
197        info = self.getUser(username)
198        if info :
199            quotas = self.getUserPQuotas(username)
200            return User(username, info, \
201                                  self.getUserPQuotas(username), \
202                                  self.getPrinters())
203   
204class PyKotIconGrid(gridlib.Grid) :   
205    """A class for user print quota entries."""
206    def __init__(self, parent, user) :
207        gridlib.Grid.__init__(self, parent, -1)
208        nbrows = len(user.Quotas.keys())
209        nbcols = 4
210        if user.LimitBy == "balance" :
211            nbrows += 1
212            nbcols -= 1
213        self.CreateGrid(nbrows, nbcols)
214        self.EnableEditing(False)
215        if user.LimitBy == "balance" :
216            self.SetColLabelValue(0, _("Page Counter"))
217            self.SetColLabelValue(1, _("Price per Page"))
218            self.SetColLabelValue(2, _("Price per Job"))
219            attr = gridlib.GridCellAttr()
220            attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
221            attr.SetReadOnly(True)
222            colour = wx.GREEN
223            if user.Balance <= 0.0 :
224                colour = wx.RED
225            attr.SetBackgroundColour(colour)       
226            self.SetColAttr(0, attr)
227            attr = gridlib.GridCellAttr()
228            attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
229            attr.SetReadOnly(True)
230            self.SetColAttr(1, attr)
231            self.SetColAttr(2, attr)
232            i = 0
233            for printername in user.Printers.keys() :
234                printer = user.Printers[printername]
235                quota = user.Quotas[printername]
236                self.SetRowLabelValue(i, printername)
237                self.SetCellValue(i, 0, str(quota.PageCounter))
238                self.SetCellValue(i, 1, str(printer.PricePerPage))
239                self.SetCellValue(i, 2, str(printer.PricePerJob))
240                i += 1
241            self.SetRowLabelValue(i, "")
242            self.SetCellValue(i, 0, _("CREDITS :") + (" %.2f" % user.Balance))
243            self.SetCellAlignment(i, 0, wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
244        else :   
245            self.SetColLabelValue(0, _("Page Counter"))
246            self.SetColLabelValue(1, _("Soft Limit"))
247            self.SetColLabelValue(2, _("Hard Limit"))
248            self.SetColLabelValue(3, _("Date Limit"))
249            attr = gridlib.GridCellAttr()
250            attr.SetAlignment(wx.ALIGN_RIGHT, wx.ALIGN_CENTRE)
251            attr.SetReadOnly(True)
252            self.SetColAttr(0, attr)
253            attr = gridlib.GridCellAttr()
254            attr.SetAlignment(wx.ALIGN_CENTRE, wx.ALIGN_CENTRE)
255            attr.SetReadOnly(True)
256            self.SetColAttr(1, attr)
257            self.SetColAttr(2, attr)
258            self.SetColAttr(3, attr)
259            i = 0
260            for printername in user.Quotas.keys() :
261                quota = user.Quotas[printername]
262                self.SetRowLabelValue(i, printername)
263                self.SetCellValue(i, 0, str(quota.PageCounter))
264                self.SetCellValue(i, 1, str(quota.SoftLimit))
265                self.SetCellValue(i, 2, str(quota.HardLimit))
266                self.SetCellValue(i, 3, str(quota.DateLimit))
267                colour = wx.GREEN
268                if quota.SoftLimit is not None :
269                    if quota.PageCounter >= quota.SoftLimit :
270                        colour = wx.RED
271                elif quota.HardLimit is not None :       
272                    if quota.PageCounter >= quota.HardLimit :
273                        colour = wx.RED
274                self.SetCellBackgroundColour(i, 0, colour)       
275                i += 1
276        self.AutoSize()
277           
278class PyKotIcon(wxPython.wx.wxFrame):
279    """Main class."""
280    def __init__(self, parent, id):
281        wxPython.wx.wxFrame.__init__(self, parent, -1, \
282               _("PyKota Print Quota for user %s") % getCurrentUserName(), \
283               size = (460, -1), \
284               style = wxPython.wx.wxDEFAULT_FRAME_STYLE \
285                     | wxPython.wx.wxSIZE_AUTO_HEIGHT \
286                     | wxPython.wx.wxSIZE_AUTO_WIDTH \
287                     | wxPython.wx.wxICONIZE \
288                     | wxPython.wx.wxNO_FULL_REPAINT_ON_RESIZE)
289        try :             
290            self.tbicon = wxPython.wx.wxTaskBarIcon()
291        except AttributeError :   
292            self.tbicon = None # No taskbar icon facility, old wxWidgets maybe
293       
294        self.greenicon = wxPython.wx.wxIcon(os.path.join(iconsdir, "pykoticon-green.ico"), \
295                                  wxPython.wx.wxBITMAP_TYPE_ICO)
296        self.redicon = wxPython.wx.wxIcon(os.path.join(iconsdir, "pykoticon-red.ico"), \
297                                  wxPython.wx.wxBITMAP_TYPE_ICO)
298       
299        self.SetIcon(self.greenicon)
300        if self.tbicon is not None :
301            self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
302            wxPython.wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
303            wxPython.wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
304       
305            self.TBMENU_RESTORE = wx.NewId()
306            self.TBMENU_CLOSE = wx.NewId()
307            wxPython.wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, \
308                                              self.OnTaskBarActivate)
309            wxPython.wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, \
310                                              self.OnTaskBarClose)
311            self.menu = wxPython.wx.wxMenu()
312            self.menu.Append(self.TBMENU_RESTORE, _("Show Print Quota"))
313            self.menu.Append(self.TBMENU_CLOSE, _("Quit"))
314       
315        wxPython.wx.EVT_ICONIZE(self, self.OnIconify)
316        wxPython.wx.EVT_CLOSE(self, self.OnClose)
317       
318        self.TBTIMER = wx.NewId()
319        self.chrono = wxPython.wx.wxTimer(self, self.TBTIMER)
320        wxPython.wx.EVT_TIMER(self, self.TBTIMER, self.OnChronoTimer)
321       
322        self.User = None
323        self.networkInterface = CGINetworkInterface(DUMPYKOTA_URL)
324        self.inTimer = False
325        self.chrono.Start(250) # first time in 0.25 second
326
327    def OnChronoTimer(self, event) :
328        """Retrieves user's data quota information."""
329        # we stop it there, needed because we want to
330        # change the delay the first time.
331        self.chrono.Stop()   
332        if self.inTimer is False : # avoids re-entrance
333            self.inTimer = True
334            self.User = self.networkInterface.getUserInfo(getCurrentUserName())
335            if self.User.LimitBy == "balance" :
336                if self.User.Balance <= 0.0 :
337                    self.SetIcon(self.redicon)
338                    if self.tbicon is not None :
339                        self.tbicon.SetIcon(self.redicon, "PyKotIcon")
340                else :   
341                    self.SetIcon(self.greenicon)
342                    if self.tbicon is not None :
343                        self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
344            else :       
345                isRed = False
346                for q in self.User.Quotas.keys() :
347                    quota = self.User.Quotas[q]
348                    if quota.SoftLimit is not None :
349                        if quota.PageCounter >= quota.SoftLimit :
350                            isRed = True
351                            break
352                    elif quota.HardLimit is not None :       
353                        if quota.PageCounter >= quota.HardLimit :
354                            isRed = True
355                            break
356                if isRed is True :
357                    self.SetIcon(self.redicon)
358                    if self.tbicon is not None :
359                        self.tbicon.SetIcon(self.redicon, "PyKotIcon")
360                else :   
361                    self.SetIcon(self.greenicon)
362                    if self.tbicon is not None :
363                        self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
364            if hasattr(self, "quotasgrid") :   
365                self.quotasgrid.Close()
366                self.quotasgrid.Destroy()
367                del self.quotasgrid
368            self.quotasgrid = PyKotIconGrid(self, self.User)   
369            self.inTimer = False
370        # Now we want it every 3 minutes   
371        #self.chrono.Start(1000 * 60 * 3) # every 3 minutes
372        self.chrono.Start(1000 * 20) # every 20 seconds
373   
374    def OnIconify(self, event) :
375        self.Hide()
376
377    def OnTaskBarActivate(self, event) :
378        if self.IsIconized() :
379            self.Iconize(False)
380        if not self.IsShown() :
381            self.Show(True)
382        self.Raise()
383
384    def OnClose(self, event) :
385        if hasattr(self, "chrono") :
386            self.chrono.Stop()
387            del self.chrono
388        if hasattr(self, "quotasgrid") :
389            self.quotasgrid.Close()
390            self.quotasgrid.Destroy()
391            del self.quotasgrid
392        if hasattr(self, "menu") :
393            self.menu.Destroy()
394            del self.menu
395        if hasattr(self, "tbicon") :
396            self.tbicon.Destroy()
397            del self.tbicon
398        self.Destroy()
399
400    def OnTaskBarMenu(self, evt) :
401        self.tbicon.PopupMenu(self.menu)
402
403    def OnTaskBarClose(self, evt) :
404        self.Close()
405        #wxPython.wx.wxGetApp().ProcessIdle()
406
407class PyKotIconApp(wx.PySimpleApp):
408    def OnInit(self) :
409        try :
410            frame = PyKotIcon(None, -1)
411        except :   
412            crashed()
413        else :   
414            frame.Show(True)
415        return True
416       
417def main():
418    """Program's entry point."""
419    try :
420        locale.setlocale(locale.LC_ALL, "")
421    except (locale.Error, IOError) :
422        sys.stderr.write("Problem while setting locale.\n")
423    try :
424        gettext.install("pykoticon")
425    except :
426        gettext.NullTranslations().install()
427    app = PyKotIconApp()
428    app.MainLoop()
429   
430def crashed() :   
431    """Minimal crash method."""
432    import traceback
433    lines = []
434    for line in traceback.format_exception(*sys.exc_info()) :
435        lines.extend([l for l in line.split("\n") if l])
436    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKotIcon"] + lines)])
437    sys.stderr.write(msg)
438    sys.stderr.flush()
439   
440def test() :
441    """Runs in test mode (console)."""
442    if len(sys.argv) >= 3 :
443        username = sys.argv[2] 
444    else :   
445        username = getCurrentUserName()
446    net = CGINetworkInterface(DUMPYKOTA_URL)
447    user = net.getUserInfo(username)
448    print "UserName : ", user.UserName
449    print "LimitBy : ", user.LimitBy
450    print "Balance : ", user.Balance
451    for printername in user.Quotas.keys() :
452        quota = user.Quotas[printername]
453        print "\tPrinterName : ", printername
454        print "\tPageCounter : ", quota.PageCounter
455        print "\tSoftLimit : ", quota.SoftLimit
456        print "\tHardLimit : ", quota.HardLimit
457        print "\tDateLimit : ", quota.DateLimit
458        print
459    for printername in user.Printers.keys() :
460        printer = user.Printers[printername]
461        print "\tPrinterName : ", printername
462        print "\tPrice per Page : ", printer.PricePerPage
463        print "\tPrice per Job : ", printer.PricePerJob
464        print
465
466if __name__ == '__main__':
467    if (len(sys.argv) >= 2) and (sys.argv[1] == "--test") :
468        test()
469    else :   
470        main()
471   
Note: See TracBrowser for help on using the browser.