root / pykoticon / trunk / bin / pykoticon @ 143

Revision 143, 18.5 kB (checked in by jerome, 18 years ago)

Added screenshots.

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