summaryrefslogtreecommitdiff
path: root/ui4/systemtray.py
blob: 5c30e921c448a5dbfabe05d48ab457928de3fb4e (plain)
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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# (c) Copyright 2003-2008 Hewlett-Packard Development Company, L.P.
#
# 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., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
#
# Author: Don Welch

# Std Lib
import sys
import struct
import select
import os
import signal
import os.path


# Local
from base.g import *
from base import device, utils
from base.codes import *
from ui_utils import *

# PyQt
try:
    from PyQt4.QtCore import *
    from PyQt4.QtGui import *
except ImportError:
    log.error("Python bindings for Qt4 not found. Try using --qt3. Exiting!")
    sys.exit(1)

from systrayframe import SystrayFrame

# dbus
try:
    import dbus
    #import dbus.service
    from dbus import SessionBus, lowlevel
    #from dbus.mainloop.qt import DBusQtMainLoop
except ImportError:
    log.error("Python bindings for dbus not found. Exiting!")
    sys.exit(1)
    
    
    

TRAY_MESSAGE_DELAY = 10000
HIDE_INACTIVE_DELAY = 5000
BLIP_DELAY = 2000

ERROR_STATE_TO_ICON = {
    ERROR_STATE_CLEAR: QSystemTrayIcon.Information, 
    ERROR_STATE_OK: QSystemTrayIcon.Information,
    ERROR_STATE_WARNING: QSystemTrayIcon.Warning,
    ERROR_STATE_ERROR: QSystemTrayIcon.Critical,
    ERROR_STATE_LOW_SUPPLIES: QSystemTrayIcon.Warning,
    ERROR_STATE_BUSY: QSystemTrayIcon.Warning,
    ERROR_STATE_LOW_PAPER: QSystemTrayIcon.Warning,
    ERROR_STATE_PRINTING: QSystemTrayIcon.Information,
    ERROR_STATE_SCANNING: QSystemTrayIcon.Information,
    ERROR_STATE_PHOTOCARD: QSystemTrayIcon.Information,
    ERROR_STATE_FAXING: QSystemTrayIcon.Information,
    ERROR_STATE_COPYING: QSystemTrayIcon.Information,
}


class SystraySettingsDialog(QDialog):
    def __init__(self, parent, systray_visible, polling, 
                 polling_interval, device_list=None):
                     
        QDialog.__init__(self, parent)
        
        self.systray_visible = systray_visible
        
        if device_list is not None:
            self.device_list = device_list
        else:
            self.device_list = {}
            
        self.polling = polling
        self.polling_interval = polling_interval
        
        self.initUi()
        self.SystemTraySettings.updateUi()
    
    
    def initUi(self):
        self.setObjectName("SystraySettingsDialog")
        self.resize(QSize(QRect(0,0,488,565).size()).expandedTo(self.minimumSizeHint()))

        self.gridlayout = QGridLayout(self)
        self.gridlayout.setObjectName("gridlayout")

        self.SystemTraySettings = SystrayFrame(self)
        self.SystemTraySettings.initUi(self.systray_visible, 
                                       self.polling, self.polling_interval, 
                                       self.device_list)
        
        sizePolicy = QSizePolicy(QSizePolicy.Expanding,QSizePolicy.Expanding)
        sizePolicy.setHorizontalStretch(0)
        sizePolicy.setVerticalStretch(0)
        sizePolicy.setHeightForWidth(self.SystemTraySettings.sizePolicy().hasHeightForWidth())
        self.SystemTraySettings.setSizePolicy(sizePolicy)
        self.SystemTraySettings.setFrameShadow(QFrame.Raised)
        self.SystemTraySettings.setObjectName("SystemTraySettings")
        self.gridlayout.addWidget(self.SystemTraySettings,0,0,1,2)

        spacerItem = QSpacerItem(301,20,QSizePolicy.Expanding,QSizePolicy.Minimum)
        self.gridlayout.addItem(spacerItem,1,0,1,1)

        self.StdButtons = QDialogButtonBox(self)
        self.StdButtons.setStandardButtons(QDialogButtonBox.Cancel|QDialogButtonBox.NoButton|QDialogButtonBox.Ok)
        self.StdButtons.setCenterButtons(False)
        self.StdButtons.setObjectName("StdButtons")
        self.gridlayout.addWidget(self.StdButtons,1,1,1,1)

        QObject.connect(self.StdButtons, SIGNAL("accepted()"), self.acceptClicked)
        QObject.connect(self.StdButtons, SIGNAL("rejected()"), self.reject)
        #QMetaObject.connectSlotsByName(self)

        self.setWindowTitle(self.__tr("HP Device Manager - System Tray Settings"))
    
    
    def acceptClicked(self):
        self.systray_visible = self.SystemTraySettings.systray_visible
        self.polling = self.SystemTraySettings.polling
        self.polling_interval = self.SystemTraySettings.polling_interval
        self.device_list = self.SystemTraySettings.device_list
        self.accept()
    

    def __tr(self, s, c=None):
        return QApplication.translate("SystraySettingsDialog", s, c, QApplication.UnicodeUTF8)



