Tizen 2.1 base
[platform/upstream/hplip.git] / toolbox.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3 #
4 # (c) Copyright 2003-2009 Hewlett-Packard Development Company, L.P.
5 #
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
10 #
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
19 #
20 # Author: Don Welch
21 #
22 # Thanks to Henrique M. Holschuh <hmh@debian.org> for various security patches
23 #
24
25 __version__ = '15.0'
26 __mod__ = 'hp-toolbox'
27 __title__ = 'HP Device Manager'
28 __doc__ = """The HP Device Manager (aka "Toolbox") for HPLIP supported devices. Provides access to status, tools, and supplies levels."""
29
30 # Std Lib
31 import sys
32 import os
33 import getopt
34 import signal
35
36 # Local
37 from base.g import *
38 import base.utils as utils
39 from base import status, tui, module
40
41
42 w = None # write pipe
43 app = None
44 toolbox  = None
45 session_bus = None
46
47
48 def handle_session_signal(*args, **kwds):
49     if kwds['interface'] == 'com.hplip.Toolbox' and \
50         kwds['member'] == 'Event':
51
52         event = device.Event(*args)
53         event.debug()
54
55         if event.event_code > EVENT_MAX_EVENT:
56             event.event_code = status.MapPJLErrorCode(event.event_code)
57
58         # regular user/device status event
59         log.debug("Received event notifier: %d" % event.event_code)
60
61         if not event.send_via_pipe(w, 'toolbox ui'):
62             sys.exit(1)
63             # if this fails, then hp-toolbox must be killed.
64             # No need to continue running...
65
66
67 mod = module.Module(__mod__, __title__, __version__, __doc__, None,
68                     (GUI_MODE,), (UI_TOOLKIT_QT3, UI_TOOLKIT_QT4))
69 mod.lockInstance()
70
71 mod.setUsage(module.USAGE_FLAG_NONE,
72              extra_options=[("Disable dbus (Qt3 only):", "-x or --disable-dbus", "option", False)],
73              see_also_list = ['hp-align', 'hp-clean', 'hp-colorcal', 'hp-devicesettings',
74                               'hp-faxsetup', 'hp-firmware', 'hp-info', 'hp-levels',
75                               'hp-linefeedcal', 'hp-makecopies', 'hp-plugin',
76                               'hp-pqdiag', 'hp-print', 'hp-printsettings', 'hp-scan',
77                               'hp-sendfax', 'hp-testpage', 'hp-timedate', 'hp-unload'])
78
79 opts, device_uri, printer_name, mode, ui_toolkit, loc = \
80     mod.parseStdOpts('x', ['disable-dbus'])
81
82 disable_dbus = False
83
84 for o, a in opts:
85     if o in ('-x', '--disable-dbus') and ui_toolkit == 'qt3':
86         disable_dbus = True
87
88 if ui_toolkit == 'qt3':
89     if not utils.canEnterGUIMode():
90         log.error("%s requires GUI support. Exiting." % __mod__)
91         sys.exit(1)
92 elif ui_toolkit == 'qt4':
93     if not utils.canEnterGUIMode4():
94         log.error("%s requires GUI support. Exiting." % __mod__)
95         sys.exit(1)
96
97 child_pid, w, r = 0, 0, 0
98
99 if ui_toolkit == 'qt3':
100     try:
101         from dbus import SessionBus
102         import dbus.service
103         from dbus.mainloop.glib import DBusGMainLoop, threads_init
104         from gobject import MainLoop
105         import glib
106         glib.threads_init()
107         dbus.mainloop.glib.threads_init()
108     except ImportError:
109         log.error("Unable to load dbus - Automatic status updates in HPLIP Device Manager will be disabled.")
110         disable_dbus = True
111
112     if not disable_dbus:
113         r, w = os.pipe()
114         parent_pid = os.getpid()
115         log.debug("Parent PID=%d" % parent_pid)
116         child_pid = os.fork()
117
118     if disable_dbus or child_pid: # qt3/ui
119         # parent (UI)
120         log.set_module("hp-toolbox(UI)")
121
122         if w:
123             os.close(w)
124
125         try:
126             from qt import *
127             from ui.devmgr4 import DevMgr4
128         except ImportError:
129             log.error("Unable to load Qt3 support. Is it installed?")
130             sys.exit(1)
131
132         # create the main application object
133         app = QApplication(sys.argv)
134
135         if loc is None:
136             loc = user_conf.get('ui', 'loc', 'system')
137             if loc.lower() == 'system':
138                 loc = str(QTextCodec.locale())
139                 log.debug("Using system locale: %s" % loc)
140
141         if loc.lower() != 'c':
142             e = 'utf8'
143             try:
144                 l, x = loc.split('.')
145                 loc = '.'.join([l, e])
146             except ValueError:
147                 l = loc
148                 loc = '.'.join([loc, e])
149
150             log.debug("Trying to load .qm file for %s locale." % loc)
151             trans = QTranslator(None)
152
153             qm_file = 'hplip_%s.qm' % l
154             log.debug("Name of .qm file: %s" % qm_file)
155             loaded = trans.load(qm_file, prop.localization_dir)
156
157             if loaded:
158                 app.installTranslator(trans)
159             else:
160                 loc = 'c'
161
162         if loc == 'c':
163             log.debug("Using default 'C' locale")
164         else:
165             log.debug("Using locale: %s" % loc)
166             QLocale.setDefault(QLocale(loc))
167             prop.locale = loc
168             try:
169                 locale.setlocale(locale.LC_ALL, locale.normalize(loc))
170             except locale.Error:
171                 pass
172
173         toolbox = DevMgr4(r, __version__, device_uri, disable_dbus)
174         app.setMainWidget(toolbox)
175
176         toolbox.show()
177
178         try:
179             try:
180                 log.debug("Starting GUI loop...")
181                 app.exec_loop()
182             except KeyboardInterrupt:
183                 sys.exit(0)
184
185         finally:
186             if child_pid:
187                 log.debug("Killing child toolbox process (pid=%d)..." % child_pid)
188                 try:
189                     os.kill(child_pid, signal.SIGKILL)
190                 except OSError, e:
191                     log.debug("Failed: %s" % e.message)
192
193             mod.unlockInstance()
194             sys.exit(0)
195
196     elif not disable_dbus: # qt3/dbus
197         # dBus
198         log.set_module("hp-toolbox(dbus)")
199         from base import device
200
201         try:
202             # child (dbus connector)
203             os.close(r)
204
205             dbus_loop = DBusGMainLoop(set_as_default=True)
206
207             try:
208                 session_bus = dbus.SessionBus()
209             except dbus.exceptions.DBusException, e:
210                 if os.getuid() != 0:
211                     log.error("Unable to connect to dbus session bus. Exiting.")
212                     sys.exit(1)
213                 else:
214                     log.error("Unable to connect to dbus session bus (running as root?)")
215                     sys.exit(1)
216
217             # Receive events from the session bus
218             session_bus.add_signal_receiver(handle_session_signal, sender_keyword='sender',
219                 destination_keyword='dest', interface_keyword='interface',
220                 member_keyword='member', path_keyword='path')
221
222             log.debug("Entering main loop...")
223
224             try:
225                 MainLoop().run()
226             except KeyboardInterrupt:
227                 log.debug("Ctrl-C: Exiting...")
228
229         finally:
230             if parent_pid:
231                 log.debug("Killing parent toolbox process (pid=%d)..." % parent_pid)
232                 try:
233                     os.kill(parent_pid, signal.SIGKILL)
234                 except OSError, e:
235                     log.debug("Failed: %s" % e.message)
236
237             mod.unlockInstance()
238
239         sys.exit(0)
240
241 else: # qt4
242     try:
243         from PyQt4.QtGui import QApplication
244
245     except ImportError:
246         log.error("Unable to load Qt4 support. Is it installed?")
247         sys.exit(1)
248
249     from ui4.devmgr5 import DevMgr5
250
251     log.set_module("hp-toolbox(UI)")
252
253     if 1:
254     #try:
255         app = QApplication(sys.argv)
256
257         toolbox = DevMgr5(__version__, device_uri,  None)
258         toolbox.show()
259         try:
260             log.debug("Starting GUI loop...")
261             app.exec_()
262         except KeyboardInterrupt:
263             sys.exit(0)
264
265     if 1:
266     #finally:
267         mod.unlockInstance()
268         sys.exit(0)