root / pykoticon / trunk / bin / pykoticon @ 113

Revision 113, 16.3 kB (checked in by jerome, 18 years ago)

Fixed unicode problem.

  • 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        try :             
214            self.tbicon = wx.TaskBarIcon()
215        except AttributeError :   
216            self.tbicon = None # No taskbar icon facility
217       
218        self.greenicon = wx.Icon(os.path.join(iconsdir, "pykoticon-green.ico"), \
219                                  wx.BITMAP_TYPE_ICO)
220        self.redicon = wx.Icon(os.path.join(iconsdir, "pykoticon-red.ico"), \
221                                  wx.BITMAP_TYPE_ICO)
222       
223        self.SetIcon(self.greenicon)
224        if self.tbicon is not None :
225            self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
226            wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
227            wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
228       
229            self.TBMENU_ABOUT = wx.NewId()
230            self.TBMENU_RESTORE = wx.NewId()
231            self.TBMENU_CLOSE = wx.NewId()
232            wx.EVT_MENU(self.tbicon, self.TBMENU_ABOUT, \
233                                              self.OnAbout)
234            wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, \
235                                              self.OnTaskBarActivate)
236            wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, \
237                                              self.OnTaskBarClose)
238            try :                                 
239                self.menu = wx.Menu()
240            except :   
241                pass
242            else :   
243                self.menu.Append(self.TBMENU_ABOUT, _("About"))
244                self.menu.Append(self.TBMENU_CLOSE, _("Quit"))
245       
246        wx.EVT_ICONIZE(self, self.OnIconify)
247        wx.EVT_CLOSE(self, self.OnClose)
248        self.Show(True)
249       
250    def OnIconify(self, event) :
251        if not self.IsIconized() :
252            self.Iconize(True)
253        self.Hide()
254
255    def OnTaskBarActivate(self, event) :
256        if self.IsIconized() :
257            self.Iconize(False)
258        if not self.IsShown() :
259            self.Show(True)
260        self.Raise()
261
262    def OnClose(self, event) :
263        self.closeServer()
264        try :
265            self.menu.Destroy()
266        except AttributeError :   
267            pass
268        try :   
269            self.tbicon.Destroy()
270        except AttributeError :   
271            pass
272        self.Destroy()
273
274    def OnTaskBarMenu(self, event) :
275        if self.tbicon :
276            try :
277                self.tbicon.PopupMenu(self.menu)
278            except AttributeError :   
279                pass
280
281    def OnTaskBarClose(self, event) :
282        self.Close()
283       
284    def OnAbout(self, event) :   
285        """Displays the about box."""
286        dialog = wx.MessageDialog(self, aboutbox, _("About"), wx.OK | wx.ICON_INFORMATION)
287        dialog.ShowModal()
288        dialog.Destroy()
289       
290    def showDialog(self, message, yesno) :
291        """Opens a notification dialog."""
292        self.dialogAnswer = None
293        if yesno :
294            caption = _("Confirmation")
295            style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION
296        else :
297            caption = _("Information")
298            style = wx.OK | wx.ICON_INFORMATION
299        style |= wx.STAY_ON_TOP   
300        dialog = wx.MessageDialog(self, message, caption, style)
301        self.dialogAnswer = ((dialog.ShowModal() == wx.ID_NO) and "CANCEL") or "OK"
302        dialog.Destroy()
303       
304    def askDatas(self, labels, varnames, varvalues) :
305        """Opens a dialog box asking for data entry."""
306        # use it this way : self.askDatas(["Username", "Password", "Billing code"], ["username", "password", "billingcode"])
307        self.dialogAnswer = None
308        dialog = GenericInputDialog(self, wx.ID_ANY, labels, varnames, varvalues)
309        retvalues = {}
310        if dialog.ShowModal() == wx.ID_OK :
311            retvalues["isValid"] = True
312            for i in range(len(varnames)) :
313                retvalues[varnames[i]] = dialog.variables[i].GetValue()
314        else :       
315            retvalues["isValid"] = False
316            for k in varvalues.keys() :
317                retvalues[k] = ""
318        self.dialogAnswer = retvalues
319        dialog.Destroy()
320       
321    def closeServer(self) :   
322        """Tells the xml-rpc server to exit."""
323        if not self.quitEvent.isSet() :
324            self.quitEvent.set()
325        server = xmlrpclib.ServerProxy("http://localhost:%s" % self.port)   
326        try :
327            # wake the server with an empty request
328            # for it to see the event object
329            # which has just been set
330            server.nop()
331        except :   
332            # Probably already stopped
333            pass
334       
335    def postInit(self, charset, printserver, localport) :   
336        """Starts the XML-RPC server."""
337        self.quitEvent = threading.Event()
338        self.charset = charset
339        self.port = localport
340        self.server = MyXMLRPCServer(self, printserver, localport, debug=True)
341       
342    def UTF8ToUserCharset(self, text) :
343        """Converts from UTF-8 to user's charset."""
344        if text is not None :
345            try :
346                return unicode(text, "UTF-8").encode(self.charset) 
347            except (UnicodeError, TypeError) :   
348                try :
349                    # Incorrect locale settings ?
350                    return unicode(text, "UTF-8").encode("ISO-8859-15") 
351                except (UnicodeError, TypeError) :   
352                    try :
353                        return text.encode(self.charset) 
354                    except (UnicodeError, TypeError, AttributeError) :
355                        pass
356        return text
357       
358    def userCharsetToUTF8(self, text) :
359        """Converts from user's charset to UTF-8."""
360        if text is not None :
361            try :
362                return unicode(text, self.charset).encode("UTF-8") 
363            except (UnicodeError, TypeError) :   
364                try :
365                    # Incorrect locale settings ?
366                    return unicode(text, "ISO-8859-15").encode("UTF-8") 
367                except (UnicodeError, TypeError) :   
368                    try :
369                        return text.encode("UTF-8") 
370                    except (UnicodeError, TypeError, AttributeError) :
371                        pass
372        return text
373
374class PyKotIconApp(wx.App):
375    def OnInit(self) :
376        self.frame = PyKotIcon(None, wx.ID_ANY)
377        self.frame.Center(wx.BOTH)
378        self.frame.Show(False)
379        return True
380       
381    def postInit(self, charset, printserver, localport) :   
382        """Continues processing."""
383        self.frame.postInit(charset, printserver, localport)
384       
385def main(printserver, localport):
386    """Program's entry point."""
387    try :
388        locale.setlocale(locale.LC_ALL, "")
389    except (locale.Error, IOError) :
390        sys.stderr.write("Problem while setting locale.\n")
391    try :
392        gettext.install("pykoticon")
393    except :
394        gettext.NullTranslations().install()
395       
396    localecharset = None
397    try :
398        try :
399            localecharset = locale.nl_langinfo(locale.CODESET)
400        except AttributeError :   
401            try :
402                localecharset = locale.getpreferredencoding()
403            except AttributeError :   
404                try :
405                    localecharset = locale.getlocale()[1]
406                    localecharset = localecharset or locale.getdefaultlocale()[1]
407                except ValueError :   
408                    pass        # Unknown locale, strange...
409    except locale.Error :           
410        pass
411    charset = os.environ.get("CHARSET") or localecharset or "ISO-8859-15"
412   
413    app = PyKotIconApp()
414    try :
415        localport = int(localport)   
416    except (TypeError, ValueError) :   
417        raise ValueError, "Invalid TCP port parameter %s\n" % localport
418    app.postInit(charset, printserver, localport)
419    app.MainLoop()
420   
421def crashed() :   
422    """Minimal crash method."""
423    import traceback
424    lines = []
425    for line in traceback.format_exception(*sys.exc_info()) :
426        lines.extend([l for l in line.split("\n") if l])
427    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKotIcon"] + lines)])
428    sys.stderr.write(msg)
429    sys.stderr.flush()
430   
431if __name__ == '__main__':
432    if len(sys.argv) >= 2 :
433        arg = sys.argv[1]
434        if arg in ("-v", "--version") :   
435            print "0.3"
436        elif arg in ("-h", "--help") :   
437            sys.stderr.write("usage : pykoticon  pykota_server_hostname_or_ip_address  localTCPPort\n")
438        else :
439            main(*sys.argv[1:3])
440    else :   
441        sys.stderr.write("usage : pykoticon  pykota_server_hostname_or_ip_address  localTCPPort\n")
Note: See TracBrowser for help on using the browser.