Debian Codegraph @

Nagstamon/qui/qt.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 # Select Qt version based on installation found
19 # Prefer in this order: PyQt6 - PyQt5
20
21 from os import environ
22 from pathlib import Path
23 import sys
24
25 # Differences in *.ui files between PyQt5 and PyQt6, will be replaced when UI files are loaded
26 UI_FILE_QT6_QT5_DOWNGRADES = {
27 'AnyTerritory': 'AnyCountry',
28 'QDialogButtonBox::StandardButton::Cancel': 'QDialogButtonBox::Cancel',
29 'QDialogButtonBox::StandardButton::Ok': 'QDialogButtonBox::Ok',
30 'QFrame::Shadow::Sunken': 'QFrame::Sunken',
31 'QFrame::Shape::Box': 'QFrame::Box',
32 'QLayout::SizeConstraint::SetMinimumSize': 'QLayout::SetMinimumSize',
33 'QLineEdit::EchoMode::Password': 'QLineEdit::Password',
34 'QListView::ResizeMode::Adjust': 'QListView::Adjust',
35 'Qt::AlignmentFlag::AlignCenter': 'Qt::AlignCenter',
36 'Qt::AlignmentFlag::AlignLeading': 'Qt::AlignLeading',
37 'Qt::AlignmentFlag::AlignLeft': 'Qt::AlignLeft',
38 'Qt::AlignmentFlag::AlignTop': 'Qt::AlignTop',
39 'Qt::AlignmentFlag::AlignVCenter': 'Qt::AlignVCenter',
40 'Qt::Orientation::Horizontal': 'Qt::Horizontal',
41 'Qt::Orientation::Vertical': 'Qt::Vertical',
42 'Qt::TextInteractionFlag::TextBrowserInteraction': 'Qt::TextBrowserInteraction',
43 'QTabWidget::TabShape::Rounded': 'QTabWidget::Rounded'
44 }
45
46 # Enough to handle with differences between PyQt5 + PyQt6, so PySide6 will be
47 # ignored right now
48 # by the little import the appropriate PyQt version will be loaded
49 # Check for PyQt6 and all its required modules
50 try:
51 from PyQt6.QtCore import PYQT_VERSION_STR as QT_VERSION_STR
52 # Check if all required PyQt6 modules are available
53 # This prevents crashes when PyQt6 is partially installed
54 from PyQt6.QtMultimedia import QAudioOutput
55 from PyQt6.QtWebEngineCore import QWebEnginePage
56 from PyQt6.QtWebEngineWidgets import QWebEngineView
57 from PyQt6.QtSvg import QSvgRenderer
58 from PyQt6.QtSvgWidgets import QSvgWidget
59
60 # get int-ed version parts
61 QT_VERSION_MAJOR, QT_VERSION_MINOR = [int(x) for x in QT_VERSION_STR.split('.')[0:2]]
62 # for later decision which differences have to be considered
63 QT_FLAVOR = 'PyQt6'
64 except ImportError:
65 try:
66 from PyQt5.QtCore import PYQT_VERSION_STR as QT_VERSION_STR
67
68 # get int-ed version parts
69 QT_VERSION_MAJOR, QT_VERSION_MINOR = [int(x) for x in QT_VERSION_STR.split('.')[0:2]]
70 # for later decision which differences have to be considered
71 QT_FLAVOR = 'PyQt5'
72 except ImportError:
73 sys.exit('Qt is missing')
74
75 # useful for testing to force a specific Qt version
76 if environ.get('NAGSTAMON_QT_FLAVOR'):
77 QT_FLAVOR = environ.get('NAGSTAMON_QT_FLAVOR')
78 if QT_FLAVOR == 'PyQt6':
79 try:
80 from PyQt6.QtCore import PYQT_VERSION_STR as QT_VERSION_STR
81 # Check if all required PyQt6 modules are available
82 from PyQt6.QtMultimedia import QAudioOutput
83 from PyQt6.QtWebEngineCore import QWebEnginePage
84 from PyQt6.QtWebEngineWidgets import QWebEngineView
85 from PyQt6.QtSvg import QSvgRenderer
86 from PyQt6.QtSvgWidgets import QSvgWidget
87
88 # get int-ed version parts
89 QT_VERSION_MAJOR, QT_VERSION_MINOR = [int(x) for x in QT_VERSION_STR.split('.')[0:2]]
90 except ImportError as e:
91 sys.exit(f"NAGSTAMON_QT_FLAVOR set to PyQt6 but required modules are missing: {e}")
92 elif QT_FLAVOR == 'PyQt5':
93 from PyQt5.QtCore import PYQT_VERSION_STR as QT_VERSION_STR
94
95 # get int-ed version parts
96 QT_VERSION_MAJOR, QT_VERSION_MINOR = [int(x) for x in QT_VERSION_STR.split('.')[0:2]]
97 else:
98 sys.exit("NAGSTAMON_QT_FLAVOR has invalid value. Use 'PyQt5' or 'PyQt6'.")
99
100 # because 'PyQt6' is in sys.modules even if the import some line before failed
101 # the backup PyQt5 should be loaded earlier if it exists due to exception treatment
102 if QT_FLAVOR == 'PyQt5':
103 from PyQt5.QtCore import pyqtSignal as Signal, \
104 pyqtSlot as Slot, \
105 PYQT_VERSION_STR as QT_VERSION_STR, \
106 QAbstractTableModel, \
107 QByteArray, \
108 QDateTime, \
109 QModelIndex, \
110 QObject, \
111 QPoint, \
112 QSignalMapper, \
113 Qt, \
114 QThread, \
115 QTimer, \
116 QUrl, \
117 QVariant, \
118 QXmlStreamReader
119 from PyQt5.QtGui import QBrush, \
120 QColor, \
121 QCursor, \
122 QFont, \
123 QFontDatabase, \
124 QIcon, \
125 QKeySequence, \
126 QPainter, \
127 QPalette, \
128 QPixmap, \
129 QWindow
130 from PyQt5.QtMultimedia import QMediaContent, \
131 QMediaPlayer, \
132 QMediaPlaylist
133 from PyQt5.QtNetwork import (QNetworkCookie,
134 QNetworkProxy,
135 QNetworkProxyFactory)
136 from PyQt5.QtSvg import QSvgRenderer, \
137 QSvgWidget
138 from PyQt5.QtWebEngineWidgets import (QWebEngineCertificateError as WebEngineCertificateError,
139 QWebEnginePage as WebEnginePage,
140 QWebEngineProfile as WebEngineProfile,
141 QWebEngineView as WebEngineView)
142 from PyQt5.QtWidgets import QAbstractItemView, \
143 QAction, \
144 QApplication, \
145 QColorDialog, \
146 QComboBox, \
147 QDialog, \
148 QFileDialog, \
149 QFontDialog, \
150 QHBoxLayout, \
151 QHeaderView, \
152 QListWidgetItem, \
153 QMenu, \
154 QMenuBar, \
155 QMessageBox, \
156 QLabel, \
157 QProxyStyle, \
158 QPushButton, \
159 QScrollArea, \
160 QSizePolicy, \
161 QSpacerItem, \
162 QToolButton, \
163 QTreeView, \
164 QStyle, \
165 QSystemTrayIcon, \
166 QVBoxLayout, \
167 QWidget
168 from PyQt5 import uic
169
170
171 class QSignalMapper(QSignalMapper):
172 """
173 QSignalMapper has method mappedString since Qt 5.15 which is not available in Ubuntu 20.04
174 See https://github.com/HenriWahl/Nagstamon/issues/865 for details
175 """
176
177 def __init__(self):
178 super().__init__()
179 # map mappedString onto mapped
180 self.mappedString = self.mapped
181
182
183 class MediaPlayer(QObject):
184 """
185 play media files for notification
186 """
187 # needed to show error in a thread-safe way
188 send_message = Signal(str, str)
189
190 def __init__(self, resource_files):
191 QObject.__init__(self)
192 self.player = QMediaPlayer(parent=self)
193
194 self.player.setVolume(100)
195 self.playlist = QMediaPlaylist()
196 self.player.setPlaylist(self.playlist)
197 self.resource_files = resource_files
198
199 @Slot(str)
200 def set_media(self, media_file):
201 """
202 Give media_file to player and if it is one of the default files check first if still exists
203 :param media_file:
204 :return:
205 """
206 if media_file in self.resource_files:
207 # by using RESOURCE_FILES the file path will be checked on macOS and the file restored if necessary
208 media_file = self.resource_files[media_file]
209 # only existing file can be played
210 if Path(media_file).exists:
211 url = QUrl.fromLocalFile(media_file)
212 media_content = QMediaContent(url)
213 self.player.setMedia(media_content)
214 del url, media_content
215 return True
216 else:
217 # cry and tell no file was found
218 self.send_message.emit('warning',
219 'Sound file <b>\'{0}\'</b> not found for playback.'.format(media_file))
220 return False
221
222 @Slot()
223 def play(self):
224 # just play sound
225 self.player.play()
226
227
228 def get_global_position(event):
229 """
230 Qt5 uses other method than Qt6
231 """
232 return event.globalPos()
233
234
235 def get_sort_order_value(sort_order):
236 """
237 Qt5 has int for Qt.SortOrder but Qt6 has Qt.SortOrder.[Ascending|Descending]Order
238 """
239 return sort_order
240
241
242 elif QT_FLAVOR == 'PyQt6':
243 # PySide/PyQt compatibility
244 from PyQt6.QtCore import (pyqtSignal as Signal,
245 pyqtSlot as Slot,
246 PYQT_VERSION_STR as QT_VERSION_STR,
247 QAbstractTableModel,
248 QByteArray,
249 QDateTime,
250 QModelIndex,
251 QObject,
252 QPoint,
253 QSignalMapper,
254 Qt,
255 QThread,
256 QTimer,
257 QUrl,
258 QVariant,
259 QXmlStreamReader)
260 from PyQt6.QtGui import (QAction,
261 QBrush,
262 QColor,
263 QCursor,
264 QFont,
265 QFontDatabase,
266 QIcon,
267 QKeySequence,
268 QPainter,
269 QPalette,
270 QPixmap, \
271 QWindow)
272 from PyQt6.QtMultimedia import (QAudioOutput,
273 QMediaDevices,
274 QMediaPlayer)
275 from PyQt6.QtNetwork import (QNetworkCookie,
276 QNetworkProxy,
277 QNetworkProxyFactory)
278 from PyQt6.QtSvg import QSvgRenderer
279 from PyQt6.QtSvgWidgets import QSvgWidget
280 from PyQt6.QtWebEngineCore import (QWebEngineCertificateError as WebEngineCertificateError,
281 QWebEnginePage as WebEnginePage,
282 QWebEngineProfile as WebEngineProfile)
283 from PyQt6.QtWebEngineWidgets import QWebEngineView as WebEngineView
284 from PyQt6.QtWidgets import (QAbstractItemView,
285 QApplication,
286 QColorDialog,
287 QComboBox,
288 QDialog,
289 QFileDialog,
290 QFontDialog,
291 QHBoxLayout,
292 QHeaderView,
293 QListWidgetItem,
294 QMenu,
295 QMenuBar,
296 QMessageBox,
297 QLabel,
298 QProxyStyle,
299 QPushButton,
300 QScrollArea,
301 QSizePolicy,
302 QSpacerItem,
303 QToolButton,
304 QTreeView,
305 QStyle,
306 QSystemTrayIcon,
307 QVBoxLayout,
308 QWidget)
309 from PyQt6 import uic
310
311 # for later decision which differences have to be considered
312 QT_FLAVOR = 'PyQt6'
313
314
315 class MediaPlayer(QObject):
316 """
317 play media files for notification
318 """
319 # needed to show error in a thread-safe way
320 send_message = Signal(str, str)
321
322 def __init__(self, resource_files):
323 QObject.__init__(self)
324 # access to media devices
325 self.media_devices = QMediaDevices()
326 # output needed fpr player
327 self.audio_output = QAudioOutput()
328 # player gets the output device assigned before playing
329 self.player = QMediaPlayer(parent=self)
330 self.resource_files = resource_files
331
332 @Slot(str)
333 def set_media(self, media_file):
334 """
335 Give media_file to player and if it is one of the default files check first if still exists
336 :param media_file:
337 :return:
338 """
339 if media_file in self.resource_files:
340 # by using RESOURCE_FILES the file path will be checked on macOS and the file restored if necessary
341 media_file = self.resource_files[media_file]
342 # only existing file can be played
343 if Path(media_file).exists():
344 self.player.setSource(QUrl.fromLocalFile(media_file))
345 return True
346 else:
347 # cry and tell no file was found
348 self.send_message.emit('warning', f'Sound file <b>\'{media_file}\'</b> not found for playback.')
349 return False
350
351 @Slot()
352 def play(self):
353 """
354 play sound on default audio output device, triggered by signal
355 """
356 try:
357 # default audio device
358 audio_device = False
359 # because devices may change dynamically, get default output device each time before playing
360 for audio_device in self.media_devices.audioOutputs():
361 # default device found
362 if audio_device.isDefault():
363 break
364 if audio_device:
365 # use audio output device
366 self.audio_output.setDevice(audio_device)
367 # connect player with audio output
368 self.player.setAudioOutput(self.audio_output)
369 # just play sound
370 self.player.play()
371 except Exception as error:
372 print(error)
373
374
375 def get_global_position(event):
376 """
377 Qt5 uses other method than Qt6
378 """
379 return event.globalPosition()
380
381
382 def get_sort_order_value(sort_order):
383 """
384 Qt5 has int for Qt.SortOrder but Qt6 has Qt.SortOrder.[Ascending|Descending]Order
385 """
386 return sort_order.value
387
388 # elif 'PySide6' in sys.modules:
389 # from PySide6.QtCore import Signal, \
390 # Slot, \
391 # QAbstractTableModel, \
392 # QByteArray, \
393 # QDateTime, \
394 # QModelIndex, \
395 # QObject, \
396 # QPoint, \
397 # QSignalMapper, \
398 # Qt, \
399 # QThread, \
400 # QTimer, \
401 # QUrl, \
402 # QVariant, \
403 # QXmlStreamReader
404 # from PySide6.QtGui import QAction, \
405 # QBrush, \
406 # QColor, \
407 # QCursor, \
408 # QFont, \
409 # QFontDatabase, \
410 # QIcon, \
411 # QKeySequence, \
412 # QPainter, \
413 # QPalette, \
414 # QPixmap
415 # from PySide6.QtMultimedia import QAudioOutput, \
416 # QMediaPlayer
417 # from PySide6.QtSvg import QSvgRenderer
418 # from PySide6.QtSvgWidgets import QSvgWidget
419 # from PySide6.QtWidgets import QAbstractItemView, \
420 # QApplication, \
421 # QColorDialog, \
422 # QComboBox, \
423 # QDialog, \
424 # QFileDialog, \
425 # QFontDialog, \
426 # QHBoxLayout, \
427 # QHeaderView, \
428 # QListWidgetItem, \
429 # QMenu, \
430 # QMenuBar, \
431 # QMessageBox, \
432 # QLabel, \
433 #
434 # QPushButton, \
435 # QScrollArea, \
436 # QSizePolicy, \
437 # QSpacerItem, \
438 # QToolButton, \
439 # QTreeView, \
440 # QStyle, \
441 # QSystemTrayIcon, \
442 # QVBoxLayout, \
443 # QWidget
444 # # for later decision which differences have to be considered
445 # QT_FLAVOR = 'PySide6'