Debian Codegraph @

Nagstamon/qui/widgets/system_tray_icon.py

raw
1 # Nagstamon - Nagios status monitor for your desktop
2 # Copyright (C) 2008-2026 Henri Wahl <[email protected]> et al.
3 #
4 # This program is free software; you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation; either version 2 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program; if not, write to the Free Software
16 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
17
18 from os import (environ,
19 sep)
20 from sys import stdout
21 from traceback import print_exc
22
23 from Nagstamon.config import (conf,
24 debug_queue,
25 OS,
26 OS_MACOS,
27 RESOURCES, OS_NON_LINUX)
28 from Nagstamon.qui.globals import (resource_files,
29 statuswindow_properties)
30 from Nagstamon.qui.qt import (QCursor,
31 QMenu,
32 QPainter,
33 QPixmap,
34 QSvgRenderer,
35 QSystemTrayIcon,
36 Qt,
37 QTimer,
38 QXmlStreamReader,
39 Signal,
40 Slot)
41 from Nagstamon.qui.widgets.icon import QIconWithFilename
42 from Nagstamon.servers import get_worst_status
43
44
45 class SystemTrayIcon(QSystemTrayIcon):
46 """
47 Icon in system tray, works at least in Windows and OSX
48 Several Linux desktop environments have different problems
49
50 For some dark, very dark reason systray menu does NOT work in
51 Windows if run on commandline as nagstamon.py - the binary .exe works
52 """
53 show_popwin = Signal()
54 hide_popwin = Signal()
55
56 # flag for displaying error icon in case of error
57 error_shown = False
58
59 def __init__(self):
60 # debug environment variables
61 if conf.debug_mode:
62 for environment_key, environment_value in environ.items():
63 debug_queue.append(f'DEBUG: Environment variable: {environment_key}={environment_value}')
64
65 # initialize systray icon
66 QSystemTrayIcon.__init__(self)
67
68 # icons are in dictionary
69 self.icons = {}
70 self.create_icons()
71 # empty icon for flashing notification
72 self.icons['EMPTY'] = QIconWithFilename(f'{RESOURCES}{sep}nagstamon_systrayicon_empty.svg')
73 # little workaround to match statuswindow.worker_notification.worst_notification_status
74 self.icons['UP'] = self.icons['OK']
75 # default icon is OK
76 if conf.icon_in_systray:
77 self.setIcon(self.icons['OK'])
78
79 # store icon for flashing
80 self.current_icon = None
81
82 # no menu at first
83 self.menu = None
84
85 # timer for singleshots for flashing
86 self.timer = QTimer()
87
88 # treat clicks
89 self.activated.connect(self.icon_clicked)
90
91 def current_icon_name(self):
92 """
93 internal function useful for debugging, returns the name of the
94 current icon
95 """
96 current_account_icon = self.icon()
97 if current_account_icon is None:
98 return '<none>'
99 return str(current_account_icon)
100
101 @Slot(QMenu)
102 def set_menu(self, menu):
103 """
104 create current menu for right clicks
105 """
106 # store menu for future use, especially for MacOSX
107 self.menu = menu
108
109 # MacOSX does not distinguish between left and right click so menu will go to upper menu bar
110 # update: apparently not, but own context menu will be shown when icon is clicked an all is OK = green
111 if OS != OS_MACOS:
112 self.setContextMenu(self.menu)
113
114 @Slot()
115 def create_icons(self):
116 """
117 create icons from template, applying colors
118 """
119 svg_template = f'{RESOURCES}{sep}nagstamon_systrayicon_template.svg'
120 # get template from file
121 # by using RESOURCE_FILES the file path will be checked on macOS and the file restored if necessary
122 with open(resource_files[svg_template]) as svg_template_file:
123 svg_template_xml = svg_template_file.readlines()
124
125 # create icons for all states
126 for state in ['OK', 'INFORMATION', 'UNKNOWN', 'WARNING', 'AVERAGE', 'HIGH', 'CRITICAL', 'DISASTER',
127 'UNREACHABLE', 'DOWN', 'ERROR']:
128 # current SVG XML for state icon, derived from svg_template_cml
129 svg_state_xml = list()
130
131 # replace dummy text and background colors with configured ones
132 for line in svg_template_xml:
133 line = line.replace('fill:#ff00ff', 'fill:' + conf.__dict__['color_' + state.lower() + '_text'])
134 line = line.replace('fill:#00ff00',
135 'fill:' + conf.__dict__['color_' + state.lower() + '_background'])
136 svg_state_xml.append(line)
137
138 # create XML stream of SVG
139 svg_xml_stream = QXmlStreamReader(''.join(svg_state_xml))
140 # create renderer for SVG and put SVG XML into renderer
141 svg_renderer = QSvgRenderer(svg_xml_stream)
142 # pixmap to be painted on - arbitrarily choosen 128x128 px
143 svg_pixmap = QPixmap(128, 128)
144 # fill transparent backgound
145 svg_pixmap.fill(Qt.GlobalColor.transparent)
146 # initiate painter which paints onto paintdevice pixmap
147 svg_painter = QPainter(svg_pixmap)
148 # render svg to pixmap
149 svg_renderer.render(svg_painter)
150 # close painting
151 svg_painter.end()
152 # put pixmap into icon
153 self.icons[state] = QIconWithFilename(svg_pixmap)
154
155 debug_queue.append(f'DEBUG: SystemTrayIcon created icon {self.icons[state]} for state "{state}"')
156
157 @Slot(QSystemTrayIcon.ActivationReason)
158 def icon_clicked(self, reason):
159 """
160 evaluate mouse click
161 """
162 # retrieve icon position and store it in statuswindow_properties
163 self.retrieve_icon_position()
164
165 if reason in (QSystemTrayIcon.ActivationReason.Trigger,
166 QSystemTrayIcon.ActivationReason.DoubleClick,
167 QSystemTrayIcon.ActivationReason.MiddleClick):
168 # when green icon is displayed and no popwin is about to pop up...
169 if get_worst_status() == 'UP':
170 # ...nothing to do except on macOS where menu should be shown
171 if OS == OS_MACOS:
172 # in case there is some error show popwin rather than context menu
173 if not self.error_shown:
174 self.menu.show_at_cursor()
175 else:
176 self.show_popwin.emit()
177 else:
178 # show status window if there is something to tell
179 if statuswindow_properties.is_shown:
180 self.hide_popwin.emit()
181 else:
182 self.show_popwin.emit()
183
184 @Slot()
185 def retrieve_icon_position(self):
186 """
187 get the coordinates of the systray icon and store it in statuswindow_properties
188 """
189 # where is the pointer which clicked onto systray icon
190 icon_x = self.geometry().x()
191 icon_y = self.geometry().y()
192 if OS in OS_NON_LINUX:
193 if statuswindow_properties.icon_x == 0:
194 statuswindow_properties.icon_x = QCursor.pos().x()
195 elif icon_x != 0:
196 statuswindow_properties.icon_x = icon_x
197 else:
198 # strangely enough on KDE the systray icon geometry gives back 0, 0 as coordinates
199 # also at Ubuntu Unity 16.04
200 if icon_x == 0 and statuswindow_properties.icon_x == 0:
201 statuswindow_properties.icon_x = QCursor.pos().x()
202 elif icon_x != 0:
203 statuswindow_properties.icon_x = icon_x
204
205 if icon_y == 0 and statuswindow_properties.icon_y == 0:
206 statuswindow_properties.icon_y = QCursor.pos().y()
207
208 if OS in OS_NON_LINUX:
209 if statuswindow_properties.icon_y == 0:
210 statuswindow_properties.icon_y = QCursor.pos().y()
211 elif icon_y != 0:
212 statuswindow_properties.icon_y = icon_y
213
214 pass
215
216 @Slot()
217 def show_state(self):
218 """
219 get the worst status and display it in systray
220 """
221 if not self.error_shown:
222 worst_status = get_worst_status()
223 self.setIcon(self.icons[worst_status])
224 # set current icon for flashing
225 self.current_icon = self.icons[worst_status]
226 del worst_status
227 else:
228 self.setIcon(self.icons['ERROR'])
229
230 @Slot()
231 def flash(self):
232 """
233 send color inversion signal to labels
234 """
235 # only if currently a notification is necessary
236 if statuswindow_properties.is_notifying:
237 # store current icon to get it reset back
238 if self.current_icon is None:
239 if not self.error_shown:
240 self.current_icon = self.icons[statuswindow_properties.worst_notification_status]
241 else:
242 self.current_icon = self.icons['ERROR']
243 # use empty SVG icon to display emptiness
244 if resource_files[self.icons['EMPTY'].filename]:
245 self.setIcon(self.icons['EMPTY'])
246 # fire up a singleshot to reset color soon
247 self.timer.singleShot(500, self.reset)
248
249 @Slot()
250 def reset(self):
251 """
252 tell labels to set original colors
253 """
254 # only if currently a notification is necessary
255 if statuswindow_properties.is_notifying:
256 try:
257 # set curent status icon
258 self.setIcon(self.current_icon)
259 # even later call itself to invert colors as flash
260 self.timer.singleShot(500, self.flash)
261 except:
262 print_exc(file=stdout)
263 else:
264 if self.current_icon is not None:
265 self.setIcon(self.current_icon)
266 self.current_icon = None
267
268 @Slot()
269 def set_error(self):
270 self.error_shown = True
271
272 @Slot()
273 def reset_error(self):
274 self.error_shown = False