-
Notifications
You must be signed in to change notification settings - Fork 89
/
applet.py
479 lines (415 loc) · 16.8 KB
/
applet.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
#!/usr/bin/python3
## Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, 2014 Red Hat, Inc.
## Author: Tim Waugh <[email protected]>
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
## This program is distributed in the hope that it will be useful,
## but WITHOUT ANY WARRANTY; without even the implied warranty of
## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
## GNU General Public License for more details.
## You should have received a copy of the GNU General Public License
## along with this program; if not, write to the Free Software
## Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
import cups
from functools import reduce
cups.require ("1.9.42")
import sys
import socket
import getpass
from debug import *
import dbus
# set up global default main loop
from dbus.mainloop.glib import DBusGMainLoop
DBusGMainLoop(set_as_default=True)
import dbus.service
import gi
from gi.repository import GObject
from gi.repository import GLib
import time
import locale
import cupshelpers.installdriver
DOMAIN="system-config-printer"
import gettext
gettext.install(domain=DOMAIN)
try:
locale.setlocale (locale.LC_ALL, "")
except locale.Error as e:
import os
os.environ['LC_ALL'] = 'C'
locale.setlocale (locale.LC_ALL, "")
gi.require_version('Notify', '0.7')
from gi.repository import Notify
APPDIR="/usr/share/system-config-printer"
ICON="printer"
# We need to call Notify.init before we can check the server for caps
Notify.init('System Config Printer Notification')
# D-Bus APIs of other objects we'll use.
PRINTING_BUS="org.fedoraproject.Config.Printing"
PRINTING_PATH="/org/fedoraproject/Config/Printing"
PRINTING_IFACE="org.fedoraproject.Config.Printing"
NEWPRINTERDIALOG_IFACE=PRINTING_IFACE + ".NewPrinterDialog"
PRINTERPROPERTIESDIALOG_IFACE=PRINTING_IFACE + ".PrinterPropertiesDialog"
####
#### NewPrinterNotification DBus server (the 'new' way).
####
PDS_PATH="/com/redhat/NewPrinterNotification"
PDS_IFACE="com.redhat.NewPrinterNotification"
PDS_OBJ="com.redhat.NewPrinterNotification"
class NewPrinterNotification(dbus.service.Object):
STATUS_SUCCESS = 0
STATUS_MODEL_MISMATCH = 1
STATUS_GENERIC_DRIVER = 2
STATUS_NO_DRIVER = 3
def __init__ (self, system_bus, session_bus):
self.system_bus = system_bus
self.session_bus = session_bus
self.getting_ready = 0
bus_name = dbus.service.BusName (PDS_OBJ, bus=system_bus)
dbus.service.Object.__init__ (self, bus_name, PDS_PATH)
self.notification = None
@dbus.service.method(PDS_IFACE, in_signature='', out_signature='')
def GetReady (self):
TIMEOUT=1200000
if self.getting_ready == 0:
n = Notify.Notification.new (_("Configuring new printer"),
_("Please wait..."),
'printer')
n.set_timeout (TIMEOUT + 5000)
n.closed = False
n.connect ('closed', self.on_notification_closed)
n.show ()
self.notification = n
self.getting_ready += 1
GLib.timeout_add_seconds (TIMEOUT, self.timeout_ready)
def on_notification_closed (self, notification):
notification.closed = True
def timeout_ready (self):
if self.getting_ready > 0:
self.getting_ready -= 1
if (self.getting_ready == 0 and
self.notification and
not getattr (self.notification, 'closed', None)):
self.notification.close ()
return False
@dbus.service.method(PDS_IFACE, in_signature='isssss', out_signature='')
def NewPrinter (self, status, name, mfg, mdl, des, cmd):
if name.find("/") >= 0:
# name is a URI, no queue was generated, because no suitable
# driver was found
title = _("Missing printer driver")
devid = "MFG:%s;MDL:%s;DES:%s;CMD:%s;" % (mfg, mdl, des, cmd)
if (mfg and mdl) or des:
if (mfg and mdl):
device = "%s %s" % (mfg, mdl)
else:
device = des
text = _("No printer driver for %s.") % device
else:
text = _("No driver for this printer.")
n = Notify.Notification.new (title, text, 'printer')
if "actions" in Notify.get_server_caps():
n.set_urgency (Notify.Urgency.CRITICAL)
n.set_timeout (Notify.EXPIRES_NEVER)
n.add_action ("setup-printer", _("Search"),
lambda x, y:
self.setup_printer (x, y, name, devid))
else:
self.setup_printer (None, None, name, devid)
else:
# name is the name of the queue which hal_lpadmin has set up
# automatically.
c = cups.Connection ()
try:
printer = c.getPrinters ()[name]
except KeyError:
return
try:
filename = c.getPPD (name)
except cups.IPPError:
return
del c
# Check for missing packages
cups.ppdSetConformance (cups.PPD_CONFORM_RELAXED)
ppd = cups.PPD (filename)
import os
os.unlink (filename)
import sys
sys.path.append (APPDIR)
import cupshelpers
(missing_pkgs,
missing_exes) = cupshelpers.missingPackagesAndExecutables (ppd)
from cupshelpers.ppds import ppdMakeModelSplit
(make, model) = ppdMakeModelSplit (printer['printer-make-and-model'])
driver = make + " " + model
if status < self.STATUS_GENERIC_DRIVER:
title = _("Printer added")
else:
title = _("Missing printer driver")
if len (missing_pkgs) > 0:
pkgs = reduce (lambda x,y: x + ", " + y, missing_pkgs)
title = _("Install printer driver")
text = (_("`%s' requires driver installation: %s.") %
(name, pkgs))
n = Notify.Notification.new (title, text, 'printer')
import installpackage
if "actions" in Notify.get_server_caps():
try:
self.packagekit = installpackage.PackageKit ()
n.set_timeout (Notify.EXPIRES_NEVER)
n.add_action ("install-driver", _("Install"),
lambda x, y:
self.install_driver (x, y,
missing_pkgs))
except:
pass
else:
try:
self.packagekit = installpackage.PackageKit ()
self.packagekit.InstallPackageName (0, 0,
missing_pkgs[0])
except:
pass
elif status == self.STATUS_SUCCESS:
devid = "MFG:%s;MDL:%s;DES:%s;CMD:%s;" % (mfg, mdl, des, cmd)
text = _("`%s' is ready for printing.") % name
n = Notify.Notification.new (title, text, 'printer')
if "actions" in Notify.get_server_caps():
n.set_urgency (Notify.Urgency.NORMAL)
n.add_action ("test-page", _("Print test page"),
lambda x, y:
self.print_test_page (x, y, name))
n.add_action ("configure", _("Configure"),
lambda x, y: self.configure (x, y, name))
else: # Model mismatch
devid = "MFG:%s;MDL:%s;DES:%s;CMD:%s;" % (mfg, mdl, des, cmd)
text = (_("`%s' has been added, using the `%s' driver.") %
(name, driver))
n = Notify.Notification.new (title, text, 'printer')
if "actions" in Notify.get_server_caps():
n.set_urgency (Notify.Urgency.CRITICAL)
n.add_action ("test-page", _("Print test page"),
lambda x, y:
self.print_test_page (x, y, name, devid))
n.add_action ("find-driver", _("Find driver"),
lambda x, y:
self.find_driver (x, y, name, devid))
n.set_timeout (Notify.EXPIRES_NEVER)
else:
self.configure (None, None, name)
self.timeout_ready ()
n.show ()
self.notification = n
def print_test_page (self, notification, action, name):
path = self.configure (None, None, name)
obj = self.session_bus.get_object (PRINTING_BUS, path)
iface = dbus.Interface (obj, PRINTERPROPERTIESDIALOG_IFACE)
iface.PrintTestPage ()
def configure (self, notification, action, name):
obj = self.session_bus.get_object (PRINTING_BUS, PRINTING_PATH)
iface = dbus.Interface (obj, PRINTING_IFACE)
return iface.PrinterPropertiesDialog (dbus.UInt32(0), name)
def get_newprinterdialog_interface (self):
obj = self.session_bus.get_object (PRINTING_BUS, PRINTING_PATH)
iface = dbus.Interface (obj, PRINTING_IFACE)
path = iface.NewPrinterDialog ()
obj = self.session_bus.get_object (PRINTING_BUS, path)
iface = dbus.Interface (obj, NEWPRINTERDIALOG_IFACE)
return iface
def ignore_dbus_replies (self, *args):
pass
def find_driver (self, notification, action, name, devid = ""):
try:
iface = self.get_newprinterdialog_interface ()
iface.ChangePPD (dbus.UInt32(0), name, devid,
reply_handler=self.ignore_dbus_replies,
error_handler=self.ignore_dbus_replies)
except dbus.DBusException:
pass
def setup_printer (self, notification, action, uri, devid = ""):
try:
iface = self.get_newprinterdialog_interface ()
iface.NewPrinterFromDevice (dbus.UInt32(0), uri, devid,
reply_handler=self.ignore_dbus_replies,
error_handler=self.ignore_dbus_replies)
except dbus.DBusException:
pass
def install_driver (self, notification, action, missing_pkgs):
try:
self.packagekit.InstallPackageName (0, 0, missing_pkgs[0])
except:
pass
def collect_exit_code (self, pid):
# We do this with timers instead of signals because we already
# have GLib imported, but don't (yet) import signal;
# let's try not to inflate the process size.
import os
try:
print("Waiting for child %d" % pid)
(pid, status) = os.waitpid (pid, os.WNOHANG)
if pid == 0:
# Run this timer again.
return True
except OSError:
pass
return False
PROGRAM_NAME="system-config-printer-applet"
def show_help ():
print("usage: %s [--help|--version|--debug]" % PROGRAM_NAME)
def show_version ():
import config
print("%s %s" % (PROGRAM_NAME, config.VERSION))
####
#### Main program entry
####
def monitor_session (*args):
pass
def any_jobs ():
try:
c = cups.Connection ()
jobs = c.getJobs (my_jobs=True, limit=1)
if len (jobs):
return True
except:
pass
return False
class RunLoop:
DBUS_PATH="/com/redhat/PrinterSpooler"
DBUS_IFACE="com.redhat.PrinterSpooler"
def __init__ (self, session_bus, system_bus, loop):
self.system_bus = system_bus
self.session_bus = session_bus
self.loop = loop
self.timer = None
try:
system_bus.add_signal_receiver (self.handle_dbus_signal,
path=self.DBUS_PATH,
dbus_interface=self.DBUS_IFACE)
except dbus.DBusException as e:
try:
print ("%s: failed to add D-Bus signal receiver: %s" \
% (PROGRAM_NAME, e), file=sys.stderr)
finally:
sys.exit (1)
self.check_for_jobs ()
def remove_signal_receiver (self):
try:
self.system_bus.remove_signal_receiver (self.handle_dbus_signal,
path=self.DBUS_PATH,
dbus_interface=self.DBUS_IFACE)
except dbus.DBusException as e:
try:
print ("%s: failed to remove D-Bus signal receiver: %s" \
% (PROGRAM_NAME, e), file=sys.stderr)
except:
pass
def run (self):
self.loop.run ()
def __del__ (self):
self.remove_signal_receiver ()
if self.timer:
GLib.source_remove (self.timer)
def handle_dbus_signal (self, *args):
if self.timer:
GLib.source_remove (self.timer)
self.timer = GLib.timeout_add (200, self.check_for_jobs)
def check_for_jobs (self, *args):
debugprint ("checking for jobs")
if any_jobs ():
if self.timer is not None:
GLib.source_remove (self.timer)
self.remove_signal_receiver ()
# Start the job applet.
debugprint ("Starting job applet")
try:
obj = self.session_bus.get_object (PRINTING_BUS, PRINTING_PATH)
iface = dbus.Interface (obj, PRINTING_IFACE)
path = iface.JobApplet ()
debugprint ("Job applet is %s" % path)
except dbus.DBusException as e:
try:
print(e)
except:
pass
# Don't run this timer again.
return False
if __name__ == '__main__':
import sys, getopt
try:
opts, args = getopt.gnu_getopt (sys.argv[1:], '',
['debug',
'help',
'version'])
except getopt.GetoptError:
show_help ()
sys.exit (1)
for opt, optarg in opts:
if opt == "--help":
show_help ()
sys.exit (0)
if opt == "--version":
show_version ()
sys.exit (0)
elif opt == "--debug":
set_debugging (True)
# Must be done before connecting to D-Bus (for some reason).
if not Notify.init (PROGRAM_NAME):
try:
print(("%s: unable to initialize pynotify" %
PROGRAM_NAME), file=sys.stderr)
except:
pass
system_bus = session_bus = None
try:
system_bus = dbus.SystemBus()
except:
try:
print(("%s: failed to connect to system D-Bus" %
PROGRAM_NAME), file=sys.stderr)
finally:
sys.exit (1)
try:
session_bus = dbus.SessionBus()
# Stop running when the session ends.
session_bus.add_signal_receiver (monitor_session)
except:
try:
print(("%s: failed to connect to "
"session D-Bus" % PROGRAM_NAME), file=sys.stderr)
finally:
sys.exit (1)
try:
NewPrinterNotification(system_bus, session_bus)
except:
try:
print(("%s: failed to start "
"NewPrinterNotification service" %
PROGRAM_NAME), file=sys.stderr)
except:
pass
try:
cupshelpers.installdriver.set_debugprint_fn (debugprint)
cupshelpers.installdriver.PrinterDriversInstaller(system_bus)
except Exception as e:
try:
print(("%s: failed to start "
"PrinterDriversInstaller service: "
"%s" % (PROGRAM_NAME, e)), file=sys.stderr)
except:
pass
try:
sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
# Create an abstract socket, by prefixing it with null.
sock.bind("\0printer-applet-lock-user-" + getpass.getuser())
except socket.error as err:
error_code = err.args[0]
error_string = err.args[1]
print("Process already running ({0}:{1}). Exiting.".format(error_code, error_string))
sys.exit(0)
loop = GLib.MainLoop ()
runloop = RunLoop (session_bus, system_bus, loop)
try:
runloop.run ()
except KeyboardInterrupt:
pass