root / pykoticon / trunk / bin / pykoticon @ 114

Revision 114, 15.7 kB (checked in by jerome, 18 years ago)

Small changes

  • Property svn:keywords set to Id
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4# PyKotIcon - Client side helper for PyKota
5#
6# (c) 2003, 2004, 2005, 2006 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
31import socket
32import threading
33import xmlrpclib
34import SimpleXMLRPCServer
35
36import time
37
38if sys.platform == "win32" :
39    isWindows = 1
40    try :
41        import win32api
42    except ImportError :   
43        raise ImportError, "Mark Hammond's Win32 Extensions are missing. Please install them."
44    else :   
45        iconsdir = os.path.split(sys.argv[0])[0]
46else :       
47    isWindows = 0
48    iconsdir = "/usr/share/pykoticon"   # TODO : change this
49    import pwd
50   
51try :   
52    import wx
53    hasWxPython = 1
54except ImportError :   
55    hasWxPython = 0
56    raise ImportError, "wxPython is missing. Please install it."
57   
58aboutbox = """PyKotIcon v1.00 (c) 2003, 2004, 2005, 2006 Jerome Alet - alet@librelogiciel.com   
59
60PyKotIcon is a client side print quota notifier for PyKota, but it
61can be used from other applications if you want.
62
63This program is free software; you can redistribute it and/or modify
64it under the terms of the GNU General Public License as published by
65the Free Software Foundation; either version 2 of the License, or
66(at your option) any later version.
67
68This program is distributed in the hope that it will be useful,
69but WITHOUT ANY WARRANTY; without even the implied warranty of
70MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
71GNU General Public License for more details.
72
73You should have received a copy of the GNU General Public License
74along with this program; if not, write to the Free Software
75Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA."""
76
77def getCurrentUserName() :
78    """Retrieves the current user's name."""
79    if isWindows :
80        return win32api.GetUserName()
81    else :   
82        try :
83            return pwd.getpwuid(os.geteuid())[0]
84        except :
85            return "** Unknown **"
86       
87class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer) :
88    """My own server class."""
89    allow_reuse_address = True
90    def __init__(self, frame, printserver, localport, debug=False) :
91        SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, ('0.0.0.0', localport))
92        self.printServer = printserver
93        self.frame = frame
94        self.debug = debug
95        loop = threading.Thread(target=self.mainloop)
96        loop.start()
97       
98    def logDebug(self, message) :   
99        """Logs a debug message if debug mode is active."""
100        if self.debug :
101            sys.stderr.write("%s\n" % message)
102           
103    def export_quitApplication(self) :   
104        """Makes the application quit."""
105        self.frame.quitEvent.set()
106        wx.CallAfter(self.frame.OnClose, None)
107        return True
108       
109    def export_askDatas(self, labels, varnames, varvalues) :
110        """Asks some textual datas defined by a list of labels, a list of variables' names and a list of variables values in a mapping."""
111        values = {}
112        for (k, v) in varvalues.items() :
113            values[k] = self.frame.UTF8ToUserCharset(v.data)
114        wx.CallAfter(self.frame.askDatas, [ self.frame.UTF8ToUserCharset(v.data) for v in labels ], \
115                                          varnames, \
116                                          values)
117        # ugly, isn't it ?
118        while self.frame.dialogAnswer is None :
119            time.sleep(0.1)
120        retcode = self.frame.dialogAnswer   
121        for (k, v) in retcode.items() :
122            if k != "isValid" :
123                retcode[k] = xmlrpclib.Binary(self.frame.userCharsetToUTF8(v))
124        self.frame.dialogAnswer = None # prepare for next call, just in case
125        return retcode
126       
127    def export_showDialog(self, message, yesno) :
128        """Opens a notification or confirmation dialog."""
129        wx.CallAfter(self.frame.showDialog, self.frame.UTF8ToUserCharset(message.data), yesno)
130        # ugly, isn't it ?
131        while self.frame.dialogAnswer is None :
132            time.sleep(0.1)
133        retcode = self.frame.dialogAnswer   
134        self.frame.dialogAnswer = None # prepare for next call, just in case
135        return retcode
136       
137    def export_nop(self) :   
138        """Does nothing, but allows a clean shutdown from the frame itself."""
139        return True
140       
141    def verify_request(self, request, client_address) :
142        """Ensures that requests which don't come from the print server are rejected."""
143        (client, port) = client_address
144        if socket.gethostbyname(self.printServer) == client :
145            self.logDebug("%s accepted." % client)
146            return True
147        else :
148            # Unauthorized access !
149            self.logDebug("%s rejected." % client)
150            return False
151       
152    def _dispatch(self, method, params) :   
153        """Ensure that only export_* methods are available."""
154        return getattr(self, "export_%s" % method)(*params)
155       
156    def mainloop(self) :
157        """XML-RPC Server's main loop."""
158        self.register_function(self.export_askDatas)
159        self.register_function(self.export_showDialog)
160        self.register_function(self.export_quitApplication)
161        self.register_function(self.export_nop)
162        while not self.frame.quitEvent.isSet() :
163            self.handle_request()
164        self.server_close()   
165        sys.exit(0)
166   
167class GenericInputDialog(wx.Dialog) :
168    """Generic input dialog box."""
169    def __init__(self, parent, id, labels, varnames, varvalues):
170        wx.Dialog.__init__(self, parent, id, \
171               _("PyKotIcon data input"), \
172               style = wx.CAPTION \
173                     | wx.THICK_FRAME \
174                     | wx.STAY_ON_TOP \
175                     | wx.DIALOG_MODAL)
176
177        self.variables = []
178        vsizer = wx.BoxSizer(wx.VERTICAL)
179        for i in range(len(varnames)) :
180            varname = varnames[i]
181            try :
182                label = labels[i]
183            except IndexError :   
184                label = ""
185            labelid = wx.NewId()   
186            varid = wx.NewId()
187            label = wx.StaticText(self, labelid, label)
188            if varname.lower().find("password") != -1 :
189                variable = wx.TextCtrl(self, varid, varvalues.get(varname, ""), style=wx.TE_PASSWORD)
190            else :
191                variable = wx.TextCtrl(self, varid, varvalues.get(varname, ""))
192            self.variables.append(variable)   
193            hsizer = wx.BoxSizer(wx.HORIZONTAL)
194            hsizer.Add(label, 0, wx.ALIGN_CENTER | wx.ALIGN_RIGHT | wx.ALL, 5)
195            hsizer.Add(variable, 0, wx.ALIGN_CENTER | wx.ALIGN_LEFT | wx.ALL, 5)
196            vsizer.Add(hsizer, 0, wx.ALIGN_CENTER | wx.ALL, 5)
197           
198        okbutton = wx.Button(self, wx.ID_OK, "OK")   
199        vsizer.Add(okbutton, 0, wx.ALIGN_CENTER | wx.ALL, 5)
200       
201        self.SetAutoLayout(True)
202        self.SetSizerAndFit(vsizer)
203        self.Layout()
204       
205class PyKotIcon(wx.Frame):
206    """Main class."""
207    def __init__(self, parent, id):
208        self.dialogAnswer = None
209        wx.Frame.__init__(self, parent, id, \
210               _("PyKotIcon info for %s") % getCurrentUserName(), \
211               size = (1, 1), \
212               style = wx.FRAME_NO_TASKBAR | wx.NO_FULL_REPAINT_ON_RESIZE)
213                     
214        self.tbicon = wx.TaskBarIcon()
215        self.greenicon = wx.Icon(os.path.join(iconsdir, "pykoticon-green.ico"), \
216                                  wx.BITMAP_TYPE_ICO)
217        self.redicon = wx.Icon(os.path.join(iconsdir, "pykoticon-red.ico"), \
218                                  wx.BITMAP_TYPE_ICO)
219        self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
220       
221        wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
222        wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
223       
224        self.TBMENU_ABOUT = wx.NewId()
225        self.TBMENU_RESTORE = wx.NewId()
226        self.TBMENU_CLOSE = wx.NewId()
227        wx.EVT_MENU(self.tbicon, self.TBMENU_ABOUT, \
228                                          self.OnAbout)
229        wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, \
230                                          self.OnTaskBarActivate)
231        wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, \
232                                          self.OnTaskBarClose)
233        self.menu = wx.Menu()
234        self.menu.Append(self.TBMENU_ABOUT, _("About"))
235        self.menu.Append(self.TBMENU_CLOSE, _("Quit"))
236       
237        wx.EVT_ICONIZE(self, self.OnIconify)
238        wx.EVT_CLOSE(self, self.OnClose)
239        self.Show(True)
240       
241    def OnIconify(self, event) :
242        if not self.IsIconized() :
243            self.Iconize(True)
244        self.Hide()
245
246    def OnTaskBarActivate(self, event) :
247        if self.IsIconized() :
248            self.Iconize(False)
249        if not self.IsShown() :
250            self.Show(True)
251        self.Raise()
252
253    def OnClose(self, event) :
254        self.closeServer()
255        self.menu.Destroy()
256        self.tbicon.Destroy()
257        self.Destroy()
258
259    def OnTaskBarMenu(self, event) :
260        self.tbicon.PopupMenu(self.menu)
261
262    def OnTaskBarClose(self, event) :
263        self.Close()
264       
265    def OnAbout(self, event) :   
266        """Displays the about box."""
267        dialog = wx.MessageDialog(self, aboutbox, _("About"), wx.OK | wx.ICON_INFORMATION)
268        dialog.ShowModal()
269        dialog.Destroy()
270       
271    def showDialog(self, message, yesno) :
272        """Opens a notification dialog."""
273        self.dialogAnswer = None
274        if yesno :
275            caption = _("Confirmation")
276            style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION
277        else :
278            caption = _("Information")
279            style = wx.OK | wx.ICON_INFORMATION
280        style |= wx.STAY_ON_TOP   
281        dialog = wx.MessageDialog(self, message, caption, style)
282        self.dialogAnswer = ((dialog.ShowModal() == wx.ID_NO) and "CANCEL") or "OK"
283        dialog.Destroy()
284       
285    def askDatas(self, labels, varnames, varvalues) :
286        """Opens a dialog box asking for data entry."""
287        # use it this way : self.askDatas(["Username", "Password", "Billing code"], ["username", "password", "billingcode"])
288        self.dialogAnswer = None
289        dialog = GenericInputDialog(self, wx.ID_ANY, labels, varnames, varvalues)
290        retvalues = {}
291        if dialog.ShowModal() == wx.ID_OK :
292            retvalues["isValid"] = True
293            for i in range(len(varnames)) :
294                retvalues[varnames[i]] = dialog.variables[i].GetValue()
295        else :       
296            retvalues["isValid"] = False
297            for k in varvalues.keys() :
298                retvalues[k] = ""
299        self.dialogAnswer = retvalues
300        dialog.Destroy()
301       
302    def closeServer(self) :   
303        """Tells the xml-rpc server to exit."""
304        if not self.quitEvent.isSet() :
305            self.quitEvent.set()
306        server = xmlrpclib.ServerProxy("http://localhost:%s" % self.port)   
307        try :
308            # wake the server with an empty request
309            # for it to see the event object
310            # which has just been set
311            server.nop()
312        except :   
313            # Probably already stopped
314            pass
315       
316    def postInit(self, charset, printserver, localport) :   
317        """Starts the XML-RPC server."""
318        self.quitEvent = threading.Event()
319        self.charset = charset
320        self.port = localport
321        self.server = MyXMLRPCServer(self, printserver, localport, debug=True)
322       
323    def UTF8ToUserCharset(self, text) :
324        """Converts from UTF-8 to user's charset."""
325        if text is not None :
326            try :
327                return unicode(text, "UTF-8").encode(self.charset) 
328            except (UnicodeError, TypeError) :   
329                try :
330                    # Incorrect locale settings ?
331                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
332                except (UnicodeError, TypeError) :   
333                    try :
334                        return text.encode(self.charset) 
335                    except (UnicodeError, TypeError, AttributeError) :
336                        pass
337        return text
338       
339    def userCharsetToUTF8(self, text) :
340        """Converts from user's charset to UTF-8."""
341        if text is not None :
342            try :
343                return unicode(text, self.charset).encode("UTF-8") 
344            except (UnicodeError, TypeError) :   
345                try :
346                    # Incorrect locale settings ?
347                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
348                except (UnicodeError, TypeError) :   
349                    try :
350                        return text.encode("UTF-8") 
351                    except (UnicodeError, TypeError, AttributeError) :
352                        pass
353        return text
354
355class PyKotIconApp(wx.App):
356    def OnInit(self) :
357        self.frame = PyKotIcon(None, wx.ID_ANY)
358        self.frame.Show(False)
359        self.SetTopWindow(self.frame)
360        return True
361       
362    def postInit(self, charset, printserver, localport) :   
363        """Continues processing."""
364        self.frame.postInit(charset, printserver, localport)
365       
366def main(printserver, localport):
367    """Program's entry point."""
368    try :
369        locale.setlocale(locale.LC_ALL, "")
370    except (locale.Error, IOError) :
371        sys.stderr.write("Problem while setting locale.\n")
372    try :
373        gettext.install("pykoticon")
374    except :
375        gettext.NullTranslations().install()
376       
377    localecharset = None
378    try :
379        try :
380            localecharset = locale.nl_langinfo(locale.CODESET)
381        except AttributeError :   
382            try :
383                localecharset = locale.getpreferredencoding()
384            except AttributeError :   
385                try :
386                    localecharset = locale.getlocale()[1]
387                    localecharset = localecharset or locale.getdefaultlocale()[1]
388                except ValueError :   
389                    pass        # Unknown locale, strange...
390    except locale.Error :           
391        pass
392    charset = os.environ.get("CHARSET") or localecharset or "ISO-8859-15"
393   
394    app = PyKotIconApp()
395    try :
396        localport = int(localport)   
397    except (TypeError, ValueError) :   
398        raise ValueError, "Invalid TCP port parameter %s\n" % localport
399    app.postInit(charset, printserver, localport)
400    app.MainLoop()
401   
402def crashed() :   
403    """Minimal crash method."""
404    import traceback
405    lines = []
406    for line in traceback.format_exception(*sys.exc_info()) :
407        lines.extend([l for l in line.split("\n") if l])
408    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKotIcon"] + lines)])
409    sys.stderr.write(msg)
410    sys.stderr.flush()
411   
412if __name__ == '__main__':
413    if len(sys.argv) >= 2 :
414        arg = sys.argv[1]
415        if arg in ("-v", "--version") :   
416            print "0.3"
417        elif arg in ("-h", "--help") :   
418            sys.stderr.write("usage : pykoticon  pykota_server_hostname_or_ip_address  localTCPPort\n")
419        else :
420            main(*sys.argv[1:3])
421    else :   
422        sys.stderr.write("usage : pykoticon  pykota_server_hostname_or_ip_address  localTCPPort\n")
Note: See TracBrowser for help on using the browser.