Debian Codegraph @

Nagstamon/qui/dialogs/settings.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 copy import copy
19 from os import environ
20 from urllib.parse import quote
21
22 from Nagstamon.config import (AppInfo,
23 BOOLPOOL,
24 conf,
25 CONFIG_STRINGS,
26 KEYRING,
27 OS,
28 OS_NON_LINUX,
29 OS_MACOS, OS_WINDOWS)
30 from Nagstamon.qui.constants import (COLORS,
31 HEADERS_HEADERS,
32 HEADERS_KEYS_HEADERS, HEADERS_HEADERS_KEYS)
33 from Nagstamon.qui.globals import (dbus_connection,
34 font,
35 font_icons,
36 font_default)
37 from Nagstamon.qui.qt import (Signal,
38 Slot,
39 QColor,
40 QColorDialog,
41 QFileDialog,
42 QFont,
43 QFontDialog,
44 QMessageBox,
45 QPalette,
46 QSignalMapper,
47 QStyle,
48 Qt,
49 QWidget)
50 from Nagstamon.qui.widgets.app import app
51 from Nagstamon.qui.widgets.mediaplayer import mediaplayer
52 from Nagstamon.qui.dialogs.check_version import check_version
53 from Nagstamon.qui.dialogs.dialog import Dialog
54 from Nagstamon.servers import servers
55
56
57 class DialogSettings(Dialog):
58 """
59 class for settings dialog
60 """
61
62 # signal to be fired if OK button was clicked, and new settings are applied
63 changed = Signal()
64
65 # send signal if check for a new version is wanted
66 check_for_new_version = Signal(bool, QWidget)
67
68 start_debug_loop = Signal()
69
70 # signal to be fired if a server is newly created
71 server_created = Signal()
72
73 # signal to be fired if a server is edited
74 server_edited = Signal(str)
75
76 # signal to be fired if a server is copied
77 server_copied = Signal(str)
78
79 # signal to be fired if a server is deleted
80 server_deleted = Signal(str)
81
82 # signal to be fired if an action is newly created
83 action_created = Signal()
84
85 # signal to be fired if an action is edited
86 action_edited = Signal(str)
87
88 # signal to be fired if an action is copied
89 action_copied = Signal(str)
90
91 # signal to be fired when the settings dialog OK button is pressed
92 settings_ok = Signal()
93
94 # signal to be fired when the settings dialog is cancelled
95 cancelled = Signal()
96
97 # to be fired when the servers and actions lists have to be changed
98 update_list = Signal(str, str, str)
99
100 # sent when display mode has changed
101 changed_display_mode = Signal()
102
103 def __init__(self):
104 Dialog.__init__(self, 'settings_main')
105 # file chooser Dialog
106 self.file_chooser = QFileDialog()
107 # define checkbox-to-widgets dependencies which apply at initialization
108 # which widgets have to be hidden because of irrelevance
109 # dictionary holds checkbox/radiobutton as key and relevant widgets in a list
110 self.TOGGLE_DEPS = {
111 # debug mode
112 self.window.input_checkbox_debug_mode: [self.window.input_checkbox_debug_to_file,
113 self.window.input_lineedit_debug_file],
114 # regular expressions for filtering hosts
115 self.window.input_checkbox_re_host_enabled: [self.window.input_lineedit_re_host_pattern,
116 self.window.input_checkbox_re_host_reverse],
117 # regular expressions for filtering services
118 self.window.input_checkbox_re_service_enabled: [self.window.input_lineedit_re_service_pattern,
119 self.window.input_checkbox_re_service_reverse],
120 # regular expressions for filtering status information
121 self.window.input_checkbox_re_status_information_enabled: [
122 self.window.input_lineedit_re_status_information_pattern,
123 self.window.input_checkbox_re_status_information_reverse],
124 # regular expressions for filtering duration
125 self.window.input_checkbox_re_duration_enabled: [self.window.input_lineedit_re_duration_pattern,
126 self.window.input_checkbox_re_duration_reverse],
127 # regular expressions for filtering duration
128 self.window.input_checkbox_re_attempt_enabled: [self.window.input_lineedit_re_attempt_pattern,
129 self.window.input_checkbox_re_attempt_reverse],
130 # regular expressions for filtering groups
131 self.window.input_checkbox_re_groups_enabled: [self.window.input_lineedit_re_groups_pattern,
132 self.window.input_checkbox_re_groups_reverse],
133 # offset for statuswindow when using systray
134 self.window.input_radiobutton_icon_in_systray: [self.window.input_checkbox_systray_offset_use],
135 self.window.input_checkbox_systray_offset_use: [self.window.input_spinbox_systray_offset,
136 self.window.label_offset_statuswindow],
137 # display to use in fullscreen mode
138 self.window.input_radiobutton_fullscreen: [self.window.label_fullscreen_display,
139 self.window.input_combobox_fullscreen_display],
140 # notifications in general
141 self.window.input_checkbox_notification: [self.window.notification_groupbox],
142 # sound notifications
143 self.window.input_checkbox_notification_sound: [self.window.notification_sounds_groupbox],
144 # custom sounds
145 self.window.input_radiobutton_notification_custom_sound: [self.window.notification_custom_sounds_groupbox],
146 # notification actions
147 self.window.input_checkbox_notification_actions: [self.window.notification_actions_groupbox],
148 # several notification actions depending on status
149 self.window.input_checkbox_notification_action_warning: [
150 self.window.input_lineedit_notification_action_warning_string],
151 self.window.input_checkbox_notification_action_critical: [
152 self.window.input_lineedit_notification_action_critical_string],
153 self.window.input_checkbox_notification_action_down: [
154 self.window.input_lineedit_notification_action_down_string],
155 self.window.input_checkbox_notification_action_ok: [
156 self.window.input_lineedit_notification_action_ok_string],
157 # single custom notification action
158 self.window.input_checkbox_notification_custom_action: [self.window.notification_custom_action_groupbox],
159 # use event separator or not
160 self.window.input_checkbox_notification_custom_action_single: [
161 self.window.label_notification_custom_action_separator,
162 self.window.input_lineedit_notification_custom_action_separator],
163 # customized color alternation
164 self.window.input_checkbox_show_grid: [self.window.input_checkbox_grid_use_custom_intensity],
165 self.window.input_checkbox_grid_use_custom_intensity: [self.window.input_slider_grid_alternation_intensity,
166 self.window.label_intensity_information_0,
167 self.window.label_intensity_information_1,
168 self.window.label_intensity_warning_0,
169 self.window.label_intensity_warning_1,
170 self.window.label_intensity_average_0,
171 self.window.label_intensity_average_1,
172 self.window.label_intensity_high_0,
173 self.window.label_intensity_high_1,
174 self.window.label_intensity_critical_0,
175 self.window.label_intensity_critical_1,
176 self.window.label_intensity_disaster_0,
177 self.window.label_intensity_disaster_1,
178 self.window.label_intensity_down_0,
179 self.window.label_intensity_down_1,
180 self.window.label_intensity_unreachable_0,
181 self.window.label_intensity_unreachable_1,
182 self.window.label_intensity_unknown_0,
183 self.window.label_intensity_unknown_1],
184 self.window.input_radiobutton_use_custom_browser: [self.window.groupbox_custom_browser,
185 self.window.input_lineedit_custom_browser,
186 self.window.button_choose_browser]}
187
188 self.TOGGLE_DEPS_INVERTED = [self.window.input_checkbox_notification_custom_action_single]
189
190 # because this makes only sense in macOS these dependencies will be added here
191 if OS == OS_MACOS:
192 # offer an option to hide icon in dock on macOS
193 self.TOGGLE_DEPS.update({
194 self.window.input_radiobutton_icon_in_systray: [self.window.input_checkbox_hide_macos_dock_icon]})
195
196 # show an option to enable position fix only on Unices
197 if not OS in OS_NON_LINUX:
198 self.window.input_checkbox_enable_position_fix.show()
199 else:
200 self.window.input_checkbox_enable_position_fix.hide()
201
202 # set title to the current version
203 self.window.setWindowTitle(' '.join((AppInfo.NAME, AppInfo.VERSION)))
204
205 # connect server buttons to server dialog
206 self.window.button_new_server.clicked.connect(self.new_server)
207 self.window.button_edit_server.clicked.connect(self.edit_server)
208 self.window.button_copy_server.clicked.connect(self.copy_server)
209 self.window.button_delete_server.clicked.connect(self.delete_server)
210
211 # double-click on server to edit
212 self.window.list_servers.doubleClicked.connect(self.edit_server)
213
214 # connect check-for-updates button to update check
215 # self.window.button_check_for_new_version_now.clicked.connect(check_version.check)
216 self.window.button_check_for_new_version_now.clicked.connect(self.button_check_for_new_version_clicked)
217 self.check_for_new_version.connect(check_version.check)
218
219 # avoid offset spinbox if offset is not enabled
220 self.window.input_radiobutton_windowed.clicked.connect(self.toggle_systray_icon_offset)
221 self.window.input_radiobutton_fullscreen.clicked.connect(self.toggle_systray_icon_offset)
222 self.window.input_radiobutton_icon_in_systray.clicked.connect(self.toggle_systray_icon_offset)
223 self.window.input_radiobutton_statusbar_floating.clicked.connect(self.toggle_systray_icon_offset)
224
225 # connect font chooser button to font choosing dialog
226 self.window.button_fontchooser.clicked.connect(self.font_chooser)
227 # connect revert-to-default-font button
228 self.window.button_default_font.clicked.connect(self.font_default)
229 # store font as default
230 self.font = font
231 # show current font in label_font
232 self.window.label_font.setFont(font)
233
234 # connect action buttons to action dialog
235 self.window.button_new_action.clicked.connect(self.new_action)
236 self.window.button_edit_action.clicked.connect(self.edit_action)
237 self.window.button_copy_action.clicked.connect(self.copy_action)
238 self.window.button_delete_action.clicked.connect(self.delete_action)
239
240 # double-click on action to edit
241 self.window.list_actions.doubleClicked.connect(self.edit_action)
242
243 # connect custom sound file buttons
244 self.window.button_choose_warning.clicked.connect(self.choose_sound_file_warning)
245 self.window.button_choose_critical.clicked.connect(self.choose_sound_file_critical)
246 self.window.button_choose_down.clicked.connect(self.choose_sound_file_down)
247
248 # connect custom sound file buttons
249 self.window.button_play_warning.clicked.connect(self.play_sound_file_warning)
250 self.window.button_play_critical.clicked.connect(self.play_sound_file_critical)
251 self.window.button_play_down.clicked.connect(self.play_sound_file_down)
252
253 # only show desktop notification on systems that support it
254 if not dbus_connection.connected:
255 self.window.input_checkbox_notification_desktop.hide()
256
257 # set folder and play symbols to choose and play buttons
258 self.window.button_choose_warning.setText('')
259 self.window.button_choose_warning.setIcon(
260 self.window.button_play_warning.style().standardIcon(QStyle.StandardPixmap.SP_DirIcon))
261 self.window.button_play_warning.setText('')
262 self.window.button_play_warning.setIcon(
263 self.window.button_play_warning.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
264
265 self.window.button_choose_critical.setText('')
266 self.window.button_choose_critical.setIcon(
267 self.window.button_play_warning.style().standardIcon(QStyle.StandardPixmap.SP_DirIcon))
268 self.window.button_play_critical.setText('')
269 self.window.button_play_critical.setIcon(
270 self.window.button_play_warning.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
271
272 self.window.button_choose_down.setText('')
273 self.window.button_choose_down.setIcon(
274 self.window.button_play_warning.style().standardIcon(QStyle.StandardPixmap.SP_DirIcon))
275 self.window.button_play_down.setText('')
276 self.window.button_play_down.setIcon(
277 self.window.button_play_warning.style().standardIcon(QStyle.StandardPixmap.SP_MediaPlay))
278
279 # set browser file chooser icon and current custom browser path
280 self.window.button_choose_browser.setText('')
281 self.window.button_choose_browser.setIcon(
282 self.window.button_play_warning.style().standardIcon(QStyle.StandardPixmap.SP_DirIcon))
283 self.window.input_lineedit_custom_browser.setText(conf.custom_browser)
284 # connect choose browser button with file dialog
285 self.window.button_choose_browser.clicked.connect(self.choose_browser_executable)
286
287 # QSignalMapper needed to connect all color buttons to color dialogs
288 self.signalmapper_colors = QSignalMapper()
289
290 # connect color buttons with color dialog
291 for widget in [x for x in self.window.__dict__ if x.startswith('input_button_color_')]:
292 button = self.window.__dict__[widget]
293 item = widget.split('input_button_color_')[1]
294 # multiplex slot for open color dialog by signal-mapping
295 self.signalmapper_colors.setMapping(button, item)
296 button.clicked.connect(self.signalmapper_colors.map)
297
298 # connect reset and defaults buttons
299 self.window.button_colors_reset.clicked.connect(self.paint_colors)
300 self.window.button_colors_reset.clicked.connect(self.paint_color_alternation)
301 self.window.button_colors_reset.clicked.connect(self.change_color_alternation_by_value)
302 self.window.button_colors_defaults.clicked.connect(self.colors_defaults)
303 self.window.button_colors_defaults.clicked.connect(self.paint_color_alternation)
304 self.window.button_colors_defaults.clicked.connect(self.change_color_alternation_by_value)
305
306 # paint alternating colors when example is wanted for customized intensity
307 self.window.input_checkbox_grid_use_custom_intensity.clicked.connect(self.paint_color_alternation)
308 self.window.input_checkbox_grid_use_custom_intensity.clicked.connect(self.change_color_alternation_by_value)
309 self.window.input_checkbox_grid_use_custom_intensity.clicked.connect(self.toggle_zabbix_widgets)
310
311 # finally, map signals with .sender() - [<type>] is important!
312 self.signalmapper_colors.mappedString[str].connect(self.color_chooser)
313
314 # connect slider to alternating colors
315 self.window.input_slider_grid_alternation_intensity.valueChanged.connect(self.change_color_alternation)
316
317 # apply toggle-dependencies between checkboxes and certain widgets
318 self.toggle_toggles()
319
320 # workaround to avoid a gigantic settings dialog
321 # list of Zabbix-related widgets, only to be shown if there is a Zabbix monitor server configured
322 self.ZABBIX_WIDGETS = [self.window.input_checkbox_filter_all_average_services,
323 self.window.input_checkbox_filter_all_disaster_services,
324 self.window.input_checkbox_filter_all_high_services,
325 self.window.input_checkbox_filter_all_information_services,
326 self.window.input_checkbox_notify_if_average,
327 self.window.input_checkbox_notify_if_disaster,
328 self.window.input_checkbox_notify_if_high,
329 self.window.input_checkbox_notify_if_information,
330 self.window.input_button_color_average_text,
331 self.window.input_button_color_average_background,
332 self.window.input_button_color_disaster_text,
333 self.window.input_button_color_disaster_background,
334 self.window.input_button_color_high_text,
335 self.window.input_button_color_high_background,
336 self.window.input_button_color_information_text,
337 self.window.input_button_color_information_background,
338 self.window.label_color_average,
339 self.window.label_color_disaster,
340 self.window.label_color_high,
341 self.window.label_color_information]
342
343 # Labes for customized color intensity
344 self.ZABBIX_COLOR_INTENSITY_LABELS = [self.window.label_intensity_average_0,
345 self.window.label_intensity_average_1,
346 self.window.label_intensity_disaster_0,
347 self.window.label_intensity_disaster_1,
348 self.window.label_intensity_high_0,
349 self.window.label_intensity_high_1,
350 self.window.label_intensity_information_0,
351 self.window.label_intensity_information_1]
352
353 # the next workaround...
354 self.OP5MONITOR_WIDGETS = [self.window.input_checkbox_re_groups_enabled,
355 self.window.input_lineedit_re_groups_pattern,
356 self.window.input_checkbox_re_groups_reverse]
357
358 # ...and another...
359 self.EXPIRE_TIME_WIDGETS = [self.window.input_checkbox_defaults_acknowledge_expire,
360 self.window.label_expire_in,
361 self.window.label_expire_in_hours,
362 self.window.label_expire_in_minutes,
363 self.window.input_spinbox_defaults_acknowledge_expire_duration_hours,
364 self.window.input_spinbox_defaults_acknowledge_expire_duration_minutes]
365
366 def initialize(self):
367 # apply configuration values
368 # start with server tab
369 self.window.tabs.setCurrentIndex(0)
370 for widget in dir(self.window):
371 if widget.startswith('input_'):
372 if widget.startswith('input_checkbox_'):
373 if conf.__dict__[widget.split('input_checkbox_')[1]] is True:
374 self.window.__dict__[widget].toggle()
375 elif widget.startswith('input_radiobutton_'):
376 if conf.__dict__[widget.split('input_radiobutton_')[1]] is True:
377 self.window.__dict__[widget].toggle()
378 elif widget.startswith('input_lineedit_'):
379 # older versions of Nagstamon have a bool value for custom_action_separator
380 # which leads to a crash here - thus str() to solve this
381 self.window.__dict__[widget].setText(str(conf.__dict__[widget.split('input_lineedit_')[1]]))
382 elif widget.startswith('input_spinbox_'):
383 self.window.__dict__[widget].setValue(int(conf.__dict__[widget.split('input_spinbox_')[1]]))
384 elif widget.startswith('input_slider_'):
385 self.window.__dict__[widget].setValue(int(conf.__dict__[widget.split('input_slider_')[1]]))
386 # bruteforce size smallification, lazy try/except variant
387 try:
388 self.window.__dict__[widget].adjustSize()
389 except:
390 pass
391 # fill default order fields combobox with s names
392 # kick out empty headers for hosts and services flags
393 sort_fields = copy(HEADERS_HEADERS)
394 while '' in sort_fields:
395 sort_fields.remove('')
396
397 self.window.input_combobox_default_sort_field.addItems(sort_fields)
398 # catch exception which will occur when older settings are used which have real header names as values
399 try:
400 self.window.input_combobox_default_sort_field.setCurrentText(HEADERS_KEYS_HEADERS[conf.default_sort_field])
401 except:
402 self.window.input_combobox_default_sort_field.setCurrentText(conf.default_sort_field)
403
404 # fill default sort order combobox
405 self.window.input_combobox_default_sort_order.addItems(['Ascending', 'Descending'])
406 # .title() to get upper first letter
407 self.window.input_combobox_default_sort_order.setCurrentText(conf.default_sort_order.title())
408
409 # fill combobox with screens for fullscreen
410 for screen in app.screens():
411 self.window.input_combobox_fullscreen_display.addItem(str(screen.name()))
412 self.window.input_combobox_fullscreen_display.setCurrentText(str(conf.fullscreen_display))
413
414 # fill servers list widget with servers
415 self.fill_list(self.window.list_servers, conf.servers)
416
417 # select first item
418 self.window.list_servers.setCurrentRow(0)
419 # set focus to distinguish active and inactive servers
420 self.window.list_servers.setFocus()
421
422 # fill actions list widget with actions
423 self.fill_list(self.window.list_actions, conf.actions)
424
425 # select first item
426 self.window.list_actions.setCurrentRow(0)
427
428 # paint colors onto color selection buttons and alternation example
429 self.paint_colors()
430 self.paint_color_alternation()
431 self.change_color_alternation(conf.grid_alternation_intensity)
432
433 # hide keyring setting if keyring is not available
434 if KEYRING:
435 self.window.input_checkbox_use_system_keyring.show()
436 else:
437 self.window.input_checkbox_use_system_keyring.hide()
438
439 # hide 'Hide macOS Dock icon' if not on macOS
440 if OS != OS_MACOS:
441 self.window.input_checkbox_hide_macos_dock_icon.hide()
442
443 # avoid showing offset setting if not icon in systray is configured
444 if not OS in OS_NON_LINUX and not conf.icon_in_systray:
445 self.toggle_systray_icon_offset()
446
447 # important final size adjustment
448 self.window.adjustSize()
449
450 def show(self, tab=0):
451 # hide them and thus be able to fix size if no extra Zabbix/Op5Monitor/IcingaWeb2 widgets are shown
452 self.toggle_zabbix_widgets()
453 self.toggle_op5monitor_widgets()
454 self.toggle_expire_time_widgets()
455
456 # tell the world that dialog pops up
457 self.show_dialog.emit()
458
459 # jump to requested tab in settings dialog
460 self.window.tabs.setCurrentIndex(tab)
461
462 super().show()
463
464 @Slot()
465 def show_new_server(self):
466 """
467 opens settings and new server dialogs - used by dialogs.server_missing
468 """
469 # emulate button click
470 self.window.button_new_server.clicked.emit()
471
472 @Slot()
473 def show_filters(self):
474 """
475 opens filters settings after clicking button_filters in the top area
476 """
477 self.show(tab=2)
478
479 @Slot()
480 def show_defaults(self):
481 """
482 opens default settings after clicking button in acknowledge/downtime dialog
483 """
484 self.show(tab=6)
485
486 def ok(self):
487 """
488 what to do if OK was pressed
489 """
490 # store position of statuswindow/statusbar only if statusbar is floating
491 if conf.statusbar_floating:
492 self.settings_ok.emit()
493
494 # store hash of all display settings as display_mode to decide if statuswindow has to be recreated
495 display_mode = str(conf.statusbar_floating) + \
496 str(conf.icon_in_systray) + \
497 str(conf.fullscreen) + \
498 str(conf.fullscreen_display) + \
499 str(conf.windowed)
500
501 # do all stuff necessary after the OK button was clicked
502 # and put widget values into conf
503 for widget in self.window.__dict__.values():
504 if widget.objectName().startswith('input_checkbox_'):
505 conf.__dict__[widget.objectName().split('input_checkbox_')[1]] = widget.isChecked()
506 elif widget.objectName().startswith('input_radiobutton_'):
507 conf.__dict__[widget.objectName().split('input_radiobutton_')[1]] = widget.isChecked()
508 elif widget.objectName().startswith("input_lineedit_"):
509 conf.__dict__[widget.objectName().split('input_lineedit_')[1]] = widget.text()
510 elif widget.objectName().startswith('input_spinbox_'):
511 conf.__dict__[widget.objectName().split('input_spinbox_')[1]] = str(widget.value())
512 elif widget.objectName().startswith('input_slider_'):
513 conf.__dict__[widget.objectName().split('input_slider_')[1]] = str(widget.value())
514 elif widget.objectName().startswith('input_combobox_'):
515 conf.__dict__[widget.objectName().split('input_combobox_')[1]] = widget.currentText()
516 elif widget.objectName().startswith('input_button_color_'):
517 # get color value from color button stylesheet
518 color = self.window.__dict__[widget.objectName()].styleSheet()
519 color = color.split(':')[1].strip().split(';')[0]
520 conf.__dict__[widget.objectName().split('input_button_')[1]] = color
521
522 # convert some strings to integers and bools
523 for item in conf.__dict__:
524 if type(conf.__dict__[item]) == str:
525 # when an item is not one of those which always have to be strings, then it might be OK to convert it
526 if not item in CONFIG_STRINGS:
527 if conf.__dict__[item] in BOOLPOOL:
528 conf.__dict__[item] = BOOLPOOL[conf.__dict__[item]]
529 elif conf.__dict__[item].isdecimal():
530 conf.__dict__[item] = int(conf.__dict__[item])
531
532 # convert sorting fields to simple keys - maybe one day translated
533 conf.default_sort_field = HEADERS_HEADERS_KEYS[conf.default_sort_field]
534
535 # apply font
536 conf.font = self.font.toString()
537 # update global font and icon font
538 font.fromString(conf.font)
539 font_icons.setPointSize(font.pointSize() + 2)
540
541 # save configuration
542 conf.save_config()
543
544 # when display mode was changed, it's the easiest to destroy the old status window and create a new one
545 # store display_mode to decide if statuswindow has to be recreated
546 if display_mode != str(conf.statusbar_floating) + \
547 str(conf.icon_in_systray) + \
548 str(conf.fullscreen) + \
549 str(conf.fullscreen_display) + \
550 str(conf.windowed):
551 self.changed_display_mode.emit()
552 # tell statuswindow to reinitialize due to new settings
553 self.changed.emit()
554
555 # call close and macOS dock icon treatment from ancestor
556 super().ok()
557
558 @Slot()
559 def cancel(self):
560 """
561 check if there are any usable servers configured
562 """
563 # call close and macOS dock icon treatment from ancestor
564 self.cancelled.emit()
565 super().cancel()
566
567 @Slot()
568 def new_server(self):
569 """
570 create new server
571 """
572 self.server_created.emit()
573
574 @Slot()
575 def edit_server(self):
576 """
577 edit existing server
578 """
579 # issue #1114 - do not allow editing of servers when no server is selected nor doesn't exist
580 if self.window.list_servers.currentItem():
581 self.server_edited.emit(self.window.list_servers.currentItem().text())
582
583 @Slot()
584 def copy_server(self):
585 """
586 copy existing server
587 """
588 # issue #1114 - do not allow copying of servers when no server is selected nor doesn't exist
589 if self.window.list_servers.currentItem():
590 self.server_copied.emit(self.window.list_servers.currentItem().text())
591
592 @Slot()
593 def delete_server(self):
594 """
595 delete server, stop its thread, remove from config and list
596 """
597 # issue #1114 - do not allow editing of servers when no server is selected nor doesn't exist
598 if self.window.list_servers.currentItem():
599 # server to delete from current row in servers list
600 server = conf.servers[self.window.list_servers.currentItem().text()]
601
602 reply = QMessageBox.question(self.window, 'Nagstamon',
603 f'Do you really want to delete monitor server <b>{server.name}</b>?',
604 QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
605 QMessageBox.StandardButton.No)
606
607 if reply == QMessageBox.StandardButton.Yes:
608 # in case server is enabled to delete its vbox
609 if server.enabled:
610 self.server_deleted.emit(server.name)
611
612 # kick server out of server instances
613 servers.pop(server.name)
614 # dito from config items
615 conf.servers.pop(server.name)
616
617 # refresh list
618 # row index 0 to x
619 row = self.window.list_servers.currentRow()
620 # count real number, 1 to x
621 count = self.window.list_servers.count()
622
623 # if deleted row was the last line, the new current row has to be the new last line, accidentally the same as count
624 if row == count - 1:
625 # use the penultimate item as the new current one
626 row = count - 2
627 else:
628 # go down one row
629 row = row + 1
630 # refresh list and mark new current row
631 self.update_list.emit('list_servers', 'servers', self.window.list_servers.item(row).text())
632 del row, count
633
634 # delete server config file from disk
635 conf.delete_file('servers', 'server_{0}.conf'.format(quote(server.name, safe='')))
636 del server
637
638 @Slot(str, str, str)
639 def refresh_list(self, list_widget_str, list_conf_str, current=''):
640 """
641 refresh given 'list_widget' from given 'list_conf' and mark 'current' as current
642 """
643
644 # convert strings from signal to widgets and config items
645 list_widget = self.window.__dict__[list_widget_str]
646 list_conf = conf.__dict__[list_conf_str]
647
648 # clear list of servers
649 list_widget.clear()
650 # fill servers listwidget with servers
651 self.fill_list(list_widget, list_conf)
652 # select current edited item
653 # activate currently created/edited server monitor item by first searching it in the list
654 list_widget.setCurrentItem(list_widget.findItems(current, Qt.MatchFlag.MatchExactly)[0])
655
656 @Slot()
657 def new_action(self):
658 """
659 create new action
660 """
661 self.action_created.emit()
662
663 @Slot()
664 def edit_action(self):
665 """
666 edit existing action
667 """
668 if self.window.list_actions.currentItem():
669 self.action_edited.emit(self.window.list_actions.currentItem().text())
670
671 @Slot()
672 def copy_action(self):
673 """
674 copy existing action and edit it
675 """
676 if self.window.list_actions.currentItem():
677 self.action_copied.emit(self.window.list_actions.currentItem().text())
678
679 @Slot()
680 def delete_action(self):
681 """
682 delete action remove from config and list
683 """
684 # action to delete from current row in actions list
685 action = conf.actions[self.window.list_actions.currentItem().text()]
686
687 reply = QMessageBox.question(self.window, 'Nagstamon',
688 f'Do you really want to delete action <b>{action.name}</b>?',
689 QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
690 QMessageBox.StandardButton.No)
691
692 if reply == QMessageBox.StandardButton.Yes:
693 # kick action out of config items
694 conf.actions.pop(action.name)
695
696 # refresh list
697 # row index 0 to x
698 row = self.window.list_actions.currentRow()
699 # count real number, 1 to x
700 count = self.window.list_actions.count()
701
702 # if deleted row was the last line, the new current row has to be the new last line, accidentally the same as count
703 if row == count - 1:
704 # use the penultimate item as the new current one
705 row = count - 2
706 else:
707 # go down one row
708 row = row + 1
709 # refresh list and mark new current row
710 self.update_list.emit('list_actions', 'actions', self.window.list_actions.item(row).text())
711 del row, count
712
713 # delete the action config file from disk
714 conf.delete_file('actions', 'action_{0}.conf'.format(quote(action.name, safe='')))
715 del action
716
717 def choose_sound_file_decoration(method):
718 """
719 try to decorate sound file dialog
720 """
721
722 def decoration_function(self):
723 # execute decorated function
724 method(self)
725 # shortcut for widget to fill and revaluate
726 widget = self.window.__dict__['input_lineedit_notification_custom_sound_%s' % self.sound_file_type]
727
728 # use 2 filters, sound files and all files
729 file = self.file_chooser.getOpenFileName(self.window,
730 filter='Sound files (*.mp3 *.MP3 *.mp4 *.MP4 '
731 '*.wav *.WAV *.ogg *.OGG);;'
732 'All files (*)')[0]
733
734 # only take filename if QFileDialog gave something useful back
735 if file != '':
736 widget.setText(file)
737
738 return decoration_function
739
740 @choose_sound_file_decoration
741 @Slot()
742 def choose_sound_file_warning(self):
743 self.sound_file_type = 'warning'
744
745 @choose_sound_file_decoration
746 @Slot()
747 def choose_sound_file_critical(self):
748 self.sound_file_type = 'critical'
749
750 @choose_sound_file_decoration
751 @Slot()
752 def choose_sound_file_down(self):
753 self.sound_file_type = 'down'
754
755 def play_sound_file_decoration(method):
756 """
757 try to decorate sound file dialog
758 """
759
760 def decoration_function(self):
761 # execute decorated function
762 method(self)
763 # shortcut for widget to fill and revaluate
764 widget = self.window.__dict__['input_lineedit_notification_custom_sound_%s' % self.sound_file_type]
765
766 # get the file path from widget
767 file = widget.text()
768
769 # tell mediaplayer to play a file only if it exists
770 if mediaplayer.set_media(file) is True:
771 mediaplayer.play()
772
773 return decoration_function
774
775 @play_sound_file_decoration
776 @Slot()
777 def play_sound_file_warning(self):
778 self.sound_file_type = 'warning'
779
780 @play_sound_file_decoration
781 @Slot()
782 def play_sound_file_critical(self):
783 self.sound_file_type = 'critical'
784
785 @play_sound_file_decoration
786 @Slot()
787 def play_sound_file_down(self):
788 self.sound_file_type = 'down'
789
790 def paint_colors(self):
791 """
792 fill color selection buttons with appropriate colors
793 """
794 # color buttons
795 for color in [x for x in conf.__dict__ if x.startswith('color_')]:
796 self.window.__dict__['input_button_%s' % (color)].setStyleSheet('''background-color: %s;
797 border-width: 1px;
798 border-color: black;
799 border-style: solid;'''
800 % conf.__dict__[color])
801 # example color labels
802 for label in [x for x in self.window.__dict__ if x.startswith('label_color_')]:
803 status = label.split('label_color_')[1]
804 self.window.__dict__[label].setStyleSheet('color: %s; background: %s' %
805 (conf.__dict__['color_%s_text' % (status)],
806 (conf.__dict__['color_%s_background' % (status)])))
807
808 @Slot()
809 def colors_defaults(self):
810 """
811 apply default colors to buttons
812 """
813 # color buttons
814 for default_color in [x for x in conf.__dict__ if x.startswith('default_color_')]:
815 # cut 'default_' off to get color
816 color = default_color.split('default_')[1]
817 self.window.__dict__['input_button_%s' % (color)].setStyleSheet('''background-color: %s;
818 border-width: 1px;
819 border-color: black;
820 border-style: solid;'''
821 % conf.__dict__[default_color])
822 # example color labels
823 for label in [x for x in self.window.__dict__ if x.startswith('label_color_')]:
824 status = label.split('label_color_')[1]
825
826 # get color values from color button stylesheets
827 color_text = self.window.__dict__['input_button_color_' + status + '_text'].styleSheet()
828 color_text = color_text.split(':')[1].strip().split(';')[0]
829 color_background = self.window.__dict__['input_button_color_' + status + '_background'].styleSheet()
830 color_background = color_background.split(':')[1].strip().split(';')[0]
831
832 # apply color values from stylesheet to label
833 self.window.__dict__[label].setStyleSheet('color: %s; background: %s' %
834 (color_text, color_background))
835
836 @Slot(str)
837 def color_chooser(self, item):
838 """
839 open QColorDialog to choose a color and change it in the settings dialog
840 """
841 color = conf.__dict__['color_%s' % (item)]
842
843 new_color = QColorDialog.getColor(QColor(color), parent=self.window)
844 # if canceled, the color is invalid
845 if new_color.isValid():
846 self.window.__dict__[f'input_button_color_{item}'].setStyleSheet(f'''background-color: {new_color.name()};
847 border-width: 1px;
848 border-color: black;
849 border-style: solid;
850 ''')
851 status = item.split('_')[0]
852 # get color value from stylesheet to paint example
853 text = self.window.__dict__[f'input_button_color_{status}_text'].styleSheet()
854 text = text.split(':')[1].strip().split(';')[0]
855 background = self.window.__dict__[f'input_button_color_{status}_background'].styleSheet()
856 background = background.split(':')[1].strip().split(';')[0]
857 # set example color
858 self.window.__dict__[f'label_color_{status}'].setStyleSheet(f'''color: {text};
859 background: {background};
860 ''')
861 # update alternation colors
862 self.paint_color_alternation()
863 self.change_color_alternation(self.window.input_slider_grid_alternation_intensity.value())
864
865 def paint_color_alternation(self):
866 """
867 paint the intensity example color labels taking actual colors from color chooser buttons
868 these labels have the color of alteration level 0 aka default
869 """
870 for state in COLORS:
871 # get text color from button CSS
872 text = self.window.__dict__['input_button_color_{0}_text'
873 .format(state.lower())] \
874 .styleSheet() \
875 .split(';\n')[0].split(': ')[1]
876 # get background color from button CSS
877 background = self.window.__dict__['input_button_color_{0}_background'
878 .format(state.lower())] \
879 .styleSheet() \
880 .split(';\n')[0].split(': ')[1]
881 # set CSS
882 self.window.__dict__['label_intensity_{0}_0'.format(state.lower())] \
883 .setStyleSheet('''color: {0};
884 background-color: {1};
885 padding-top: 3px;
886 padding-bottom: 3px;
887 '''.format(text, background))
888
889 @Slot(int)
890 def change_color_alternation(self, value):
891 """
892 fill alternation level 1 labels with altered color
893 derived from level 0 labels aka default
894 """
895 for state in COLORS:
896 # only evaluate colors if there is any stylesheet
897 if len(self.window.__dict__['input_button_color_{0}_text'
898 .format(state.lower())] \
899 .styleSheet()) > 0:
900
901 # access both labels
902 label_0 = self.window.__dict__['label_intensity_{0}_0'.format(state.lower())]
903 label_1 = self.window.__dict__['label_intensity_{0}_1'.format(state.lower())]
904
905 # get text color from text color chooser button
906 text = self.window.__dict__['input_button_color_{0}_text'
907 .format(state.lower())] \
908 .styleSheet() \
909 .split(';\n')[0].split(': ')[1]
910
911 # get background of level 0 label
912 background = label_0.palette().color(QPalette.ColorRole.Window)
913 r, g, b, a = background.getRgb()
914
915 # if a label background is too dark, lighten the color instead of darken it more
916 if background.lightness() < 30:
917 if value > 5:
918 r += 30
919 g += 30
920 b += 30
921 r = round(r / 100 * (100 + value))
922 g = round(g / 100 * (100 + value))
923 b = round(b / 100 * (100 + value))
924 else:
925 r = round(r / 100 * (100 - value))
926 g = round(g / 100 * (100 - value))
927 b = round(b / 100 * (100 - value))
928
929 # finally apply new background color
930 # easier with style sheets than with QPalette/QColor
931 label_1.setStyleSheet('''color: {0};
932 background-color: rgb({1}, {2}, {3});
933 padding-top: 3px;
934 padding-bottom: 3px;
935 '''.format(text, r, g, b))
936
937 @Slot()
938 def change_color_alternation_by_value(self):
939 """
940 to be fired up when colors are reset
941 """
942 self.change_color_alternation(self.window.input_slider_grid_alternation_intensity.value())
943
944 @Slot()
945 def font_chooser(self):
946 """
947 use the font dialog to choose a font
948 """
949 self.font = QFontDialog.getFont(self.font, parent=self.window)[0]
950 self.window.label_font.setFont(self.font)
951
952 @Slot()
953 def font_default(self):
954 """
955 reset font to default font which was valid when Nagstamon was launched
956 """
957 self.window.label_font.setFont(font_default)
958 self.font = font_default
959
960 @Slot()
961 def button_check_for_new_version_clicked(self):
962 """
963 at this point, start_mode for version check is definitively False
964 """
965 self.check_for_new_version.emit(False, self.window)
966
967 @Slot()
968 def choose_browser_executable(self):
969 """
970 show dialog for selection of non-default browser
971 """
972 # present dialog with OS-specific sensible defaults
973 if OS == OS_WINDOWS:
974 file_filter = 'Executables (*.exe *.EXE);; All files (*)'
975 directory = environ['ProgramFiles']
976 elif OS == OS_MACOS:
977 file_filter = ''
978 directory = '/Applications'
979 else:
980 file_filter = ''
981 directory = '/usr/bin'
982
983 file = self.file_chooser.getOpenFileName(self.window,
984 directory=directory,
985 filter=file_filter)[0]
986
987 # only take filename if QFileDialog gave something useful back
988 if file != '':
989 self.window.input_lineedit_custom_browser.setText(file)
990
991 @Slot()
992 def toggle_zabbix_widgets(self):
993 """
994 depending on the existence of an enabled Zabbix monitor, the Zabbix widgets are shown or hidden
995 """
996 use_zabbix = False
997 for server in servers.values():
998 if server.enabled:
999 if server.type.startswith('Zabbix'):
1000 use_zabbix = True
1001 break
1002 # remove extra Zabbix options
1003 if use_zabbix:
1004 for widget in self.ZABBIX_WIDGETS:
1005 widget.show()
1006 else:
1007 for widget in self.ZABBIX_WIDGETS:
1008 widget.hide()
1009 # remove custom color intensity labels
1010 if use_zabbix and self.window.input_checkbox_grid_use_custom_intensity.isChecked():
1011 for widget in self.ZABBIX_COLOR_INTENSITY_LABELS:
1012 widget.show()
1013 else:
1014 for widget in self.ZABBIX_COLOR_INTENSITY_LABELS:
1015 widget.hide()
1016
1017 @Slot()
1018 def toggle_op5monitor_widgets(self):
1019 """
1020 depending on the existence of an enabled Op5Monitor monitor, the Op5Monitor widgets are shown or hidden
1021 """
1022 use_op5monitor = False
1023 for server in servers.values():
1024 if server.enabled:
1025 if server.type == 'op5Monitor':
1026 use_op5monitor = True
1027 break
1028 if use_op5monitor:
1029 for widget in self.OP5MONITOR_WIDGETS:
1030 widget.show()
1031 else:
1032 for widget in self.OP5MONITOR_WIDGETS:
1033 widget.hide()
1034
1035 @Slot()
1036 def toggle_expire_time_widgets(self):
1037 """
1038 depending on the existence of an enabled IcingaWeb2 or Alertmanager monitor, the expire_time widgets are shown or hidden
1039 """
1040 use_expire_time = False
1041 for server in servers.values():
1042 if server.enabled:
1043 if server.type in ['IcingaWeb2', 'Icinga2API', 'IcingaDBWeb', 'Alertmanager']:
1044 use_expire_time = True
1045 break
1046 if use_expire_time:
1047 for widget in self.EXPIRE_TIME_WIDGETS:
1048 widget.show()
1049 else:
1050 for widget in self.EXPIRE_TIME_WIDGETS:
1051 widget.hide()
1052
1053 @Slot()
1054 def toggle_systray_icon_offset(self):
1055 """
1056 only show offset spinbox when offset is enabled
1057 """
1058 if self.window.input_checkbox_systray_offset_use.isVisible():
1059 if self.window.input_checkbox_systray_offset_use.isChecked():
1060 self.window.input_spinbox_systray_offset.show()
1061 self.window.label_offset_statuswindow.show()
1062 else:
1063 self.window.input_spinbox_systray_offset.hide()
1064 self.window.label_offset_statuswindow.hide()
1065 else:
1066 self.window.input_spinbox_systray_offset.hide()
1067 self.window.label_offset_statuswindow.hide()