Debian Codegraph @

Nagstamon/qui/widgets/statuswindow.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 sep
19 from pathlib import Path
20 from subprocess import Popen
21 import sys
22 from sys import stdout
23 from time import (sleep,
24 time)
25 from traceback import print_exc
26
27 from Nagstamon.config import (AppInfo,
28 conf,
29 DESKTOP_WAYLAND,
30 OS,
31 OS_MACOS,
32 OS_NON_LINUX,
33 OS_WINDOWS,
34 RESOURCES, debug_queue)
35 from Nagstamon.helpers import (STATES,
36 STATES_SOUND)
37 from Nagstamon.qui.constants import WINDOW_FLAGS
38 from Nagstamon.qui.globals import (dbus_connection,
39 statuswindow_properties)
40 from Nagstamon.qui.helpers import (get_screen_geometry,
41 get_screen_name,
42 hide_macos_dock_icon)
43 from Nagstamon.qui.qt import (QAction,
44 QCursor,
45 QIcon,
46 QMenuBar,
47 QMessageBox,
48 QObject,
49 QVBoxLayout,
50 QScrollArea,
51 QSizePolicy,
52 QSpacerItem,
53 QThread,
54 QWidget,
55 Qt,
56 QT_VERSION_MAJOR,
57 QT_VERSION_MINOR,
58 QTimer,
59 Signal,
60 Slot)
61 from Nagstamon.qui.widgets.app import app
62 from Nagstamon.qui.widgets.labels import LabelAllOK
63 from Nagstamon.qui.widgets.server_vbox import ServerVBox
64 from Nagstamon.qui.widgets.statusbar import StatusBar
65 from Nagstamon.qui.widgets.toparea import TopArea
66 from Nagstamon.servers import (get_enabled_servers,
67 get_status_count,
68 servers)
69
70 # only on X11/Linux thirdparty path should be added because it contains the Xlib module
71 # needed to tell window manager via EWMH to keep Nagstamon window on all virtual desktops
72 if OS not in OS_NON_LINUX and not DESKTOP_WAYLAND:
73 # extract thirdparty path from resources path - make submodules accessible by thirdparty modules
74 sys.path.insert(0, sep.join(RESOURCES.split(sep)[0:-1] + ['thirdparty']))
75
76 # Xlib for EWMH needs the file ~/.Xauthority and crashes if it does not exist
77 xauthority_file = Path().home() / '.Xauthority'
78 if not xauthority_file.exists():
79 open(xauthority_file, 'a').close()
80
81 from Nagstamon.thirdparty.ewmh import EWMH
82
83
84 class StatusWindow(QWidget):
85 """
86 Consists of statusbar, toparea and scrolling area.
87 Either statusbar is shown or (toparea + scrolling area)
88 """
89 # sent by .resize_window()
90 resizing = Signal()
91
92 # send when windows opens, e.g. for stopping notifications
93 showing = Signal()
94
95 # send when window shrinks down to statusbar or closes
96 hiding = Signal()
97
98 # signal to be sent to all server workers to recheck all
99 recheck = Signal()
100
101 # signal to submit server to authentication dialog
102 authenticate = Signal(str)
103
104 # signal to be sent to all treeview workers to clear server event history
105 # after 'Refresh'-button has been pressed
106 clear_event_history = Signal()
107
108 # signals for changing the state of the system tray icon
109 systrayicon_enabled = Signal()
110 systrayicon_disabled = Signal()
111
112 # signal to request systray icon position for storing it in statuswindow_properties
113 request_systrayicon_position = Signal()
114
115 # shortcut to systray icon needed for connecting signals/slots
116 injected_systrayicon = None
117
118 # cached coordinates
119 stored_x = 0
120 stored_y = 0
121 stored_height = 0
122 stored_width = 0
123
124 def __init__(self, dialogs=None, systrayicon=None):
125 """
126 Status window combined from status bar and popup window
127 """
128 QWidget.__init__(self)
129
130 # immediately hide to avoid flicker on Windows and OSX
131 self.hide()
132
133 # avoid quitting when using Qt.Tool flag and closing settings dialog
134 app.setQuitOnLastWindowClosed(False)
135
136 # show tooltips even if popup window has no focus
137 self.setAttribute(Qt.WidgetAttribute.WA_AlwaysShowToolTips)
138 # title + icon
139 self.setWindowTitle(AppInfo.NAME)
140 self.setWindowIcon(QIcon(f'{RESOURCES}{sep}nagstamon.svg'))
141
142 if OS == OS_MACOS:
143 # avoid hiding window if it has no focus - necessary on OSX if using flag Qt.Tool
144 self.setAttribute(Qt.WidgetAttribute.WA_MacAlwaysShowToolWindow)
145
146 # ewmh.py in thirdparty directory needed to keep floating statusbar on all desktops in Linux
147 if not OS in OS_NON_LINUX and not DESKTOP_WAYLAND:
148 self.ewmh = EWMH()
149
150 # set shortcut for dialogs icon to be used for connecting signals/slots
151 self.injected_dialogs = dialogs
152 # set shortcut for systray icon to be used for connecting signals/slots
153 self.injected_systrayicon = systrayicon
154
155 self.vbox = QVBoxLayout(self) # global VBox
156 self.vbox.setSpacing(0) # no spacing
157 self.vbox.setContentsMargins(0, 0, 0, 0) # no margin
158
159 self.statusbar = StatusBar(parent=self) # statusbar HBox
160 self.toparea = TopArea(parent=self) # toparea HBox
161 # no need to be seen first
162 self.toparea.hide()
163
164 self.servers_scrollarea = QScrollArea(self) # scrollable area for server vboxes
165 # avoid horizontal scrollbars
166 self.servers_scrollarea.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAlwaysOff)
167 # necessary widget to contain vbox for servers
168 self.servers_scrollarea_widget = QWidget(self.servers_scrollarea)
169 self.servers_scrollarea.hide()
170
171 self.vbox.addWidget(self.statusbar)
172 self.vbox.addWidget(self.toparea)
173 self.vbox.addWidget(self.servers_scrollarea)
174
175 self.servers_vbox = QVBoxLayout(self.servers_scrollarea) # VBox full of servers
176 self.servers_vbox.setSpacing(0)
177 self.servers_vbox.setContentsMargins(0, 0, 0, 0)
178
179 self.label_all_ok = LabelAllOK(parent=self)
180 self.label_all_ok.hide()
181 self.servers_vbox.addWidget(self.label_all_ok)
182
183 # test with OSX top menubar
184 if OS == OS_MACOS:
185 self.menubar = QMenuBar()
186 action_exit = QAction('exit', self.menubar)
187 action_settings = QAction('settings', self.menubar)
188 self.menubar.addAction(action_settings)
189 self.menubar.addAction(action_exit)
190
191 # stored x y values for systemtray icon
192 statuswindow_properties.icon_x = 0
193 statuswindow_properties.icon_y = 0
194
195 # if status_ok is true no server_vboxes are needed
196 statuswindow_properties.status_ok = True
197
198 # timer for waiting to set is_shown flag
199 self.timer = QTimer(self)
200
201 # react to open button in notification bubble
202 dbus_connection.open_statuswindow.connect(self.show_window_from_notification_bubble)
203
204 # connect logo of statusbar
205 self.statusbar.logo.window_moved.connect(self.save_position)
206 self.statusbar.logo.window_moved.connect(self.hide_window)
207 self.statusbar.logo.window_moved.connect(self.correct_moving_position)
208 self.statusbar.logo.window_moved.connect(self.update)
209 self.statusbar.logo.mouse_pressed.connect(self.save_position)
210
211 # after status summarization check if window has to be resized
212 self.statusbar.resize.connect(self.adjust_size)
213
214 # statusbar label has been entered by mouse -> show
215 for label in self.statusbar.color_labels.values():
216 label.mouse_entered.connect(self.show_window_after_checking_for_hover)
217 label.mouse_released.connect(self.show_window_after_checking_for_clicking)
218 label.mouse_released_in_window.connect(self.hide_window)
219
220 # connect message label to hover
221 self.statusbar.label_message.mouse_entered.connect(self.show_window_after_checking_for_hover)
222 self.statusbar.label_message.mouse_released.connect(self.show_window_after_checking_for_clicking)
223 self.statusbar.label_message.mouse_released_in_window.connect(self.hide_window)
224
225 # when logo in toparea was pressed hurry up to save the position so the statusbar will not jump
226 self.toparea.logo.window_moved.connect(self.save_position)
227 self.toparea.logo.window_moved.connect(self.hide_window)
228 self.toparea.logo.window_moved.connect(self.correct_moving_position)
229 self.toparea.logo.window_moved.connect(self.update)
230 self.toparea.logo.mouse_pressed.connect(self.save_position)
231 self.toparea.logo.mouse_released_in_window.connect(self.hide_window)
232
233 # when version label in toparea was pressed hurry up to save the position so the statusbar will not jump
234 self.toparea.label_version.window_moved.connect(self.save_position)
235 self.toparea.label_version.window_moved.connect(self.hide_window)
236 self.toparea.label_version.window_moved.connect(self.correct_moving_position)
237 self.toparea.label_version.window_moved.connect(self.update)
238 self.toparea.label_version.mouse_pressed.connect(self.save_position)
239 self.toparea.label_version.mouse_released_in_window.connect(self.hide_window)
240
241 # when empty space in toparea was pressed hurry up to save the position so the statusbar will not jump
242 self.toparea.label_empty_space.window_moved.connect(self.save_position)
243 self.toparea.label_empty_space.window_moved.connect(self.hide_window)
244 self.toparea.label_empty_space.window_moved.connect(self.correct_moving_position)
245 self.toparea.label_empty_space.window_moved.connect(self.update)
246 self.toparea.label_empty_space.mouse_pressed.connect(self.save_position)
247 self.toparea.label_empty_space.mouse_released_in_window.connect(self.hide_window)
248
249 # buttons in toparea
250 self.toparea.button_recheck_all.clicked.connect(self.recheck_all)
251 self.toparea.button_refresh.clicked.connect(self.refresh)
252 self.toparea.button_settings.clicked.connect(self.hide_window)
253 self.toparea.button_close.clicked.connect(self.hide_window)
254
255 # if monitor was selected in combobox its monitor window is opened
256 self.toparea.combobox_servers.monitor_opened.connect(self.hide_window)
257
258 # due to lack of a better place the 'Delete cookies' button action is defined here
259 self.injected_dialogs.weblogin.delete_web_cookies.connect(
260 self.injected_dialogs.server.delete_web_cookies_action)
261 self.injected_dialogs.server.delete_web_cookies.connect(self.injected_dialogs.server.delete_web_cookies_action)
262
263 self.initialize()
264
265 def initialize(self):
266 """
267 initialize the volatile widgets of the status window
268 """
269 # needed to store position of status window
270 self.stored_y = 0
271 self.stored_x = 0
272 self.stored_width = 0
273 self.stored_height = 0
274
275 # worker and thread duo needed for notifications
276 self.worker_notification_thread = QThread(parent=self)
277 self.worker_notification = self.WorkerNotification(statuswindow_properties)
278
279 # clean shutdown of thread
280 self.worker_notification.finish.connect(self.finish_worker_notification_thread)
281
282 # flashing statusbar
283 self.worker_notification.start_flash.connect(self.statusbar.flash)
284 self.worker_notification.stop_flash.connect(self.statusbar.reset)
285
286 # desktop notification
287 self.worker_notification.desktop_notification.connect(self.desktop_notification)
288
289 # stop notification if window gets shown or hidden
290 self.hiding.connect(self.worker_notification.stop)
291
292 self.hiding.connect(self.move_while_hiding)
293
294 self.worker_notification.moveToThread(self.worker_notification_thread)
295 # start with low priority
296 self.worker_notification_thread.start(QThread.Priority.LowestPriority)
297
298 self.create_server_vboxes()
299
300 # connect status window server vboxes to systray
301 for server_vbox in self.servers_vbox.children():
302 if 'server' in server_vbox.__dict__.keys():
303 # tell systray after table was refreshed
304 server_vbox.table.worker.new_status.connect(self.injected_systrayicon.show_state)
305 # show error icon in systray
306 server_vbox.table.worker.show_error.connect(self.injected_systrayicon.set_error)
307 server_vbox.table.worker.hide_error.connect(self.injected_systrayicon.reset_error)
308
309 self.servers_scrollarea_widget.setLayout(self.servers_vbox)
310 self.servers_scrollarea.setWidget(self.servers_scrollarea_widget)
311 self.servers_scrollarea.setWidgetResizable(True)
312
313 # needed for moving the statuswindow
314 statuswindow_properties.moving = False
315 statuswindow_properties.relative_x = 0
316 statuswindow_properties.relative_y = 0
317
318 # helper values for QTimer.singleShot move attempt
319 self.move_to_x = self.move_to_y = 0
320
321 # flag to mark if window is shown or not
322 if conf.windowed:
323 statuswindow_properties.is_shown = True
324 else:
325 statuswindow_properties.is_shown = False
326
327 # store show_window timestamp to avoid flickering window in KDE5 with systray
328 statuswindow_properties.is_shown_timestamp = time()
329
330 # store timestamp to avoid reappearing window shortly after clicking onto toparea
331 statuswindow_properties.is_hiding_timestamp = time()
332
333 # a thread + worker is necessary to do actions thread-safe in background
334 # like debugging
335 self.worker_thread = QThread(parent=self)
336 self.worker = self.Worker()
337 self.worker.moveToThread(self.worker_thread)
338 # start thread and debugging loop if debugging is enabled
339 if conf.debug_mode:
340 self.worker_thread.started.connect(self.worker.debug_loop)
341 # start with low priority
342 self.worker_thread.start(QThread.Priority.LowestPriority)
343
344 # clean shutdown of thread
345 self.worker.finish.connect(self.finish_worker_thread)
346
347 # finally show up
348 self.set_mode()
349
350 @Slot()
351 def reinitialize(self):
352 """
353 delete volatile widgets and initialize them again
354 """
355 # stop both workers
356 if hasattr(self, 'worker'):
357 self.worker.running = False
358 self.worker.finish.emit()
359 if hasattr(self, 'worker_notification'):
360 self.worker_notification.running = False
361 self.worker_notification.finish.emit()
362 # remove all server vboxes
363 if hasattr(self, 'servers_vbox'):
364 for vbox in self.servers_vbox.children():
365 if hasattr(vbox, 'table') and hasattr(vbox.table, 'worker'):
366 vbox.table.worker.finish.emit()
367 vbox.deleteLater()
368 # initialize all volatile widgets
369 self.initialize()
370
371 def get_screen(self):
372 """
373 very hackish fix for https://github.com/HenriWahl/Nagstamon/issues/865
374 should actually fit into qt.py but due to the reference to `app` it could only
375 be solved here
376 """
377 # Qt6 has .screen() as replacement for QDesktopWidget...
378 if QT_VERSION_MAJOR > 5:
379 return self.screen()
380 # ...and .screen() exists since Qt5 5.15...
381 elif QT_VERSION_MINOR < 15:
382 return app.desktop()
383 # ...so newer ones can use .screen() again
384 else:
385 return self.screen()
386
387 def set_mode(self):
388 """
389 apply presentation mode
390 """
391 # hide everything first
392 self.hide()
393 self.statusbar.hide()
394 self.toparea.hide()
395 self.servers_scrollarea.hide()
396
397 # restore to normal window in case it was fullscreen
398 self.showNormal()
399
400 if conf.statusbar_floating:
401 # show icon in dock if window is set
402 if OS == OS_MACOS:
403 # in floating mode always show dock icon - right now I am not able to
404 # get the icon hidden
405 hide_macos_dock_icon(False)
406
407 # no need for systray
408 self.systrayicon_disabled.emit()
409
410 self.statusbar.show()
411
412 # show statusbar/statuswindow on last saved position
413 # when coordinates are inside known screens
414 if get_screen_name(conf.position_x, conf.position_y):
415 self.move(conf.position_x, conf.position_y)
416 else:
417 # get available desktop specs
418 available_x = self.get_screen().availableGeometry().x()
419 available_y = self.get_screen().availableGeometry().y()
420 self.move(available_x, available_y)
421
422 # statusbar and detail window should be frameless and stay on top
423 # tool flag helps to be invisible in taskbar
424 self.setWindowFlags(WINDOW_FLAGS)
425
426 # show statusbar without being active, just floating
427 self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
428
429 # necessary to be shown before Linux EWMH-mantra can be applied
430 self.show()
431
432 # X11/Linux needs some special treatment to get the statusbar floating on all virtual desktops
433 if OS not in OS_NON_LINUX and not DESKTOP_WAYLAND:
434 # get all windows...
435 self.ewmh.setWmDesktop(self.winId().__int__(), 0xffffffff)
436 self.ewmh.display.flush()
437
438 # show statusbar/statuswindow on last saved position
439 # when coordinates are inside known screens
440 if get_screen_name(conf.position_x, conf.position_y):
441 self.move(conf.position_x, conf.position_y)
442 else:
443 # get available desktop specs
444 available_x = self.get_screen().availableGeometry().x()
445 available_y = self.get_screen().availableGeometry().y()
446 self.move(available_x, available_y)
447
448 # need a close button
449 self.toparea.button_close.show()
450
451 elif conf.icon_in_systray:
452 # no need for icon in dock if in systray
453 if OS == OS_MACOS:
454 hide_macos_dock_icon(conf.hide_macos_dock_icon)
455
456 # statusbar and detail window should be frameless and stay on top
457 # tool flag helps to be invisible in taskbar
458 self.setWindowFlags(WINDOW_FLAGS)
459
460 # show statusbar without being active, just floating
461 self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating)
462
463 # yeah! systray!
464 self.systrayicon_enabled.emit()
465
466 # need a close button
467 self.toparea.button_close.show()
468
469 # reset systray icon position
470 statuswindow_properties.icon_x = statuswindow_properties.icon_y = 0
471
472 elif conf.fullscreen:
473 # no need for systray
474 self.systrayicon_disabled.emit()
475
476 # needed permanently
477 self.toparea.show()
478 self.servers_scrollarea.show()
479
480 # get screen geometry to get right screen to position window on
481 screen_geometry = get_screen_geometry(conf.fullscreen_display)
482 self.move(screen_geometry.x(), screen_geometry.y())
483
484 # keep window entry in taskbar and thus no Qt.Tool
485 self.setWindowFlags(Qt.WindowType.Widget | Qt.WindowType.FramelessWindowHint)
486
487 # show statusbar actively
488 self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, False)
489
490 # newer Qt5 seem to be better regarding fullscreen mode on non-OSX
491 self.show_window()
492 # fullscreen mode is rather buggy on everything other than OSX so just use a maximized window
493 if OS == OS_MACOS:
494 self.showFullScreen()
495 # in fullscreen mode dock icon does not disturb because the dock is away anyway
496 hide_macos_dock_icon(False)
497 else:
498 self.show()
499 self.showMaximized()
500
501 # no need for close button
502 self.toparea.button_close.hide()
503
504 elif conf.windowed:
505 # show icon in dock if window is set
506 if OS == OS_MACOS:
507 # in windowed mode always show dock icon
508 hide_macos_dock_icon(False)
509
510 self.systrayicon_disabled.emit()
511
512 # no need for close button
513 self.toparea.button_close.hide()
514 self.toparea.show()
515 self.servers_scrollarea.show()
516
517 # keep window entry in taskbar and thus no Qt.Tool
518 self.setWindowFlags(Qt.WindowType.Widget)
519
520 # show statusbar actively
521 self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, False)
522
523 # some maybe sensible default
524 self.setMinimumSize(700, 300)
525 self.setSizePolicy(QSizePolicy.Policy.MinimumExpanding, QSizePolicy.Policy.MinimumExpanding)
526
527 # default maximum size
528 self.setMaximumSize(16777215, 16777215)
529
530 self.move(conf.position_x, conf.position_y)
531 self.resize(conf.position_width, conf.position_height)
532
533 # make sure window is shown
534 self.show()
535 self.showNormal()
536 self.show_window()
537
538 # make sure window comes up
539 self.raise_()
540
541 # force correct position of statuswindow
542 self.adjust_size()
543
544 # store position for showing/hiding statuswindow
545 self.stored_x = self.x()
546 self.stored_y = self.y()
547 self.stored_width = self.width()
548
549 def sort_server_vboxes(self):
550 """
551 sort ServerVBoxes alphabetically
552 """
553 # shortly after applying changes a QObject might hang around in the children list which should
554 # be filtered out this way
555 vboxes_dict = dict()
556 for child in self.servers_vbox.children():
557 if 'server' in child.__dict__.keys():
558 vboxes_dict[child.server.name] = child
559
560 # freshly set servers_scrollarea_widget and its layout servers_vbox
561 servers_vbox_new = QVBoxLayout() # VBox full of servers
562 servers_vbox_new.setContentsMargins(0, 0, 0, 0)
563 servers_vbox_new.setSpacing(0)
564
565 # sort server vboxes
566 for vbox in sorted(vboxes_dict):
567 vboxes_dict[vbox].setParent(None)
568 servers_vbox_new.addLayout(vboxes_dict[vbox])
569
570 # add expanding stretching item at the end for fullscreen beauty
571 servers_vbox_new.addSpacerItem(QSpacerItem(0, self.get_screen().availableGeometry().height(),
572 QSizePolicy.Policy.Minimum, QSizePolicy.Policy.Expanding))
573
574 # switch to new servers_vbox
575 self.servers_vbox = servers_vbox_new
576 # necessary widget to contain vbox for servers
577 self.servers_scrollarea_widget = QWidget()
578 self.servers_scrollarea_widget.setLayout(self.servers_vbox)
579 self.servers_scrollarea.setWidget(self.servers_scrollarea_widget)
580
581 self.servers_scrollarea.contentsMargins().setTop(0)
582 self.servers_scrollarea.contentsMargins().setBottom(0)
583
584 del vboxes_dict
585
586 @Slot(str)
587 def create_server_vbox(self, name):
588 """
589 internally used to create enabled servers to be displayed
590 """
591 server = servers[name]
592
593 # create server vboxed from current running servers
594 if server.enabled:
595 # display authentication dialog if password is not known
596 if not conf.servers[server.name].save_password and \
597 not conf.servers[server.name].use_autologin and \
598 conf.servers[server.name].password == '' and \
599 not conf.servers[server.name].authentication == 'kerberos' and \
600 not conf.servers[server.name].authentication == 'web':
601 self.authenticate.emit(server.name)
602
603 # without parent, there is some flickering when starting
604 server_vbox = ServerVBox(server, parent=self)
605
606 # important to set correct server to worker, especially after server changes
607 server_vbox.table.worker.server = server
608
609 # connect to global resize signal
610 server_vbox.table.ready_to_resize.connect(self.adjust_size)
611
612 # tell statusbar to summarize after table was refreshed
613 server_vbox.table.worker.new_status.connect(self.statusbar.summarize_states)
614 server_vbox.table.worker.new_status.connect(self.raise_window_on_all_desktops)
615
616 # if problems go themselves there is no need to notify user anymore
617 server_vbox.table.worker.problems_vanished.connect(self.worker_notification.stop)
618
619 # show the error message in statusbar
620 server_vbox.table.worker.show_error.connect(self.statusbar.set_error)
621 server_vbox.table.worker.hide_error.connect(self.statusbar.reset_error)
622
623 # tell notification worker to do something AFTER the table was updated
624 server_vbox.table.status_changed.connect(self.worker_notification.start)
625
626 # and to update status window
627 server_vbox.table.refreshed.connect(self.update_window)
628
629 # hide statuswindow if authentication dialog is to be shown
630 server_vbox.button_authenticate.clicked.connect(self.hide_window)
631
632 # tell table it should remove freshness of formerly new items when window closes
633 # because apparently the new events have been seen now
634 self.hiding.connect(server_vbox.table.worker.unfresh_event_history)
635
636 # stop notification if statuswindow pops up
637 self.showing.connect(self.worker_notification.stop)
638
639 # tell server worker to recheck all hosts and services
640 self.recheck.connect(server_vbox.table.worker.recheck_all)
641
642 # refresh table after changed settings
643 self.injected_dialogs.settings.changed.connect(server_vbox.table.refresh)
644 self.injected_dialogs.weblogin.page_loaded.connect(server_vbox.table.worker.get_status)
645
646 # listen if statuswindow cries for event history clearance
647 self.clear_event_history.connect(server_vbox.table.worker.unfresh_event_history)
648
649 # statuswindow.servers_vbox.addLayout(statuswindow.create_server_vbox(servers[server_name]))
650 self.servers_vbox.addLayout(server_vbox)
651 self.sort_server_vboxes()
652
653 return server_vbox
654 else:
655 return None
656
657 def create_server_vboxes(self):
658 """
659 create VBox for each enabled server
660 """
661 for server in servers.values():
662 if server.enabled:
663 server_vbox = self.create_server_vbox(server.name)
664 self.servers_vbox.addLayout(server_vbox)
665 self.sort_server_vboxes()
666
667 @Slot(str)
668 def delete_server_vbox(self, name):
669 """
670 delete VBox for server with given name - called by signal from settings dialog
671 """
672 for vbox in self.servers_vbox.children():
673 if vbox.server.name == name:
674 # stop thread by falsificate running flag
675 vbox.table.worker.running = False
676 vbox.table.worker.finish.emit()
677 break
678
679 @Slot()
680 def show_window_after_checking_for_clicking(self):
681 """
682 being called after clicking statusbar - check if window should be shown
683 """
684 if conf.popup_details_clicking:
685 self.show_window()
686
687 @Slot()
688 def show_window_after_checking_for_hover(self):
689 """
690 being called after hovering over statusbar - check if window should be shown
691 """
692 if conf.popup_details_hover:
693 self.show_window()
694
695 @Slot()
696 def show_window_from_notification_bubble(self):
697 """
698 show status window after button being clicked in notification bubble
699 """
700 if conf.statusbar_floating:
701 self.show_window()
702 elif conf.icon_in_systray:
703 self.show_window_systrayicon()
704
705 @Slot()
706 def show_window_systrayicon(self):
707 """
708 handle clicks onto systray icon
709 """
710 if not statuswindow_properties.is_shown:
711 # under unfortunate circumstances statusbar might have the the moving flag true
712 # fix it here because it makes no sense but might cause non-appearing statuswindow‚
713 statuswindow_properties.moving = False
714
715 # hopefully no race condition here and the systray icon position will be retrieved just in time
716 self.request_systrayicon_position.emit()
717
718 # already show here because was closed before in hide_window()
719 # best results achieved when doing .show() before .show_window()
720 self.show()
721 self.show_window()
722
723 # Wayland workaround: Force an immediate update to prevent a black rectangle
724 if DESKTOP_WAYLAND:
725 self.update()
726 else:
727 self.hide_window()
728
729 @Slot()
730 def show_window_for_authentication(self):
731 """
732 show status window for authentication if not already shown
733 especially needed for systray icon and floating mode
734 """
735 if not self.injected_dialogs.get_shown_dialogs():
736 if conf.icon_in_systray:
737 self.show_window_systrayicon()
738 elif conf.statusbar_floating:
739 self.show_window()
740
741 @Slot()
742 def show_window(self, event=None):
743 """
744 used to show status window when its appearance is triggered, also adjusts geometry
745 """
746 # do not show up when being dragged around
747 if not statuswindow_properties.moving:
748 # check if really all is OK
749 for vbox in self.servers_vbox.children():
750 if vbox.server.all_ok and \
751 vbox.server.status == '' and \
752 not vbox.server.refresh_authentication and \
753 not vbox.server.tls_error:
754 statuswindow_properties.status_ok = True
755 else:
756 statuswindow_properties.status_ok = False
757 break
758
759 # here we should check if scroll_area should be shown at all
760 if not statuswindow_properties.status_ok:
761 # store timestamp to avoid flickering as in https://github.com/HenriWahl/Nagstamon/issues/184
762 statuswindow_properties.is_shown_timestamp = time()
763
764 if not conf.fullscreen and not conf.windowed:
765 # attempt to avoid flickering on MacOSX - already hide statusbar here
766 self.statusbar.hide()
767 # show the other status window components
768 self.toparea.show()
769 self.servers_scrollarea.show()
770 else:
771 self.label_all_ok.hide()
772
773 for vbox in self.servers_vbox.children():
774 if not vbox.server.all_ok:
775 vbox.show_all()
776 # show at least server vbox header to notify about connection or other errors
777 elif vbox.server.status != '' or vbox.server.refresh_authentication or vbox.server.tls_error:
778 vbox.show_only_header()
779 elif vbox.server.all_ok and vbox.server.status == '':
780 vbox.hide_all()
781
782 # depending on authentication state show reauthentication button
783 if vbox.server.refresh_authentication:
784 vbox.button_authenticate.show()
785 else:
786 vbox.button_authenticate.hide()
787
788 # depending on TLS error show fix-TLS-button
789 if vbox.server.tls_error:
790 vbox.button_fix_tls_error.show()
791 else:
792 vbox.button_fix_tls_error.hide()
793
794 if not conf.fullscreen and \
795 not conf.windowed:
796 # theory...
797 width, height, x, y = self.calculate_size()
798 # ...and practice
799 self.resize_window(width, height, x, y)
800 # switch on
801 if OS == OS_MACOS:
802 # delayed because of flickering window in OSX
803 self.timer.singleShot(200, self.set_shown)
804 else:
805 self.set_shown()
806
807 # avoid horizontally scrollable tables
808 self.adjust_dummy_columns()
809
810 self.show()
811
812 # Using the EWMH protocol to move the window to the active desktop.
813 # Seemed to be a problem on XFCE
814 # https://github.com/HenriWahl/Nagstamon/pull/199
815 if not OS in OS_NON_LINUX and conf.icon_in_systray:
816 try:
817 winid = self.winId().__int__()
818 deskid = self.ewmh.getCurrentDesktop()
819 self.ewmh.setWmDesktop(winid, deskid)
820 self.ewmh.display.flush()
821 # makes the window manager switch to the desktop where this widget has appeared
822 self.raise_()
823 except Exception:
824 # workaround for https://github.com/HenriWahl/Nagstamon/issues/246#issuecomment-220478066
825 pass
826
827 # tell others like notification that statuswindow shows up now
828 self.showing.emit()
829
830 else:
831 # hide vboxes in fullscreen and whole window in any other case if all is OK
832 for vbox in self.servers_vbox.children():
833 vbox.hide_all()
834 if conf.fullscreen or conf.windowed:
835 self.label_all_ok.show()
836 if conf.icon_in_systray or conf.statusbar_floating:
837 self.hide_window()
838
839 # If the mouse cursor drives too fast over and out the window will not be hidden.
840 # Thus, we check again with this timer to catch missed mouse-outs.
841 # causes trouble in Wayland so is disabled for it
842 if conf.close_details_hover and \
843 conf.statusbar_floating and \
844 statuswindow_properties.is_shown and \
845 not DESKTOP_WAYLAND:
846 self.periodically_check_window_under_mouse_and_hide()
847
848 def periodically_check_window_under_mouse_and_hide(self):
849 """
850 Periodically check if window is under mouse and hide it if not
851 """
852 if not self.hide_window_if_not_under_mouse():
853 self.timer.singleShot(1000, self.periodically_check_window_under_mouse_and_hide)
854
855 def hide_window_if_not_under_mouse(self):
856 """
857 hide window if it is under mouse pointer
858 """
859 mouse_pos = QCursor.pos()
860 # Check mouse cursor over window and an opened context menu or dropdown list
861 if self.geometry().contains(mouse_pos.x(), mouse_pos.y()) or \
862 not app.activePopupWidget() is None or \
863 statuswindow_properties.is_shown:
864 return False
865
866 self.hide_window()
867 return True
868
869 @Slot()
870 def update_window(self):
871 """
872 redraw window content, to be effective only when window is shown
873 """
874 if statuswindow_properties.is_shown or \
875 conf.fullscreen or \
876 (conf.windowed and statuswindow_properties.is_shown):
877 self.show_window()
878
879 @Slot()
880 def hide_window(self):
881 """
882 hide window if not needed
883 """
884 if not conf.fullscreen and not conf.windowed:
885 # only hide if shown and not locked or if not yet hidden if moving
886 if statuswindow_properties.is_shown is True or \
887 statuswindow_properties.is_shown is True and \
888 statuswindow_properties.moving is True:
889 # only hide if shown at least a fraction of a second
890 # or has not been hidden a too short time ago
891 if statuswindow_properties.is_shown_timestamp + 0.5 < time() or \
892 statuswindow_properties.is_hiding_timestamp + 0.1 < time():
893 if conf.statusbar_floating:
894 self.statusbar.show()
895 self.toparea.hide()
896 self.servers_scrollarea.hide()
897 # macOS needs this since Qt6 to avoid statuswindow size changeability
898 # looks silly but works to force using the own hint as hint
899 if OS == OS_MACOS:
900 self.setMinimumSize(self.sizeHint())
901 self.setMaximumSize(self.sizeHint())
902 else:
903 self.setMinimumSize(1, 1)
904 self.adjustSize()
905
906 if conf.icon_in_systray:
907 self.close()
908 else:
909 # show again after reorganizing widgets
910 self.show()
911
912 # switch off
913 statuswindow_properties.is_shown = False
914
915 # flag to reflect top-ness of window/statusbar
916 statuswindow_properties.top = False
917
918 # reset icon x y
919 statuswindow_properties.icon_x = 0
920 statuswindow_properties.icon_y = 0
921
922 if conf.windowed:
923 self.hide()
924
925 # store time of hiding
926 statuswindow_properties.is_hiding_timestamp = time()
927
928 # tell the world that window goes down
929 self.hiding.emit()
930
931 @Slot()
932 def move_while_hiding(self):
933 """
934 silly workaround to avoid flickering window in floating mode
935 """
936 # give some rest to avoid flickering
937 sleep(0.0125)
938 # move the window to the last stored position
939 self.move(self.stored_x, self.stored_y)
940
941 @Slot()
942 def correct_moving_position(self):
943 """
944 correct position if moving and cursor started outside statusbar
945 """
946 if statuswindow_properties.moving:
947 mouse_x = QCursor.pos().x()
948 mouse_y = QCursor.pos().y()
949 # when cursor is outside moved window correct the coordinates of statusbar/statuswindow
950 if not self.geometry().contains(mouse_x, mouse_y):
951 rect = self.geometry()
952 corrected_x = int(mouse_x - rect.width() // 2)
953 corrected_y = int(mouse_y - rect.height() // 2)
954 # calculate new relative values
955 statuswindow_properties.relative_x = mouse_x - corrected_x
956 statuswindow_properties.relative_y = mouse_y - corrected_y
957 self.move(corrected_x, corrected_y)
958 del mouse_x, mouse_y, corrected_x, corrected_y
959
960 def calculate_size(self):
961 """
962 get size of popup window
963 """
964
965 # only consider offset if it is configured
966 if conf.systray_offset_use and conf.icon_in_systray:
967 available_height = self.get_screen().availableGeometry().height() - conf.systray_offset
968 else:
969 available_height = self.get_screen().availableGeometry().height()
970
971 available_width = self.get_screen().availableGeometry().width()
972 available_x = self.get_screen().availableGeometry().x()
973 available_y = self.get_screen().availableGeometry().y()
974
975 # Workaround for Cinnamon + GNOME Flashback
976 if OS not in OS_NON_LINUX and conf.enable_position_fix:
977 if available_x == 0:
978 available_x = available_width
979 if available_y == 0:
980 available_y = available_height
981
982 # take whole screen height into account when deciding about upper/lower-ness
983 # add available_y because it might vary on differently setup screens
984 # calculate top-ness only if window is closed
985 if conf.statusbar_floating:
986 if self.y() < self.get_screen().geometry().height() // 2 + available_y:
987 statuswindow_properties.top = True
988 else:
989 statuswindow_properties.top = False
990
991 # always take the stored position of the statusbar
992 x = self.stored_x
993
994 elif conf.icon_in_systray or conf.windowed:
995 # Wayland fallback for absolute coordinates
996 if DESKTOP_WAYLAND and statuswindow_properties.icon_x == 0:
997 statuswindow_properties.icon_x = available_x + available_width - 50
998 statuswindow_properties.icon_y = available_y + available_height
999
1000 # Determine top/bottom placement AFTER retrieving/setting coordinates
1001 if statuswindow_properties.icon_y < self.get_screen().geometry().height() // 2 + available_y:
1002 statuswindow_properties.top = True
1003 else:
1004 statuswindow_properties.top = False
1005
1006 # just a little buffer to let systrayicon.retrieve_icon_position() time to do its work, just in case
1007 while statuswindow_properties.icon_x == 0:
1008 sleep(0.01)
1009
1010 x = statuswindow_properties.icon_x
1011
1012 # get height from table widgets
1013 real_height = self.get_real_height()
1014
1015 # width simply will be the current screen maximal width - less hassle!
1016 if self.get_real_width() > available_width:
1017 width = available_width
1018 x = available_x
1019 else:
1020 width = self.get_real_width()
1021
1022 if width < self.toparea.sizeHint().width():
1023 width = self.toparea.sizeHint().width()
1024
1025 # always take the stored width of the statusbar into account
1026 x -= int(width // 2) + int(self.stored_width // 2)
1027
1028 # check left and right limits of x
1029 if x < available_x:
1030 x = available_x
1031 if x + width > available_x + available_width:
1032 x = available_x + available_width - width
1033
1034 if conf.statusbar_floating:
1035 # when statusbar resides in the uppermost part of current screen extend from top to bottom
1036 if statuswindow_properties.top:
1037 y = self.y()
1038 if self.y() + real_height < available_height + available_y:
1039 height = real_height
1040 else:
1041 height = available_height - self.y() + available_y
1042
1043 # when statusbar hangs around in lowermost part of current screen extend from bottom to top
1044 else:
1045 # when height is too large for current screen cut it
1046 if self.y() + self.height() - real_height < available_y:
1047 height = self.get_screen().geometry().height() - available_y - (
1048 self.get_screen().geometry().height() - (self.y() + self.height()))
1049 y = available_y
1050 else:
1051 height = real_height
1052 y = self.y() + self.height() - height
1053
1054 elif conf.icon_in_systray or conf.windowed:
1055 # when systrayicon resides in the uppermost part of current screen extend from top to bottom
1056 if statuswindow_properties.top:
1057 # when being top y is of course the available one
1058 y = available_y
1059 if self.y() + real_height < available_height + available_y:
1060 height = real_height
1061 else:
1062 # if bigger than screen shrink to maximal real_height
1063 height = available_height - available_y
1064 # when statusbar hangs around in lowermost part of current screen extend from bottom to top
1065 else:
1066 if available_height < real_height:
1067 y = available_y
1068 height = available_height
1069 else:
1070 y = available_height - real_height
1071 height = real_height
1072
1073 return width, height, x, y
1074
1075 def resize_window(self, width, height, x, y):
1076 """
1077 resize status window according to its new size
1078 """
1079 # store position for restoring it when hiding - only if not shown of course
1080 if statuswindow_properties.is_shown is False:
1081 self.stored_x = self.x()
1082 self.stored_y = self.y()
1083 self.stored_width = self.width()
1084 self.stored_height = self.height()
1085
1086 if OS == OS_WINDOWS:
1087 # absolutely strange, but no other solution available
1088 # - Only on Windows the statusbar is moving FIRST before resizing - no matter which
1089 # order was used
1090 # - Dirty workaround:
1091 # - store x and y in .move_to_*
1092 # - start helper move_timer by timer singleshot to give statusbar some time to hide
1093 self.move_to_x, self.move_to_y = x, y
1094 self.timer.singleShot(10, self.move_timer)
1095 else:
1096 self.move(x, y)
1097
1098 self.setMaximumSize(width, height)
1099 self.setMinimumSize(width, height)
1100
1101 self.adjustSize()
1102
1103 return True
1104
1105 @Slot()
1106 def move_timer(self):
1107 """
1108 helper for move by QTimer.singleShot - attempt to avoid flickering on Windows
1109 """
1110 self.move(self.move_to_x, self.move_to_y)
1111
1112 @Slot()
1113 def adjust_size(self):
1114 """
1115 resize window if shown and needed
1116 """
1117 # avoid race condition when waiting for password dialog
1118 if 'is_shown' in statuswindow_properties.__dict__:
1119 if not conf.fullscreen and not conf.windowed:
1120 # fully displayed statuswindow
1121 if statuswindow_properties.is_shown is True:
1122 width, height, x, y = self.calculate_size()
1123 self.adjust_dummy_columns()
1124 else:
1125 # statusbar only
1126 hint = self.sizeHint()
1127 # on MacOSX and Windows statusbar will not shrink automatically, so this workaround hopefully helps
1128 width = hint.width()
1129 height = hint.height()
1130 x = self.x()
1131 y = self.y()
1132 self.setMaximumSize(hint)
1133 self.setMinimumSize(hint)
1134 del hint
1135 self.resize_window(width, height, x, y)
1136
1137 del width, height, x, y
1138 else:
1139 self.adjust_dummy_columns()
1140
1141 @Slot()
1142 def adjust_dummy_columns(self):
1143 """
1144 calculate the widest width of all server tables to hide dummy column at the widest one
1145 """
1146 max_width = 0
1147 max_width_table = None
1148 for server in self.servers_vbox.children():
1149 # if table is wider than current max_width take its width as max_width
1150 if server.table.get_real_width() > max_width:
1151 max_width = server.table.get_real_width()
1152 max_width_table = server.table
1153
1154 # widest table does not need the dummy column #9
1155 for server in self.servers_vbox.children():
1156 if max_width_table == server.table and max_width == server.table.width():
1157 # hide dummy column as here is the most stretched table
1158 server.table.setColumnHidden(9, True)
1159 server.table.header().setStretchLastSection(False)
1160 else:
1161 # show dummy column because some other table is wider
1162 server.table.setColumnHidden(9, False)
1163 server.table.header().setStretchLastSection(True)
1164 del max_width, max_width_table
1165 return True
1166
1167 @Slot()
1168 def save_position(self):
1169 """
1170 store position for restoring it when hiding
1171 """
1172 if not statuswindow_properties.is_shown:
1173 self.stored_x = self.x()
1174 self.stored_y = self.y()
1175 self.stored_width = self.width()
1176 self.stored_height = self.height()
1177
1178 def leaveEvent(self, event):
1179 """
1180 check if popup has to be hidden depending on mouse position
1181 """
1182 # depending on display mode the leave time offset shall be different because
1183 # it may be too short in systray mode and lead to flickering window
1184 if conf.statusbar_floating:
1185 leave_time_offset = 0.25
1186 elif conf.icon_in_systray:
1187 # offset is max 1 and smaller if window is smaller too
1188 leave_time_offset = self.height() / self.get_screen().availableGeometry().height()
1189 else:
1190 leave_time_offset = 0
1191
1192 # check first if popup has to be shown by hovering or clicking
1193 if conf.close_details_hover and \
1194 not conf.fullscreen and \
1195 not conf.windowed and \
1196 statuswindow_properties.is_shown_timestamp + leave_time_offset < time():
1197 # only hide window if cursor is outside of it
1198 mouse_x = QCursor.pos().x()
1199 mouse_y = QCursor.pos().y()
1200 # <= and >= necessary because sometimes mouse_* is the same as self.*()
1201 if mouse_x <= self.x() or mouse_x >= self.x() + self.width() or \
1202 mouse_y <= self.y() or mouse_y >= self.y() + self.height():
1203 self.hide_window()
1204
1205 def closeEvent(self, event):
1206 """
1207 window close
1208 """
1209 # check first if popup has to be shown by hovering or clicking
1210 if conf.windowed:
1211 exit()
1212
1213 def get_real_width(self):
1214 """
1215 calculate the widest width of all server tables
1216 """
1217 width = 0
1218 for server in self.servers_vbox.children():
1219 # if table is wider than window adjust with to table
1220 if server.table.isVisible() and server.table.get_real_width() > width:
1221 width = server.table.get_real_width()
1222 # if header in server vbox is wider than width adjust the latter
1223 if server.header.sizeHint().width() > width:
1224 width = server.header.sizeHint().width()
1225 return width
1226
1227 def get_real_height(self):
1228 """
1229 calculate summary of all heights of all server tables plus height of toparea
1230 """
1231 height = 0
1232 for vbox in self.servers_vbox.children():
1233 height += vbox.get_real_height()
1234
1235 # add size of toparea and 2 times the MARGIN (top and bottom)
1236 height += self.toparea.sizeHint().height() + 2
1237
1238 return height
1239
1240 def set_shown(self):
1241 """
1242 might help to avoid flickering on MacOSX, in cooperation with QTimer
1243 """
1244 statuswindow_properties.is_shown = True
1245
1246 @Slot()
1247 def save_position_to_conf(self):
1248 """
1249 store position of statuswindow/statusbar
1250 """
1251 # only useful if statusbar is floating
1252 if conf.statusbar_floating:
1253 # minimize window to statusbar only to get real position
1254 self.hide_window()
1255 conf.position_x = self.x()
1256 conf.position_y = self.y()
1257 if conf.windowed:
1258 conf.position_x = self.x()
1259 conf.position_y = self.y()
1260 conf.position_width = self.width()
1261 conf.position_height = self.height()
1262 # store position of statuswindow/statusbar
1263 conf.save_config()
1264
1265 @Slot(str, str)
1266 def show_message(self, msg_type, message):
1267 """
1268 show message from other thread like MediaPlayer
1269 """
1270 title = " ".join((AppInfo.NAME, msg_type))
1271 if msg_type == 'warning':
1272 return QMessageBox.warning(self, title, message)
1273
1274 elif msg_type == 'information':
1275 return QMessageBox.information(self, title, message)
1276 return None
1277
1278 @Slot()
1279 def recheck_all(self):
1280 """
1281 tell servers to recheck all hosts and services
1282 """
1283 self.recheck.emit()
1284
1285 @Slot()
1286 def refresh(self):
1287 """
1288 tell all enabled servers to refresh their information
1289 """
1290 # unfresh event history of servers
1291 self.clear_event_history.emit()
1292
1293 for server in get_enabled_servers():
1294 if conf.debug_mode:
1295 server.debug(server=server.name, debug='Refreshing all hosts and services')
1296
1297 # manipulate server thread counter so get_status loop will refresh when next looking
1298 # at thread counter
1299 server.thread_counter = conf.update_interval_seconds + 1
1300
1301 @Slot(dict)
1302 def desktop_notification(self, current_status_count):
1303 """
1304 show desktop notification - must be called from same thread as DBus intialization
1305 """
1306 # compile message from status counts
1307 message = ''
1308 for state in ['DOWN', 'UNREACHABLE', 'DISASTER', 'CRITICAL', 'HIGH', 'AVERAGE', 'WARNING', 'INFORMATION',
1309 'UNKNOWN']:
1310 if current_status_count[state] > 0:
1311 message += '{0} {1} '.format(str(current_status_count[state]), state)
1312
1313 if not message == '':
1314 # due to mysterious DBus-Crashes
1315 # see https://github.com/HenriWahl/Nagstamon/issues/320
1316 try:
1317 dbus_connection.show(AppInfo.NAME, message)
1318 except Exception:
1319 print_exc(file=stdout)
1320
1321 @Slot()
1322 def raise_window_on_all_desktops(self):
1323 """
1324 experimental workaround for floating-statusbar-only-on-one-virtual-desktop-after-a-while bug
1325 see https://github.com/HenriWahl/Nagstamon/issues/217
1326 """
1327 if conf.windowed:
1328 return
1329 # X11/Linux needs some special treatment to get the statusbar floating on all virtual desktops
1330 if OS not in OS_NON_LINUX and not DESKTOP_WAYLAND:
1331 # get all windows...
1332 winid = self.winId().__int__()
1333 self.ewmh.setWmDesktop(winid, 0xffffffff)
1334 self.ewmh.display.flush()
1335
1336 # apparently sometime the floating statusbar vanishes in the background
1337 # lets try here to keep it on top - only if not fullscreen
1338 if not conf.fullscreen and not conf.windowed and not OS == OS_WINDOWS:
1339 self.setWindowFlags(WINDOW_FLAGS)
1340
1341 # again and again try to keep that statuswindow on top!
1342 if OS == OS_WINDOWS and \
1343 not conf.fullscreen and \
1344 not conf.windowed and \
1345 app.activePopupWidget() is None:
1346 try:
1347 self.raise_()
1348 except Exception as error:
1349 # apparently a race condition could occur on set_mode() - grab it here and continue
1350 print(error)
1351
1352 @Slot()
1353 def finish_worker_thread(self):
1354 """
1355 attempt to shut down thread cleanly
1356 """
1357 # stop debugging
1358 statuswindow_properties.worker_debug_loop_looping = False
1359 # tell thread to quit
1360 self.worker_thread.quit()
1361 # wait until thread is really stopped
1362 self.worker_thread.wait()
1363
1364 @Slot()
1365 def finish_worker_notification_thread(self):
1366 """
1367 attempt to shut down thread cleanly
1368 """
1369 # tell thread to quit
1370 self.worker_notification_thread.quit()
1371 # wait until thread is really stopped
1372 self.worker_notification_thread.wait()
1373
1374 @Slot(str)
1375 def remove_previous_server_vbox(self, previous_server_name):
1376 # remove old server vbox from the status window if still running
1377 for vbox in self.servers_vbox.children():
1378 if vbox.server.name == previous_server_name:
1379 # disable server
1380 vbox.server.enabled = False
1381 # stop thread by falsificate running flag
1382 vbox.table.worker.running = False
1383 vbox.table.worker.finish.emit()
1384 # nothing more to do
1385 break
1386
1387 @Slot()
1388 def decrease_shown_timestamp(self):
1389 """
1390 small workaround for the timestamp trick to avoid flickering
1391 if the 'Settings' button was clicked too fast the timestamp difference
1392 is too short and the statuswindow will keep open
1393 modifying the timestamp could help
1394 """
1395 statuswindow_properties.is_shown_timestamp -= 1
1396
1397 @Slot()
1398 def exit(self):
1399 """
1400 stop all child threads before quitting instance
1401 """
1402 # store position of statuswindow/statusbar
1403 self.save_position_to_conf()
1404
1405 # save configuration
1406 conf.save_config()
1407
1408 # hide statuswindow first to avoid lag when waiting for finished threads
1409 self.hide()
1410
1411 # stop statuswindow workers
1412 self.worker.finish.emit()
1413 self.worker_notification.finish.emit()
1414
1415 # tell all treeview threads to stop
1416 for server_vbox in self.servers_vbox.children():
1417 server_vbox.table.worker.finish.emit()
1418
1419 app.exit()
1420
1421 class Worker(QObject):
1422 """
1423 run a thread, for example, for debugging
1424 """
1425 # send signal if ready to stop
1426 finish = Signal()
1427
1428 def __init__(self):
1429 QObject.__init__(self)
1430 # flag to decide if the thread has to run or to be stopped
1431 self.running = True
1432 # flag if debug_loop is looping
1433 self.debug_loop_looping = False
1434 # default debug dile does not exist
1435 self.debug_file = None
1436
1437 def open_debug_file(self):
1438 # open file and truncate
1439 self.debug_file = open(conf.debug_file, "w")
1440
1441 def close_debug_file(self):
1442 # close and reset file
1443 self.debug_file.close()
1444 self.debug_file = None
1445
1446 @Slot()
1447 def debug_loop(self):
1448 """
1449 if debugging is enabled, poll debug_queue list and print/write its contents
1450 """
1451 if conf.debug_mode:
1452 statuswindow_properties.worker_debug_loop_looping = True
1453
1454 # as long thread is supposed to run
1455 while self.running and statuswindow_properties.worker_debug_loop_looping:
1456 # only log something if there is something to tell
1457 while len(debug_queue) > 0:
1458 # always get the oldest item of queue list - FIFO
1459 debug_line = (debug_queue.pop(0))
1460 # output to console
1461 print(debug_line)
1462 if conf.debug_to_file:
1463 # if there is no file handle available get it
1464 if self.debug_file is None:
1465 self.open_debug_file()
1466 # log line per line
1467 self.debug_file.write(debug_line + "\n")
1468 # wait second until the next poll
1469 sleep(1)
1470
1471 # unset looping
1472 statuswindow_properties.worker_debug_loop_looping = False
1473 # close file if any
1474 if self.debug_file is not None:
1475 self.close_debug_file()
1476 else:
1477 # set the flag to tell debug loop it should stop, please
1478 self.debug_loop_looping = False
1479
1480 class WorkerNotification(QObject):
1481 """
1482 run a thread for doing all notification stuff
1483 """
1484 # tell statusbar labels to flash
1485 start_flash = Signal()
1486 stop_flash = Signal()
1487
1488 # tell mediaplayer to load and play sound file
1489 load_sound = Signal(str)
1490 play_sound = Signal()
1491
1492 # tell statuswindow to use desktop notification
1493 desktop_notification = Signal(dict)
1494
1495 # only one enabled server should have the right to send play_sound signal
1496 notifying_server = ''
1497
1498 # desktop notification needs to store count of states
1499 status_count = dict()
1500
1501 # send signal if ready to stop
1502 finish = Signal()
1503
1504 def __init__(self, statuswindow_properties=None):
1505 QObject.__init__(self)
1506 self.statuswindow_properties = statuswindow_properties
1507
1508 @Slot(str, str, str)
1509 def start(self, server_name, worst_status_diff, worst_status_current):
1510 """
1511 start notification
1512 """
1513 if conf.notification:
1514 # only if not notifying yet or the current state is worse than the prior AND
1515 # only when the current state is configured to be honking about
1516 if (STATES.index(worst_status_diff) > STATES.index(
1517 self.statuswindow_properties.worst_notification_status) or
1518 self.statuswindow_properties.is_notifying is False) and \
1519 conf.__dict__[f'notify_if_{worst_status_diff.lower()}'] is True:
1520 # keep last worst state worth a notification for comparison 3 lines above
1521 self.statuswindow_properties.worst_notification_status = worst_status_diff
1522 # set flag to avoid innecessary notification
1523 self.statuswindow_properties.is_notifying = True
1524 if self.statuswindow_properties.notifying_server == '':
1525 statuswindow_properties.notifying_server = server_name
1526
1527 # flashing statusbar
1528 if conf.notification_flashing:
1529 self.start_flash.emit()
1530
1531 # Play default sounds via mediaplayer
1532 if conf.notification_sound:
1533 sound_file = ''
1534 # at the moment there are only sounds for down, critical and warning
1535 # only honk if notifications are wanted for this state
1536 if worst_status_diff in STATES_SOUND:
1537 if conf.notification_default_sound:
1538 # default .wav sound files are in resources folder
1539 sound_file = '{0}{1}{2}.wav'.format(RESOURCES, sep, worst_status_diff.lower())
1540 elif conf.notification_custom_sound:
1541 sound_file = conf.__dict__[
1542 'notification_custom_sound_{0}'.format(worst_status_diff.lower())]
1543
1544 # only one enabled server should access the mediaplayer
1545 if statuswindow_properties.notifying_server == server_name:
1546 # once loaded file will be played by every server, even if it is
1547 # not the statuswindow_properties.notifying_server that loaded it
1548 self.load_sound.emit(sound_file)
1549 self.play_sound.emit()
1550
1551 # Notification actions
1552 if conf.notification_actions:
1553 if conf.notification_action_warning is True and worst_status_diff == 'WARNING':
1554 self.execute_action(server_name, conf.notification_action_warning_string)
1555 if conf.notification_action_critical is True and worst_status_diff == 'CRITICAL':
1556 self.execute_action(server_name, conf.notification_action_critical_string)
1557 if conf.notification_action_down is True and worst_status_diff == 'DOWN':
1558 self.execute_action(server_name, conf.notification_action_down_string)
1559
1560 # Notification action OK
1561 if worst_status_current == 'UP' and \
1562 conf.notification_actions and conf.notification_action_ok:
1563 self.execute_action(server_name, conf.notification_action_ok_string)
1564
1565 # Custom event notification - valid vor ALL events, thus without status comparison
1566 if conf.notification_actions is True and conf.notification_custom_action is True:
1567 # temporarily used to collect executed events
1568 events_list = []
1569 events_string = ''
1570
1571 # if no single notifications should be used (default) put all events into one string, separated by separator
1572 if conf.notification_custom_action_single is False:
1573 for server in get_enabled_servers():
1574 # list comprehension only considers events which are new, ergo True
1575 events_list += [k for k, v in
1576 server.events_notification.items() if v is True]
1577
1578 # create string for no-single-event-notification of events separated by separator
1579 events_string = conf.notification_custom_action_separator.join(events_list)
1580
1581 # clear already notified events setting them to False
1582 for server in get_enabled_servers():
1583 for event in [k for k, v in
1584 server.events_notification.items() if v is True]:
1585 server.events_notification[event] = False
1586 else:
1587 for server in get_enabled_servers():
1588 for event in [k for k, v in server.events_notification.items() if v is True]:
1589 custom_action_string = conf.notification_custom_action_string.replace('$EVENT$',
1590 '$EVENTS$')
1591 custom_action_string = custom_action_string.replace('$EVENTS$', event)
1592 # execute action
1593 self.execute_action(server_name, custom_action_string)
1594 # clear already notified events setting them to False
1595 server.events_notification[event] = False
1596
1597 # if events got filled display them now
1598 if events_string != '':
1599 # in case a single action per event has to be executed
1600 custom_action_string = conf.notification_custom_action_string.replace('$EVENT$', '$EVENTS$')
1601 # insert real event(s)
1602 custom_action_string = custom_action_string.replace('$EVENTS$', events_string)
1603 # execute action
1604 self.execute_action(server_name, custom_action_string)
1605 else:
1606 # set all events to False to ignore them in the future
1607 for event in servers[server_name].events_notification:
1608 servers[server_name].events_notification[event] = False
1609
1610 # repeated sound
1611 # only let one enabled server play sound to avoid a larger cacophony
1612 if statuswindow_properties.is_notifying and \
1613 conf.notification_sound_repeat and \
1614 statuswindow_properties == server_name:
1615 self.play_sound.emit()
1616
1617 # desktop notification
1618 if conf.notification_desktop:
1619 # get status count from servers
1620 current_status_count = get_status_count()
1621 if current_status_count != self.status_count:
1622 self.desktop_notification.emit(current_status_count)
1623 # store status count for next comparison
1624 self.status_count = current_status_count
1625 del current_status_count
1626
1627 @Slot()
1628 def stop(self):
1629 """
1630 stop notification if there is no need anymore
1631 """
1632 if self.statuswindow_properties.is_notifying:
1633 self.statuswindow_properties.worst_notification_status = 'UP'
1634 self.statuswindow_properties.is_notifying = False
1635
1636 # no more flashing statusbar and systray
1637 self.stop_flash.emit()
1638
1639 # reset notifying server, waiting for next notification
1640 statuswindow_properties.notifying_server = ''
1641
1642 def execute_action(self, server_name, custom_action_string):
1643 """
1644 execute custom action
1645 """
1646 if conf.debug_mode:
1647 servers[server_name].debug(debug='NOTIFICATION: ' + custom_action_string)
1648 Popen(custom_action_string, shell=True)