class SystemTrayApp(QApplication):
    def __init__(self, args, read_pipe):
        QApplication.__init__(self, args)

        self.read_pipe = read_pipe
        self.fmt = "64s64sI32sI64sf"
        self.fmt_size = struct.calcsize(self.fmt)
        #print self.fmt_size
        self.timer_active = False
        self.active_icon = False
        self.user_settings = UserSettings()
        self.user_settings.load()
        
        self.tray_icon = QSystemTrayIcon()
        
        pm = load_pixmap("prog", "48x48") #, (22, 22))
        self.prop_icon = QIcon(pm)
        
        a = load_pixmap('active', '16x16')
        painter = QPainter(pm)
        painter.drawPixmap(32, 0, a)
        painter.end()
        
        self.prop_active_icon = QIcon(pm)
        
        #icon = QIcon(self.prop_active_icon)
        self.tray_icon.setIcon(self.prop_icon)

        self.menu = QMenu()

        title = QWidgetAction(self.menu)
        title.setDisabled(True)

        hbox = QFrame(self.menu)
        layout = QHBoxLayout(hbox)
        layout.setMargin(3)
        layout.setSpacing(5)
        pix_label = QLabel(hbox)

        layout.insertWidget(-1, pix_label, 0)

        icon_size = self.menu.style().pixelMetric(QStyle.PM_SmallIconSize)
        pix_label.setPixmap(self.prop_icon.pixmap(icon_size))

        label = QLabel(hbox)
        layout.insertWidget(-1, label, 20)
        title.setDefaultWidget(hbox)

        label.setText(self.__tr("HPLIP Status Service"))

        f = label.font()
        f.setBold(True)
        label.setFont(f)
        self.menu.insertAction(None, title)

        self.menu.addSeparator()
        self.menu.addAction(self.__tr("HP Device Manager..."), self.toolboxTriggered)

        self.menu.addSeparator()
        
        self.settings_action = self.menu.addAction(QIcon(load_pixmap('settings', '16x16')), 
                                    self.__tr("Settings..."),  self.settingsTriggered)

        self.menu.addSeparator()
        self.menu.addAction(QIcon(load_pixmap('quit', '16x16')), "Quit", self.quitTriggered)
        self.tray_icon.setContextMenu(self.menu)
        
        self.tray_icon.setToolTip(self.__tr("HPLIP Status Service"))

        QObject.connect(self.tray_icon, SIGNAL("messageClicked()"), self.messageClicked)
        
        notifier = QSocketNotifier(self.read_pipe, QSocketNotifier.Read)
        QObject.connect(notifier, SIGNAL("activated(int)"), self.notifierActivated)

        QObject.connect(self.tray_icon, SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.trayActivated)

        self.tray_icon.show()

        if self.user_settings.systray_visible == SYSTRAY_VISIBLE_SHOW_ALWAYS:
            self.tray_icon.setVisible(True)
        else: 
            QTimer.singleShot(HIDE_INACTIVE_DELAY, self.timeoutHideWhenInactive) # show icon for awhile @ startup

    
    def settingsTriggered(self):
        self.sendMessage('', '', EVENT_DEVICE_STOP_POLLING)
        try:
            dlg = SystraySettingsDialog(self.menu, self.user_settings.systray_visible, 
                                        self.user_settings.polling, self.user_settings.polling_interval,
                                        self.user_settings.polling_device_list)
            
            if dlg.exec_() == QDialog.Accepted:
                self.user_settings.systray_visible = dlg.systray_visible
                    
                self.user_settings.polling_interval = dlg.polling_interval
                self.polling_timer.setInterval(self.user_settings.polling_interval * 1000)

                self.user_settings.polling_device_list = dlg.device_list
                
                self.user_settings.polling = dlg.polling
                
                if self.user_settings.polling and not self.polling_timer.isActive():
                    self.polling_timer.start()
                
                elif not self.user_settings.polling and self.polling_timer.isActive():
                    self.polling_timer.stop()
                
                self.user_settings.save()
                
                if self.user_settings.systray_visible == SYSTRAY_VISIBLE_SHOW_ALWAYS:
                    log.debug("Showing...")
                    self.tray_icon.setVisible(True)
                    
                else:
                    log.debug("Waiting to hide...")
                    QTimer.singleShot(HIDE_INACTIVE_DELAY, self.timeoutHideWhenInactive)
                    
                self.sendMessage('', '', EVENT_USER_CONFIGURATION_CHANGED)
                
        finally:
            self.sendMessage('', '', EVENT_DEVICE_START_POLLING)
            
            
    def timeoutHideWhenInactive(self):
        log.debug("Hiding...")
        if self.user_settings.systray_visible in (SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE, SYSTRAY_VISIBLE_HIDE_ALWAYS): 
            self.tray_icon.setVisible(False)
            log.debug("Hidden")
            

    def trayActivated(self, reason):
        if reason == QSystemTrayIcon.Context:
            #print "context menu"
            pass

        elif reason == QSystemTrayIcon.DoubleClick:
            #print "double click"
            self.toolboxTriggered()
            pass

        elif reason == QSystemTrayIcon.Trigger:
            #print "single click"
            pass

        elif reason == QSystemTrayIcon.MiddleClick:
            #print "middle click"
            pass


    def messageClicked(self):
        #print "\nPARENT: message clicked"
        pass


    def quitTriggered(self):
        log.debug("Exiting")
        self.sendMessage('', '', EVENT_SYSTEMTRAY_EXIT)
        self.quit()


    def toolboxTriggered(self):
        try:
            os.waitpid(-1, os.WNOHANG)
        except OSError:
            pass

        # See if it is already running...
        ok, lock_file = utils.lock_app('hp-toolbox', True)

        if ok: # able to lock, not running...
            utils.unlock(lock_file)

            path = utils.which('hp-toolbox')
            if path:
                path = os.path.join(path, 'hp-toolbox')
            else:
                self.tray_icon.showMessage(self.__tr("HPLIP Status Service"), 
                                self.__tr("Unable to locate hp-toolbox on system PATH."),
                                QSystemTrayIcon.Critical, TRAY_MESSAGE_DELAY)

                log.error("Unable to find hp-toolbox on PATH.")
                return

            #log.debug(path)
            log.debug("Running hp-toolbox: hp-toolbox --qt4")
            os.spawnlp(os.P_NOWAIT, path, 'hp-toolbox',  '--qt4')

        else: # ...already running, raise it
            self.sendMessage('', '', EVENT_RAISE_DEVICE_MANAGER, interface='com.hplip.Toolbox')
            

    def sendMessage(self, device_uri, printer_name, event_code, username=prop.username, 
                    job_id=0, title='', pipe_name='', interface='com.hplip.StatusService'):
        device.Event(device_uri, printer_name, event_code, username, job_id, title).send_via_dbus(SessionBus(), interface)
        

    def notifierActivated(self, s):
        m = ''
        while True:
            r, w, e = select.select([self.read_pipe], [], [self.read_pipe], 1.0)

            if e:
                log.error("Pipe error: %s" % e)
                break

            if r:
                m = ''.join([m, os.read(self.read_pipe, self.fmt_size)])
                while len(m) >= self.fmt_size:
                    event = device.Event(*struct.unpack(self.fmt, m[:self.fmt_size]))
                    m = m[self.fmt_size:]
                    
                    if event.event_code == EVENT_USER_CONFIGURATION_CHANGED:
                        log.debug("Re-reading configuration (EVENT_USER_CONFIGURATION_CHANGED)")
                        self.user_settings.load()

                    if self.user_settings.systray_visible in \
                        (SYSTRAY_VISIBLE_SHOW_ALWAYS, SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE):
                        
                        log.debug("Showing...")
                        self.tray_icon.setVisible(True)
                        
                        if event.event_code == EVENT_DEVICE_UPDATE_ACTIVE:
                            if not self.active_icon: 
                                self.tray_icon.setIcon(self.prop_active_icon)
                                self.active_icon = True
                            continue
                            
                        elif event.event_code == EVENT_DEVICE_UPDATE_INACTIVE:
                            if self.active_icon:
                                self.tray_icon.setIcon(self.prop_icon)
                                self.active_icon = False
                            continue
                            
                        elif event.event_code == EVENT_DEVICE_UPDATE_BLIP:
                            if not self.active_icon: 
                                self.tray_icon.setIcon(self.prop_active_icon)
                                self.active_icon = True
                                QTimer.singleShot(BLIP_DELAY, self.blipTimeout)
                            continue

                    if self.user_settings.systray_visible == SYSTRAY_VISIBLE_HIDE_WHEN_INACTIVE:
                        log.debug("Waiting to hide...")
                        QTimer.singleShot(HIDE_INACTIVE_DELAY, self.timeoutHideWhenInactive)
                    
                    if event.event_code <= EVENT_MAX_USER_EVENT and self.tray_icon.supportsMessages():
                        log.debug("Tray icon message:")
                        event.debug()
                        
                        error_state = STATUS_TO_ERROR_STATE_MAP.get(event.event_code, ERROR_STATE_CLEAR)
                        icon = ERROR_STATE_TO_ICON.get(error_state, QSystemTrayIcon.Information)
                        desc = device.queryString(event.event_code)

                        if event.job_id and event.title:
                            log.debug("Bubble: uri=%s desc=%s title=%s user=%s job_id=%d code=%d" % 
                                      (event.device_uri, desc, event.title, event.username, event.job_id, event.event_code))
                            self.tray_icon.showMessage(self.__tr("HPLIP Device Status"), 
                                QString("%1\n%2: %3\n(%4/%5)").\
                                arg(event.device_uri).\
                                arg(desc).arg(event.title).\
                                arg(event.username).arg(event.job_id),
                                icon, TRAY_MESSAGE_DELAY)
                        
                        else:
                            log.debug("Bubble: uri=%s desc=%s code=%d" % (event.device_uri, desc, event.event_code))
                            self.tray_icon.showMessage(self.__tr("HPLIP Device Status"), 
                                QString("%1\n%2 (%3)").arg(event.device_uri).\
                                arg(desc).arg(event.event_code),
                                icon, TRAY_MESSAGE_DELAY)

            else:
                break


    def blipTimeout(self):
        if self.active_icon:
            self.tray_icon.setIcon(self.prop_icon)
            self.active_icon = False
        


    def __tr(self, s, c=None):
        return QApplication.translate("SystemTray", s, c, QApplication.UnicodeUTF8)

    

def run(read_pipe):
    log.set_module("hp-systray(qt4)")
    log.debug("PID=%d" % os.getpid())

    app = SystemTrayApp(sys.argv, read_pipe)
    app.setQuitOnLastWindowClosed(False) # If not set, settings dlg closes app
    
    if not QSystemTrayIcon.isSystemTrayAvailable():
        FailureUI(None, 
            QApplication.translate("SystemTray", 
            "<b>No system tray detected on this system.</b><p>Unable to start, exiting.</p>", 
            None, QApplication.UnicodeUTF8),
            QApplication.translate("SystemTray", "HPLIP Status Service", 
            None, QApplication.UnicodeUTF8))
    else:
        notifier = QSocketNotifier(read_pipe, QSocketNotifier.Read)
        QObject.connect(notifier, SIGNAL("activated(int)"), app.notifierActivated)

        app.exec_()