root / pykoticon / trunk / bin / pykoticon @ 104

Revision 104, 12.5 kB (checked in by jerome, 18 years ago)

More work done on generic input dialog and code factoring

  • 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   
58def getCurrentUserName() :
59    """Retrieves the current user's name."""
60    if isWindows :
61        return win32api.GetUserName()
62    else :   
63        try :
64            return pwd.getpwuid(os.geteuid())[0]
65        except :
66            return "** Unknown **"
67       
68class MyXMLRPCServer(SimpleXMLRPCServer.SimpleXMLRPCServer) :
69    """My own server class."""
70    allow_reuse_address = True
71    def __init__(self, frame, printserver, localport, debug=False) :
72        SimpleXMLRPCServer.SimpleXMLRPCServer.__init__(self, ('0.0.0.0', localport))
73        self.printServer = printserver
74        self.frame = frame
75        self.debug = debug
76        loop = threading.Thread(target=self.mainloop)
77        loop.start()
78       
79    def logDebug(self, message) :   
80        """Logs a debug message if debug mode is active."""
81        if self.debug :
82            sys.stderr.write("%s\n" % message)
83           
84    def export_quitApplication(self) :   
85        """Makes the application quit."""
86        self.logDebug("Remote host asked to close the application.")
87        self.frame.quitEvent.set()
88        wx.CallAfter(self.frame.OnClose, None)
89        return True
90       
91    def export_askDatas(self, labels, varnames, varvalues) :
92        """Asks some textual datas defined by a list of labels, a list of variables' names and a list of variables values in a mapping."""
93        wx.CallAfter(self.frame.askDatas, labels, varnames, varvalues)
94        # ugly, isn't it ?
95        #while self.frame.dialogAnswer is None :
96        #    time.sleep(0.1)
97        # TODO : add value extraction and return a mapping
98        self.frame.dialogAnswer = None # prepare for next call, just in case
99        return True
100       
101    def export_showDialog(self, message, yesno) :
102        """Opens a notification or confirmation dialog."""
103        wx.CallAfter(self.frame.showDialog, message, yesno)
104        # ugly, isn't it ?
105        while self.frame.dialogAnswer is None :
106            time.sleep(0.1)
107        retcode = self.frame.dialogAnswer   
108        self.frame.dialogAnswer = None # prepare for next call, just in case
109        return retcode
110       
111    def export_nop(self) :   
112        """Does nothing, but allows a clean shutdown from the frame itself."""
113        self.logDebug("No operation !")
114        return True
115       
116    def verify_request(self, request, client_address) :
117        """Ensures that requests which don't come from the print server are rejected."""
118        (client, port) = client_address
119        if socket.gethostbyname(self.printServer) == client :
120            self.logDebug("%s accepted." % client)
121            return True
122        else :
123            # Unauthorized access !
124            self.logDebug("%s rejected." % client)
125            return False
126       
127    def _dispatch(self, method, params) :   
128        """Ensure that only export_* methods are available."""
129        return getattr(self, "export_%s" % method)(*params)
130       
131    def mainloop(self) :
132        """XML-RPC Server's main loop."""
133        self.register_function(self.export_askDatas)
134        self.register_function(self.export_showDialog)
135        self.register_function(self.export_quitApplication)
136        self.register_function(self.export_nop)
137        while not self.frame.quitEvent.isSet() :
138            self.handle_request()
139        self.server_close()   
140        sys.exit(0)
141   
142class GenericInputDialog(wx.Frame) :   
143    """Generic input dialog box."""
144    def __init__(self, parent, id, labels, varnames, varvalues):
145        wx.Frame.__init__(self, parent, id, \
146               _("PyKotIcon data input"), \
147               size = (-1, -1), \
148               style = wx.DEFAULT_FRAME_STYLE \
149                     | wx.SIZE_AUTO_HEIGHT \
150                     | wx.SIZE_AUTO_WIDTH \
151                     | wx.STAY_ON_TOP \
152                     | wx.NO_FULL_REPAINT_ON_RESIZE)
153        vsizer = wx.BoxSizer(wx.VERTICAL)
154        for i in range(len(varnames)) :
155            varname = varnames[i]
156            try :
157                label = labels[i]
158            except IndexError :   
159                label = ""
160            labelid = wx.NewId()   
161            varid = wx.NewId()
162            label = wx.StaticText(self, labelid, label)
163            variable = wx.TextCtrl(self, varid, varvalues.get(varname, ""))
164            hsizer = wx.BoxSizer(wx.HORIZONTAL)
165            hsizer.Add(label, 0, wx.ALIGN_CENTER | wx.ALIGN_RIGHT | wx.ALL, 5)
166            hsizer.Add(variable, 0, wx.ALIGN_CENTER | wx.ALIGN_LEFT | wx.ALL, 5)
167            vsizer.Add(hsizer, 0, wx.ALIGN_CENTER | wx.ALL, 5)
168           
169        buttonid = wx.NewId()   
170        okbutton = wx.Button(self, buttonid, "OK")   
171        wx.EVT_BUTTON(self, buttonid, self.OnOK)
172       
173        wx.EVT_CLOSE(self, self.OnClose)
174       
175        vsizer.Add(okbutton, 0, wx.ALIGN_CENTER | wx.ALL, 5)
176        self.SetAutoLayout(True)
177        self.SetSizerAndFit(vsizer)
178        self.Layout()
179        self.Show(True)
180       
181    def OnClose(self, event) :
182        """Closes the current frame."""
183        self.Destroy()
184       
185    def OnOK(self, event) :   
186        """Sets the variables values."""
187        # TODO : do something
188        self.Close()
189   
190class PyKotIcon(wx.Frame):
191    """Main class."""
192    def __init__(self, parent, id):
193        self.dialogAnswer = None
194        wx.Frame.__init__(self, parent, id, \
195               _("PyKotIcon info for %s") % getCurrentUserName(), \
196               size = (-1, -1), \
197               style = wx.DEFAULT_FRAME_STYLE \
198                     | wx.SIZE_AUTO_HEIGHT \
199                     | wx.SIZE_AUTO_WIDTH \
200                     | wx.NO_FULL_REPAINT_ON_RESIZE)
201        try :             
202            self.tbicon = wx.TaskBarIcon()
203        except AttributeError :   
204            self.tbicon = None # No taskbar icon facility
205       
206        self.greenicon = wx.Icon(os.path.join(iconsdir, "pykoticon-green.ico"), \
207                                  wx.BITMAP_TYPE_ICO)
208        self.redicon = wx.Icon(os.path.join(iconsdir, "pykoticon-red.ico"), \
209                                  wx.BITMAP_TYPE_ICO)
210       
211        self.SetIcon(self.greenicon)
212        if self.tbicon is not None :
213            self.tbicon.SetIcon(self.greenicon, "PyKotIcon")
214            wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate)
215            wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu)
216       
217            self.TBMENU_RESTORE = wx.NewId()
218            self.TBMENU_CLOSE = wx.NewId()
219            wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, \
220                                              self.OnTaskBarActivate)
221            wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, \
222                                              self.OnTaskBarClose)
223            self.menu = wx.wxMenu()
224            self.menu.Append(self.TBMENU_RESTORE, _("Show Print Quota"))
225            self.menu.Append(self.TBMENU_CLOSE, _("Quit"))
226       
227        wx.EVT_ICONIZE(self, self.OnIconify)
228        wx.EVT_CLOSE(self, self.OnClose)
229        self.Show(True)
230       
231    def OnIconify(self, event) :
232        if not self.IsIconized() :
233            self.Iconize(True)
234        #self.Hide()
235
236    def OnTaskBarActivate(self, event) :
237        if self.IsIconized() :
238            self.Iconize(False)
239        if not self.IsShown() :
240            self.Show(True)
241        self.Raise()
242
243    def OnClose(self, event) :
244        self.closeServer()
245        if hasattr(self, "menu") :
246            self.menu.Destroy()
247            del self.menu
248        if hasattr(self, "tbicon") and self.tbicon :
249            self.tbicon.Destroy()
250            del self.tbicon
251        self.Destroy()
252
253    def OnTaskBarMenu(self, event) :
254        if self.tbicon :
255            self.tbicon.PopupMenu(self.menu)
256
257    def OnTaskBarClose(self, event) :
258        self.Close()
259       
260    def showDialog(self, message, yesno) :
261        """Opens a notification dialog."""
262        self.dialogAnswer = None
263        if yesno :
264            caption = _("Confirmation")
265            style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION
266        else :
267            caption = _("Information")
268            style = wx.OK | wx.ICON_INFORMATION
269        style |= wx.STAY_ON_TOP   
270        dialog = wx.MessageDialog(self, message, caption, style)
271        self.dialogAnswer = ((dialog.ShowModal() == wx.ID_NO) and "CANCEL") or "OK"
272        dialog.Destroy()
273       
274    def askDatas(self, labels, varnames, varvalues) :
275        """Opens a dialog box asking for data entry."""
276        # use it this way : self.askDatas(["Username", "Password", "Billing code"], ["username", "password", "billingcode"])
277        frame = GenericInputDialog(self, wx.ID_ANY, labels, varnames, varvalues)
278        # TODO : wait for dialog to close, and return the values
279        return True
280       
281    def closeServer(self) :   
282        """Tells the xml-rpc server to exit."""
283        if not self.quitEvent.isSet() :
284            self.quitEvent.set()
285        server = xmlrpclib.ServerProxy("http://localhost:%s" % self.port)   
286        try :
287            # wake the server with an empty request
288            # for it to see the event object
289            # which has just been set
290            server.nop()
291        except :   
292            # Probably already stopped
293            pass
294       
295    def postInit(self, printserver, localport) :   
296        """Starts the XML-RPC server."""
297        self.quitEvent = threading.Event()
298        self.port = localport
299        self.server = MyXMLRPCServer(self, printserver, localport, debug=True)
300   
301
302class PyKotIconApp(wx.PySimpleApp):
303    def OnInit(self) :
304        self.frame = PyKotIcon(None, wx.ID_ANY)
305        return True
306       
307    def postInit(self, printserver, localport) :   
308        """Continues processing."""
309        self.frame.postInit(printserver, localport)
310        #self.frame.Show(True)
311       
312def main(printserver, localport):
313    """Program's entry point."""
314    try :
315        locale.setlocale(locale.LC_ALL, "")
316    except (locale.Error, IOError) :
317        sys.stderr.write("Problem while setting locale.\n")
318    try :
319        gettext.install("pykoticon")
320    except :
321        gettext.NullTranslations().install()
322    app = PyKotIconApp()
323    try :
324        localport = int(localport)   
325    except (TypeError, ValueError) :   
326        raise ValueError, "Invalid TCP port parameter %s\n" % localport
327    app.postInit(printserver, localport)
328    app.MainLoop()
329   
330def crashed() :   
331    """Minimal crash method."""
332    import traceback
333    lines = []
334    for line in traceback.format_exception(*sys.exc_info()) :
335        lines.extend([l for l in line.split("\n") if l])
336    msg = "ERROR: ".join(["%s\n" % l for l in (["ERROR: PyKotIcon"] + lines)])
337    sys.stderr.write(msg)
338    sys.stderr.flush()
339   
340if __name__ == '__main__':
341    if len(sys.argv) >= 2 :
342        arg = sys.argv[1]
343        if arg in ("-v", "--version") :   
344            print "0.3"
345        elif arg in ("-h", "--help") :   
346            sys.stderr.write("usage : pykoticon  pykota_server_hostname_or_ip_address  localTCPPort\n")
347        else :
348            main(*sys.argv[1:3])
349    else :   
350        sys.stderr.write("usage : pykoticon  pykota_server_hostname_or_ip_address  localTCPPort\n")
Note: See TracBrowser for help on using the browser.