root / pykoticon / trunk / bin / pykoticon @ 127

Revision 127, 18.7 kB (checked in by jerome, 18 years ago)

Missing argument

  • Property svn:keywords set to Id
Line 
1#! /usr/bin/env python
2# -*- coding: ISO-8859-15 -*-
3
4"""PyKotIcon is a generic, networked, cross-platform dialog box manager."""
5
6# PyKotIcon - Client side helper for PyKota
7#
8# (c) 2003, 2004, 2005, 2006 Jerome Alet <alet@librelogiciel.com>
9# This program is free software; you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation; either version 2 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program; if not, write to the Free Software
21# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
22#
23#
24
25__version__ = "1.01"
26__author__ = "Jerome Alet"
27__author_email__ = "alet@librelogiciel.com"
28__license__ = "GNU GPL"
29__url__ = "http://www.librelogiciel.com/software/"
30__revision__ = "$Id$"
31
32import sys
33import os
34import time
35import urllib
36import urllib2
37import locale
38import gettext
39import socket
40import threading
41import xmlrpclib
42import SimpleXMLRPCServer
43try :
44    import optparse
45except ImportError :   
46    sys.stderr.write("You need Python v2.3 or higher for PyKotIcon to work.\nAborted.\n")
47    sys.exit(-1)
48
49if sys.platform == "win32" :
50    isWindows = True
51    try :
52        import win32api
53    except ImportError :   
54        raise ImportError, "Mark Hammond's Win32 Extensions are missing. Please install them."
55    else :   
56        iconsdir = os.path.split(sys.argv[0])[0]
57else :       
58    isWindows = False
59    iconsdir = "/usr/share/pykoticon"   # TODO : change this
60    import pwd
61   
62try :   
63    import wx
64    hasWxPython = True
65except ImportError :   
66    hasWxPython = False
67    raise ImportError, "wxPython is missing. Please install it."
68   
69aboutbox = """PyKotIcon v%(__version__)s (c) 2003-2006 %(__author__)s - %(__author_email__)s
70
71PyKotIcon is generic, networked, cross-platform dialog box manager.
72
73It is often used as a client side companion for PyKota, but it
74can be used from other applications if you want.
75
76This program is free software; you can redistribute it and/or modify
77it under the terms of the GNU General Public License as published by
78the Free Software Foundation; either version 2 of the License, or
79(at your option) any later version.
80
81This program is distributed in the hope that it will be useful,
82but WITHOUT ANY WARRANTY; without even the implied warranty of
83MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
84GNU General Public License for more details.
85
86You should have received a copy of the GNU General Public License
87along with this program; if not, write to the Free Software
88Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA."""
89
90       
91class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer) :
92    """My own server class."""
93    allow_reuse_address = True
94    def __init__(self, frame, options, arguments) :
95        SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, \
96                                                       ('0.0.0.0', options.port), \
97                                                       SimpleXMLRPCServer.SimpleXMLRPCRequestHandler, \
98                                                       options.debug)
99        self.frame = frame
100        self.debug = options.debug
101        self.printServers = [ socket.gethostbyname(arg) for arg in arguments ]
102        if "127.0.0.1" not in self.printServers :
103            self.printServers.append("127.0.0.1") # to allow clean shutdown
104        loop = threading.Thread(target=self.mainloop)
105        loop.start()
106       
107    def logDebug(self, message) :   
108        """Logs a debug message if debug mode is active."""
109        if self.debug :
110            sys.stderr.write("%s\n" % message)
111           
112    def export_quitApplication(self) :   
113        """Makes the application quit."""
114        self.frame.quitEvent.set()
115        wx.CallAfter(self.frame.OnClose, None)
116        return True
117       
118    def export_askDatas(self, labels, varnames, varvalues) :
119        """Asks some textual datas defined by a list of labels, a list of variables' names and a list of variables values in a mapping."""
120        values = {}
121        for (key, value) in varvalues.items() :
122            values[key] = self.frame.UTF8ToUserCharset(value.data)
123        wx.CallAfter(self.frame.askDatas, [ self.frame.UTF8ToUserCharset(label.data) for label in labels ], \
124                                          varnames, \
125                                          values)
126        # ugly, isn't it ?
127        while self.frame.dialogAnswer is None :
128            time.sleep(0.1)
129        retcode = self.frame.dialogAnswer   
130        for (key, value) in retcode.items() :
131            if key != "isValid" :
132                retcode[key] = xmlrpclib.Binary(self.frame.userCharsetToUTF8(value))
133        self.frame.dialogAnswer = None # prepare for next call, just in case
134        return retcode
135       
136    def export_showDialog(self, message, yesno) :
137        """Opens a notification or confirmation dialog."""
138        wx.CallAfter(self.frame.showDialog, self.frame.UTF8ToUserCharset(message.data), yesno)
139        # ugly, isn't it ?
140        while self.frame.dialogAnswer is None :
141            time.sleep(0.1)
142        retcode = self.frame.dialogAnswer   
143        self.frame.dialogAnswer = None # prepare for next call, just in case
144        return retcode
145       
146    def export_nop(self) :   
147        """Does nothing, but allows a clean shutdown from the frame itself."""
148        return True
149       
150    def verify_request(self, request, client_address) :
151        """Ensures that requests which don't come from the print server are rejected."""
152        (client, port) = client_address
153        if client in self.printServers :
154            self.logDebug("%s accepted." % client)
155            return True
156        else :
157            # Unauthorized access !
158            self.logDebug("%s rejected." % client)
159            return False
160       
161    def _dispatch(self, method, params) :   
162        """Ensure that only export_* methods are available."""
163        return getattr(self, "export_%s" % method)(*params)
164       
165    def mainloop(self) :
166        """XML-RPC Server's main loop."""
167        self.register_function(self.export_askDatas)
168        self.register_function(self.export_showDialog)
169        self.register_function(self.export_quitApplication)
170        self.register_function(self.export_nop)
171        while not self.frame.quitEvent.isSet() :
172            self.handle_request()
173        self.server_close()   
174        sys.exit(0)
175   
176   
177class GenericInputDialog(wx.Dialog) :
178    """Generic input dialog box."""
179    def __init__(self, parent, id, labels, varnames, varvalues):
180        wx.Dialog.__init__(self, parent, id, \
181               _("PyKotIcon data input"), \
182               style = wx.CAPTION \
183                     | wx.THICK_FRAME \
184                     | wx.STAY_ON_TOP \
185                     | wx.DIALOG_MODAL)
186
187        self.variables = []
188        vsizer = wx.BoxSizer(wx.VERTICAL)
189        for i in range(len(varnames)) :
190            varname = varnames[i]
191            try :
192                label = labels[i]
193            except IndexError :   
194                label = ""
195            labelid = wx.NewId()   
196            varid = wx.NewId()
197            label = wx.StaticText(self, labelid, label)
198            if varname.lower().find("password") != -1 :
199                variable = wx.TextCtrl(self, varid, varvalues.get(varname, ""), style=wx.TE_PASSWORD)
200            else :
201                variable = wx.TextCtrl(self, varid, varvalues.get(varname, ""))
202            self.variables.append(variable)   
203            hsizer = wx.BoxSizer(wx.HORIZONTAL)
204            hsizer.Add(label, 0, wx.ALIGN_CENTER | wx.ALIGN_RIGHT | wx.ALL, 5)
205            hsizer.Add(variable, 0, wx.ALIGN_CENTER | wx.ALIGN_LEFT | wx.ALL, 5)
206            vsizer.Add(hsizer, 0, wx.ALIGN_CENTER | wx.ALL, 5)
207           
208        okbutton = wx.Button(self, wx.ID_OK, "OK")   
209        vsizer.Add(okbutton, 0, wx.ALIGN_CENTER | wx.ALL, 5)
210       
211        self.SetAutoLayout(True)
212        self.SetSizerAndFit(vsizer)
213        self.Layout()
214       
215       
216class PyKotIcon(wx.Frame):
217    """Main class."""
218    def __init__(self, parent, id):
219        self.dialogAnswer = None
220        wx.Frame.__init__(self, parent, id, \
221               _("PyKotIcon info for %s") % self.getCurrentUserName(), \
222               size = (0, 0), \
223               style = wx.FRAME_NO_TASKBAR | wx.NO_FULL_REPAINT_ON_RESIZE)
224                     
225        self.tbicon = wx.TaskBarIcon()
226        self.greenicon = wx.Icon(os.path.join(iconsdir, "pykoticon-green.ico"), \
227                                  wx.BITMAP_TYPE_ICO)
228        self.redicon = wx.Icon(os.path.join(iconsdir, "pykoticon-red.ico"), \
229                                  wx.BITMAP_TYPE_ICO)
230        if isWindows :                         
231            self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
232       
233        wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
234        wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
235       
236        self.TBMENU_ABOUT = wx.NewId()
237        self.TBMENU_RESTORE = wx.NewId()
238        self.TBMENU_CLOSE = wx.NewId()
239        wx.EVT_MENU(self.tbicon, self.TBMENU_ABOUT, \
240                                          self.OnAbout)
241        wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, \
242                                          self.OnTaskBarActivate)
243        wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, \
244                                          self.OnTaskBarClose)
245        self.menu = wx.Menu()
246        self.menu.Append(self.TBMENU_ABOUT, _("About"))
247        self.menu.Append(self.TBMENU_CLOSE, _("Quit"))
248       
249        wx.EVT_ICONIZE(self, self.OnIconify)
250        wx.EVT_CLOSE(self, self.FakeOnClose)
251        self.Show(True)
252       
253    def getCurrentUserName(self) :
254        """Retrieves the current user's name."""
255        if isWindows :
256            return win32api.GetUserName()
257        else :   
258            try :
259                return pwd.getpwuid(os.geteuid())[0]
260            except :
261                return "** Unknown **"
262           
263    def OnIconify(self, event) :
264        """Iconify/De-iconify the application."""
265        if not self.IsIconized() :
266            self.Iconize(True)
267        self.Hide()
268
269    def OnTaskBarActivate(self, event) :
270        """Show the application if it is minimized."""
271        if self.IsIconized() :
272            self.Iconize(False)
273        if not self.IsShown() :
274            self.Show(True)
275        self.Raise()
276
277    def OnClose(self, event) :
278        """Cleanly quit the application."""
279        self.closeServer()
280        self.menu.Destroy()
281        self.tbicon.Destroy()
282        self.Destroy()
283
284    def OnTaskBarMenu(self, event) :
285        """Open the taskbar menu."""
286        self.tbicon.PopupMenu(self.menu)
287
288    def FakeOnClose(self, event) :
289        """React to close from windows corner."""
290        if self.options.allowquit :
291            self.Close()
292        else :
293            self.quitIsForbidden()
294           
295    def OnTaskBarClose(self, event) :
296        """React to close from the taskbar."""
297        if self.options.allowquit :
298            self.Close()
299        else :
300            self.quitIsForbidden()
301           
302    def quitIsForbidden(self) :       
303        """Displays a message indicating that quitting the application is not allowed."""
304        message = _("Sorry, this was forbidden by your system administrator.")
305        caption = _("Information")
306        style = wx.OK | wx.ICON_INFORMATION | wx.STAY_ON_TOP
307        dialog = wx.MessageDialog(self, message, caption, style)
308        dialog.ShowModal()
309        dialog.Destroy()
310       
311    def OnAbout(self, event) :   
312        """Displays the about box."""
313        dialog = wx.MessageDialog(self, aboutbox % globals(), _("About"), wx.OK | wx.ICON_INFORMATION)
314        dialog.ShowModal()
315        dialog.Destroy()
316       
317    def showDialog(self, message, yesno) :
318        """Opens a notification dialog."""
319        self.dialogAnswer = None
320        if yesno :
321            caption = _("Confirmation")
322            style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION
323        else :
324            caption = _("Information")
325            style = wx.OK | wx.ICON_INFORMATION
326        style |= wx.STAY_ON_TOP   
327        dialog = wx.MessageDialog(self, message, caption, style)
328        self.dialogAnswer = ((dialog.ShowModal() == wx.ID_NO) and "CANCEL") or "OK"
329        dialog.Destroy()
330       
331    def askDatas(self, labels, varnames, varvalues) :
332        """Opens a dialog box asking for data entry."""
333        # use it this way : self.askDatas(["Username", "Password", "Billing code"], ["username", "password", "billingcode"])
334        self.dialogAnswer = None
335        dialog = GenericInputDialog(self, wx.ID_ANY, labels, varnames, varvalues)
336        retvalues = {}
337        if dialog.ShowModal() == wx.ID_OK :
338            retvalues["isValid"] = True
339            for i in range(len(varnames)) :
340                retvalues[varnames[i]] = dialog.variables[i].GetValue()
341        else :       
342            retvalues["isValid"] = False
343            for k in varvalues.keys() :
344                retvalues[k] = ""
345        self.dialogAnswer = retvalues
346        dialog.Destroy()
347       
348    def closeServer(self) :   
349        """Tells the xml-rpc server to exit."""
350        if not self.quitEvent.isSet() :
351            self.quitEvent.set()
352        server = xmlrpclib.ServerProxy("http://localhost:%s" % self.options.port)   
353        try :
354            # wake the server with an empty request
355            # for it to see the event object
356            # which has just been set
357            server.nop()
358        except :   
359            # Probably already stopped
360            pass
361       
362    def postInit(self, charset, options, arguments) :   
363        """Starts the XML-RPC server."""
364        self.quitEvent = threading.Event()
365        self.charset = charset
366        self.options = options
367        self.server = MyXMLRPCServer(self, options, arguments)
368       
369    def UTF8ToUserCharset(self, text) :
370        """Converts from UTF-8 to user's charset."""
371        if text is not None :
372            try :
373                return text.decode("UTF-8").encode(self.charset, "replace") 
374            except (UnicodeError, AttributeError) :   
375                try :
376                    # Maybe already in Unicode
377                    return text.encode(self.charset, "replace") 
378                except (UnicodeError, AttributeError) :
379                    pass # Don't know what to do
380        return text
381       
382    def userCharsetToUTF8(self, text) :
383        """Converts from user's charset to UTF-8."""
384        if text is not None :
385            try :
386                # We don't necessarily trust the default charset, because
387                # xprint sends us titles in UTF-8 but CUPS gives us an ISO-8859-1 charset !
388                # So we first try to see if the text is already in UTF-8 or not, and
389                # if it is, we delete characters which can't be converted to the user's charset,
390                # then convert back to UTF-8. PostgreSQL 7.3.x used to reject some unicode characters,
391                # this is fixed by the ugly line below :
392                return text.decode("UTF-8").encode(self.charset, "replace").decode(self.charset).encode("UTF-8", "replace")
393            except (UnicodeError, AttributeError) :
394                try :
395                    return text.decode(self.charset).encode("UTF-8", "replace") 
396                except (UnicodeError, AttributeError) :   
397                    try :
398                        # Maybe already in Unicode
399                        return text.encode("UTF-8", "replace") 
400                    except (UnicodeError, AttributeError) :
401                        pass # Don't know what to do
402        return text
403       
404
405class PyKotIconApp(wx.App):
406    def OnInit(self) :
407        self.frame = PyKotIcon(None, wx.ID_ANY)
408        self.frame.Show(False)
409        self.SetTopWindow(self.frame)
410        return True
411       
412    def postInit(self, charset, options, arguments) :   
413        """Continues processing."""
414        self.frame.postInit(charset, options, arguments)
415       
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       
428    localecharset = None
429    try :
430        try :
431            localecharset = locale.nl_langinfo(locale.CODESET)
432        except AttributeError :   
433            try :
434                localecharset = locale.getpreferredencoding()
435            except AttributeError :   
436                try :
437                    localecharset = locale.getlocale()[1]
438                    localecharset = localecharset or locale.getdefaultlocale()[1]
439                except ValueError :   
440                    pass        # Unknown locale, strange...
441    except locale.Error :           
442        pass
443    charset = os.environ.get("CHARSET") or localecharset or "ISO-8859-15"
444   
445    parser = optparse.OptionParser(usage="usage : pykoticon [options] server1 [server2 ...]")
446    parser.add_option("-v", "--version", 
447                            action="store_true", 
448                            dest="version",
449                            help=_("show PyKotIcon's version number and exit"))
450    parser.add_option("-d", "--debug", 
451                            action="store_true", 
452                            dest="debug",
453                            help=_("activate debug mode"))
454    parser.add_option("-p", "--port", 
455                            type="int", 
456                            default=7654, 
457                            dest="port",
458                            help=_("the TCP port PyKotIcon will listen to, default is %default"))
459    parser.add_option("-q", "--allowquit", 
460                            action="store_true", 
461                            dest="allowquit",
462                            help=_("allow the end user to close the application"))
463    (options, arguments) = parser.parse_args()
464    if options.version :
465        print "PyKotIcon v%(__version__)s" % globals()
466    else :
467        app = PyKotIconApp()
468        app.postInit(charset, options, arguments)
469        app.MainLoop()
470   
471   
472def crashed() :   
473    """Minimal crash method."""
474    import traceback
475    lines = []
476    for line in traceback.format_exception(*sys.exc_info()) :
477        lines.extend([l for l in line.split("\n") if l])
478    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKotIcon"] + lines)])
479    sys.stderr.write(msg)
480    sys.stderr.flush()
481   
482   
483if __name__ == '__main__':
484    main()
485   
Note: See TracBrowser for help on using the browser.