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 | |
---|
25 | import sys |
---|
26 | import os |
---|
27 | import urllib |
---|
28 | import urllib2 |
---|
29 | import locale |
---|
30 | import gettext |
---|
31 | import socket |
---|
32 | import threading |
---|
33 | import xmlrpclib |
---|
34 | import SimpleXMLRPCServer |
---|
35 | |
---|
36 | import time |
---|
37 | |
---|
38 | if 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] |
---|
46 | else : |
---|
47 | isWindows = 0 |
---|
48 | iconsdir = "/usr/share/pykoticon" # TODO : change this |
---|
49 | import pwd |
---|
50 | |
---|
51 | try : |
---|
52 | import wx |
---|
53 | hasWxPython = 1 |
---|
54 | except ImportError : |
---|
55 | hasWxPython = 0 |
---|
56 | raise ImportError, "wxPython is missing. Please install it." |
---|
57 | |
---|
58 | def 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 | |
---|
68 | class 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 | retcode = self.frame.dialogAnswer |
---|
98 | self.frame.dialogAnswer = None # prepare for next call, just in case |
---|
99 | return retcode |
---|
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 | |
---|
142 | class GenericInputDialog(wx.Dialog) : |
---|
143 | """Generic input dialog box.""" |
---|
144 | def __init__(self, parent, id, labels, varnames, varvalues): |
---|
145 | wx.Dialog.__init__(self, parent, id, \ |
---|
146 | _("PyKotIcon data input"), \ |
---|
147 | style = wx.CAPTION \ |
---|
148 | | wx.THICK_FRAME \ |
---|
149 | | wx.STAY_ON_TOP \ |
---|
150 | | wx.DIALOG_MODAL) |
---|
151 | |
---|
152 | self.variables = [] |
---|
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 | if varname.lower().find("password") != -1 : |
---|
164 | variable = wx.TextCtrl(self, varid, varvalues.get(varname, ""), style=wx.TE_PASSWORD) |
---|
165 | else : |
---|
166 | variable = wx.TextCtrl(self, varid, varvalues.get(varname, "")) |
---|
167 | self.variables.append(variable) |
---|
168 | hsizer = wx.BoxSizer(wx.HORIZONTAL) |
---|
169 | hsizer.Add(label, 0, wx.ALIGN_CENTER | wx.ALIGN_RIGHT | wx.ALL, 5) |
---|
170 | hsizer.Add(variable, 0, wx.ALIGN_CENTER | wx.ALIGN_LEFT | wx.ALL, 5) |
---|
171 | vsizer.Add(hsizer, 0, wx.ALIGN_CENTER | wx.ALL, 5) |
---|
172 | |
---|
173 | okbutton = wx.Button(self, wx.ID_OK, "OK") |
---|
174 | vsizer.Add(okbutton, 0, wx.ALIGN_CENTER | wx.ALL, 5) |
---|
175 | |
---|
176 | self.SetAutoLayout(True) |
---|
177 | self.SetSizerAndFit(vsizer) |
---|
178 | self.Layout() |
---|
179 | |
---|
180 | class PyKotIcon(wx.Frame): |
---|
181 | """Main class.""" |
---|
182 | def __init__(self, parent, id): |
---|
183 | self.dialogAnswer = None |
---|
184 | wx.Frame.__init__(self, parent, id, \ |
---|
185 | _("PyKotIcon info for %s") % getCurrentUserName(), \ |
---|
186 | size = (-1, -1), \ |
---|
187 | style = wx.DEFAULT_FRAME_STYLE \ |
---|
188 | | wx.SIZE_AUTO_HEIGHT \ |
---|
189 | | wx.SIZE_AUTO_WIDTH \ |
---|
190 | | wx.NO_FULL_REPAINT_ON_RESIZE) |
---|
191 | try : |
---|
192 | self.tbicon = wx.TaskBarIcon() |
---|
193 | except AttributeError : |
---|
194 | self.tbicon = None # No taskbar icon facility |
---|
195 | |
---|
196 | self.greenicon = wx.Icon(os.path.join(iconsdir, "pykoticon-green.ico"), \ |
---|
197 | wx.BITMAP_TYPE_ICO) |
---|
198 | self.redicon = wx.Icon(os.path.join(iconsdir, "pykoticon-red.ico"), \ |
---|
199 | wx.BITMAP_TYPE_ICO) |
---|
200 | |
---|
201 | self.SetIcon(self.greenicon) |
---|
202 | if self.tbicon is not None : |
---|
203 | self.tbicon.SetIcon(self.greenicon, "PyKotIcon") |
---|
204 | wx.EVT_TASKBAR_LEFT_DCLICK(self.tbicon, self.OnTaskBarActivate) |
---|
205 | wx.EVT_TASKBAR_RIGHT_UP(self.tbicon, self.OnTaskBarMenu) |
---|
206 | |
---|
207 | self.TBMENU_RESTORE = wx.NewId() |
---|
208 | self.TBMENU_CLOSE = wx.NewId() |
---|
209 | wx.EVT_MENU(self.tbicon, self.TBMENU_RESTORE, \ |
---|
210 | self.OnTaskBarActivate) |
---|
211 | wx.EVT_MENU(self.tbicon, self.TBMENU_CLOSE, \ |
---|
212 | self.OnTaskBarClose) |
---|
213 | self.menu = wx.wxMenu() |
---|
214 | self.menu.Append(self.TBMENU_RESTORE, _("Show Print Quota")) |
---|
215 | self.menu.Append(self.TBMENU_CLOSE, _("Quit")) |
---|
216 | |
---|
217 | wx.EVT_ICONIZE(self, self.OnIconify) |
---|
218 | wx.EVT_CLOSE(self, self.OnClose) |
---|
219 | self.Show(True) |
---|
220 | |
---|
221 | def OnIconify(self, event) : |
---|
222 | if not self.IsIconized() : |
---|
223 | self.Iconize(True) |
---|
224 | #self.Hide() |
---|
225 | |
---|
226 | def OnTaskBarActivate(self, event) : |
---|
227 | if self.IsIconized() : |
---|
228 | self.Iconize(False) |
---|
229 | if not self.IsShown() : |
---|
230 | self.Show(True) |
---|
231 | self.Raise() |
---|
232 | |
---|
233 | def OnClose(self, event) : |
---|
234 | self.closeServer() |
---|
235 | if hasattr(self, "menu") : |
---|
236 | self.menu.Destroy() |
---|
237 | del self.menu |
---|
238 | if hasattr(self, "tbicon") and self.tbicon : |
---|
239 | self.tbicon.Destroy() |
---|
240 | del self.tbicon |
---|
241 | self.Destroy() |
---|
242 | |
---|
243 | def OnTaskBarMenu(self, event) : |
---|
244 | if self.tbicon : |
---|
245 | self.tbicon.PopupMenu(self.menu) |
---|
246 | |
---|
247 | def OnTaskBarClose(self, event) : |
---|
248 | self.Close() |
---|
249 | |
---|
250 | def showDialog(self, message, yesno) : |
---|
251 | """Opens a notification dialog.""" |
---|
252 | self.dialogAnswer = None |
---|
253 | if yesno : |
---|
254 | caption = _("Confirmation") |
---|
255 | style = wx.YES_NO | wx.YES_DEFAULT | wx.ICON_QUESTION |
---|
256 | else : |
---|
257 | caption = _("Information") |
---|
258 | style = wx.OK | wx.ICON_INFORMATION |
---|
259 | style |= wx.STAY_ON_TOP |
---|
260 | dialog = wx.MessageDialog(self, message, caption, style) |
---|
261 | self.dialogAnswer = ((dialog.ShowModal() == wx.ID_NO) and "CANCEL") or "OK" |
---|
262 | dialog.Destroy() |
---|
263 | |
---|
264 | def askDatas(self, labels, varnames, varvalues) : |
---|
265 | """Opens a dialog box asking for data entry.""" |
---|
266 | # use it this way : self.askDatas(["Username", "Password", "Billing code"], ["username", "password", "billingcode"]) |
---|
267 | self.dialogAnswer = None |
---|
268 | dialog = GenericInputDialog(self, wx.ID_ANY, labels, varnames, varvalues) |
---|
269 | retvalues = {} |
---|
270 | if dialog.ShowModal() == wx.ID_OK : |
---|
271 | retvalues["isValid"] = True |
---|
272 | for i in range(len(varnames)) : |
---|
273 | retvalues[varnames[i]] = dialog.variables[i].GetValue() |
---|
274 | else : |
---|
275 | retvalues["isValid"] = False |
---|
276 | for k in varvalues.keys() : |
---|
277 | retvalues[k] = "" |
---|
278 | self.dialogAnswer = retvalues |
---|
279 | dialog.Destroy() |
---|
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 | |
---|
302 | class 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 | |
---|
312 | def 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 | |
---|
330 | def 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 | |
---|
340 | if __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") |
---|