-
Notifications
You must be signed in to change notification settings - Fork 3
/
widget.py
481 lines (383 loc) · 17 KB
/
widget.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
import logging
from difflib import context_diff
from functools import partial
import re
from Qt import (
QtGui,
QtWidgets,
QtCore
)
from .handler import LogbookHandler
class Worker(QtCore.QRunnable):
def __init__(self, func, *func_args, **func_kwargs):
super(Worker, self).__init__()
self.func = func
self.func_args = func_args
self.func_kwargs = func_kwargs
@QtCore.Slot()
def run(self):
return self.func(*self.func_args, **self.func_kwargs)
class LogRecordItem(QtWidgets.QListWidgetItem):
""" a simple QListWidgetItem with LogRecord storage. """
def __init__(self, record, formatter=None):
if formatter:
text = formatter.format(record)
else:
text = record.getMessage()
super(LogRecordItem, self).__init__(text)
self._record = record
@property
def record(self):
return self._record
def setBackgroundColor(self, color):
# Qt.py doesn't handle this, so maintain compatibility
try:
super(LogRecordItem, self).setBackgroundColor(color)
except AttributeError:
self.setBackground(QtGui.QBrush(color))
def set_foreground_color(self, color):
self.setForeground(QtGui.QBrush(color))
def set_readable_foreground_color(self, background_color):
almost_black = QtGui.QColor(QtCore.Qt.darkGray).darker(300)
almost_white = QtGui.QColor(QtCore.Qt.white).darker(120)
self.set_foreground_color(
almost_black if background_color.lightnessF() > 0.3 else almost_white
)
class LogRecordsListWidget(QtWidgets.QListWidget):
""" A simple QListWidget with custom events. """
def __init__(self, context_request_signal, parent=None):
super(LogRecordsListWidget, self).__init__(parent)
self.setSelectionMode(self.ExtendedSelection)
self._context_request_signal = context_request_signal
def mousePressEvent(self, event):
""" extend the mousePressEvent
We are adding a context widget request on RMB click here
Args:
event:
Returns:
"""
if event.button() == QtCore.Qt.RightButton:
cursor_pos = QtGui.QCursor.pos()
items = self.selectedItems() or [self.itemAt(self.mapFromGlobal(cursor_pos))]
if items:
self._context_request_signal.emit(cursor_pos, [_ for _ in items], self)
super(LogRecordsListWidget, self).mousePressEvent(event)
class LogbookWidget(QtWidgets.QWidget):
""" A simple widget that makes log reading more pleasant. """
class Flags:
# sets the `Coloring` checkbox on launch
INITIAL_COLORING = 2**1
# defines whether background color or foreground color (text) of an item will be set
COLORING_TEXT = 2**2
# if background color will be set this automatically sets a foreground color for better readability
READABLE_TEXT_COLOR = 2**3
# sets the `Ignore Case` checkbox on launch
RE_IGNORE_CASE = 2**4
# If a formatter was set to the handler, it can be explicitly ignored.
# This means, the formatter will not be considered as the recorditem's text.
# Instead it will only use the LogRecord.getMessage() directly.
IGNORE_FORMATTER = 2**5
FLAGS = 0
LABEL_WIDTH = 70
LEVEL_BUTTON_WIDTH = 60
LOG_LEVELS = [
"debug",
"info",
"warning",
"error",
"critical"
]
LEVEL_VALUES = {
LOG_LEVELS[0]: logging.DEBUG,
LOG_LEVELS[1]: logging.INFO,
LOG_LEVELS[2]: logging.WARNING,
LOG_LEVELS[3]: logging.ERROR,
LOG_LEVELS[4]: logging.CRITICAL
}
LEVEL_COLORS = {
LOG_LEVELS[0]: (255, 255, 255, 100),
LOG_LEVELS[1]: (204, 236, 242, 100),
LOG_LEVELS[2]: (152, 210, 217, 100),
LOG_LEVELS[3]: (223, 57, 57, 100),
LOG_LEVELS[4]: (182, 60, 66, 100)
}
INITIAL_FILTER_REGEX = r""
EXCEPTION_FORMATTER = logging.Formatter()
_handler = LogbookHandler()
def __init__(self, parent=None):
super(LogbookWidget, self).__init__(parent)
# if somebody wants to customize the levels ensure he does it properly
# to avoid issues downstream
self._validate_levels()
self._filter_regex = re.compile(
r"{}".format(self.INITIAL_FILTER_REGEX),
flags=re.IGNORECASE if self._use_re_ignore_case else 0
)
self._threadpool = QtCore.QThreadPool()
self._foreground_brush = None
self._colors = {k: QtGui.QColor(*v) for k, v in self.LEVEL_COLORS.items()}
self._setup_ui()
self._setup_signals()
# set other default states
if self._use_coloring:
self.coloring_checkbox.setChecked(True)
if self._use_re_ignore_case:
self.filter_case_box.setChecked(True)
@property
def _use_coloring(self):
return (self.FLAGS & self.Flags.INITIAL_COLORING) > 0
@property
def _use_text_coloring(self):
return (self.FLAGS & self.Flags.COLORING_TEXT) > 0
@property
def _use_readable_text_coloring(self):
return (self.FLAGS & self.Flags.READABLE_TEXT_COLOR) > 0
@property
def _use_re_ignore_case(self):
return (self.FLAGS & self.Flags.RE_IGNORE_CASE) > 0
@property
def _ignore_formatter(self):
return (self.FLAGS & self.Flags.IGNORE_FORMATTER) > 0
@classmethod
def _validate_levels(cls):
""" ensure we allow flexible level addition but give proper guidance """
_missing_key_msg = "Missing key '{}' in '{}' attribute."
_keys_number_msg = "Level name entries in '{}' attribute not matching: \n {}."
_type_msg = "Given level for level name '{}' must be of type {}. Got {}."
_invalid_rgba_msg = "Given value {} is not a proper RGB(A) color using values 0-255[0-100]."
# check for equal keys
_level_names_sorted = sorted(cls.LOG_LEVELS)
_level_values_keys_sorted = sorted(cls.LEVEL_VALUES.keys())
_level_colors_keys_sorted = sorted(cls.LEVEL_COLORS.keys())
if _level_names_sorted != _level_values_keys_sorted:
raise ValueError(_keys_number_msg.format(
"LEVEL_VALUES",
# todo: maybe not helpful enough
"".join(context_diff(_level_names_sorted, _level_values_keys_sorted))
)
)
if _level_names_sorted != _level_colors_keys_sorted:
raise ValueError(_keys_number_msg.format(
"LEVEL_COLORS",
"".join(context_diff(_level_names_sorted, _level_colors_keys_sorted))
)
)
for level_name in cls.LOG_LEVELS:
if level_name not in cls.LEVEL_VALUES:
raise KeyError(_missing_key_msg.format(level_name, "LEVEL_VALUES"))
if level_name not in cls.LEVEL_COLORS:
raise KeyError(_missing_key_msg.format(level_name, "LEVEL_COLORS"))
# check log level values
if not isinstance(cls.LEVEL_VALUES[level_name], int):
raise TypeError(_type_msg.format(
level_name,
"int",
type(cls.LEVEL_VALUES[level_name])
)
)
if cls.LEVEL_VALUES[level_name] < 1:
raise ValueError("A log level for level name '{}' must be defined with a value <= 1.".format(
level_name
)
)
# check log level colors
if not isinstance(cls.LEVEL_COLORS[level_name], (list, tuple)):
raise TypeError(_type_msg.format(
level_name,
"tuple or int",
type(cls.LEVEL_COLORS[level_name])
)
)
# check RGBA values
if [True, True, True] != [_ >= 0 and _ <= 255 for _ in cls.LEVEL_COLORS[level_name][:3]]:
raise ValueError(_invalid_rgba_msg.format(
cls.LEVEL_COLORS[level_name]
)
)
if len(cls.LEVEL_COLORS[level_name]) == 4:
if cls.LEVEL_COLORS[level_name][-1] <= 0 or cls.LEVEL_COLORS[level_name][-1] > 100:
raise ValueError(_invalid_rgba_msg.format(
cls.LEVEL_COLORS[level_name]
)
)
elif len(cls.LEVEL_COLORS[level_name]) > 4:
raise ValueError(_invalid_rgba_msg.format(cls.LEVEL_COLORS[level_name]))
def _setup_ui(self):
""" build the actual ui """
h_separator = QtWidgets.QFrame()
h_separator.setFrameStyle(QtWidgets.QFrame.HLine | QtWidgets.QFrame.Raised)
v_separator = QtWidgets.QFrame()
v_separator.setFrameStyle(QtWidgets.QFrame.VLine | QtWidgets.QFrame.Raised)
container_layout = QtWidgets.QVBoxLayout(self)
self.setLayout(container_layout)
options_group = QtWidgets.QGroupBox("Options")
container_layout.addWidget(options_group)
# === level buttons section ===
options_layout = QtWidgets.QVBoxLayout()
options_group.setLayout(options_layout)
level_buttons_layout = QtWidgets.QHBoxLayout()
options_layout.addLayout(level_buttons_layout)
levels_label = QtWidgets.QLabel("Levels: ")
levels_label.setFixedWidth(self.LABEL_WIDTH)
level_buttons_layout.addWidget(levels_label)
self.level_buttons = []
for level_name in self.LOG_LEVELS:
level_value = self.LEVEL_VALUES[level_name]
_button_style = "QPushButton:%s {border-style: outset; background-color: rgba(" + \
", ".join([str(_) for _ in self.LEVEL_COLORS[level_name]]) + \
")}"
button = QtWidgets.QPushButton()
button.setAutoFillBackground(True)
button.setText(level_name)
button.setCheckable(True)
button.setFixedHeight(20)
button.setProperty("levelno", level_value)
button.setChecked(True)
button.setFixedWidth(self.LEVEL_BUTTON_WIDTH)
button.setStyleSheet(_button_style % "checked" + _button_style % "pressed")
level_buttons_layout.addWidget(button)
self.level_buttons.append(button)
level_buttons_layout.addWidget(v_separator)
self.coloring_checkbox = QtWidgets.QCheckBox("Coloring")
level_buttons_layout.addWidget(self.coloring_checkbox)
level_buttons_layout.addStretch()
options_layout.addWidget(h_separator)
# === filter field ===
filter_layout = QtWidgets.QHBoxLayout()
options_layout.addLayout(filter_layout)
filter_label = QtWidgets.QLabel("Filter: ")
filter_label.setFixedWidth(self.LABEL_WIDTH)
filter_layout.addWidget(filter_label)
self.filter_edit = QtWidgets.QLineEdit(self.INITIAL_FILTER_REGEX)
self.filter_edit.setStyleSheet("""QWidget {border: none} """)
filter_layout.addWidget(self.filter_edit)
self.filter_case_box = QtWidgets.QCheckBox("Ignore case")
filter_layout.addWidget(self.filter_case_box)
records_group = QtWidgets.QGroupBox("Records")
container_layout.addWidget(records_group)
# === records list ===
records_layout = QtWidgets.QVBoxLayout()
records_group.setLayout(records_layout)
self.records_list = LogRecordsListWidget(
context_request_signal=self.signals.record_context_request
)
self.records_list.setStyleSheet("""QWidget {border: none} """)
records_layout.addWidget(self.records_list)
self.clear_records_button = QtWidgets.QPushButton("Clear Records")
self.clear_records_button.setFixedWidth(90)
records_layout.addWidget(self.clear_records_button)
def _setup_signals(self):
""" setup all Qt signals """
self.handler.signals.signal_record.connect(self.add_record)
for level_button in self.level_buttons:
level_button.toggled.connect(
partial(self._on_level_button_toggled, level_button)
)
self.clear_records_button.clicked.connect(self.records_list.clear)
self.coloring_checkbox.toggled.connect(self._toggle_coloring)
self.filter_edit.textChanged.connect(self._on_filter_changed)
self.filter_case_box.toggled.connect(self._on_filter_changed)
def _on_level_button_toggled(self, button, state):
""" handles show states of LogRecordItems """
self._revert_filter_states()
for item in self._record_items:
self._filter(item)
def _on_filter_changed(self, text_or_case):
""" performs a regex match on all record items and filter out items that will not match """
# as we use this as a callback on a QCheckBox state and QLineEdit text change
# lets always grab the information from the widgets
flags = re.IGNORECASE if self.filter_case_box.isChecked() else 0
text = self.filter_edit.text()
self._filter_regex = re.compile(r"{}".format(text), flags=flags)
self._revert_filter_states()
for item in self._record_items:
self._filter(item)
def _revert_filter_states(self):
for item in self._record_items:
item.setHidden(False)
def _toggle_coloring(self, state):
""" activates or deactivates background coloring for record items """
for item in self._record_items:
if not self._use_text_coloring:
self._set_background_color(item)
else:
self._set_text_color(item)
def _set_item_color(self, item):
if self._use_text_coloring:
self._set_text_color(item)
else:
self._set_background_color(item)
def _set_background_color(self, item):
""" actives or deactivates background coloring
This is based on the check state of the coloring checkbox.
"""
if self.coloring_checkbox.isChecked():
item.setBackgroundColor(
self._colors[self._get_level_name_from_level_value(item.record.levelno)]
)
if self._use_readable_text_coloring:
item.set_readable_foreground_color(item.backgroundColor())
else:
item.setBackgroundColor(QtGui.QColor(0, 0, 0, 0))
def _set_text_color(self, item):
""" actives or deactivates background coloring
This is based on the check state of the coloring checkbox.
"""
if self.coloring_checkbox.isChecked():
item.setForeground(
self._colors[self._get_level_name_from_level_value(item.record.levelno)]
)
else:
item.setForeground(self._foreground_brush)
def _get_level_name_from_level_value(self, value):
""" a helper to retrieve the level name from the associated value """
for k, v in self.LEVEL_VALUES.items():
if v == value:
return k
raise ValueError("Value {} not found in LEVEL_VALUES attribute.".format(value))
def _filter(self, item):
""" set visibility state based on filter regex match and active levels """
_match = self._filter_regex.search(item.text())
if not _match or item.record.levelno not in self._active_levels:
item.setHidden(True)
@property
def _active_levels(self):
return [_.property("levelno") for _ in self.level_buttons if _.isChecked()]
@property
def _record_items(self):
""" all available record items """
for row in range(self.records_list.count()):
yield self.records_list.item(row)
def add_record(self, log_record):
""" adds a LogRecord object to the records list widget"""
def _add_item():
if self._ignore_formatter:
formatter = None
else:
formatter = self.handler.formatter
item = LogRecordItem(log_record, formatter)
# there is likely a better way to revert back to the initial brush/color of an item
# but for now lets store it before we apply any color change
self._foreground_brush = self._foreground_brush or item.foreground()
self.records_list.addItem(item)
self._set_tooltip(item)
self._filter(item)
self._set_item_color(item)
worker = Worker(_add_item)
self._threadpool.start(worker)
def _set_tooltip(self, item):
if item.record.exc_info:
item.setToolTip(self.EXCEPTION_FORMATTER.formatException(item.record.exc_info))
@property
def handler(self):
""" THE handler somebody has to add to the logger he wants to catch messages for.
Examples:
>>> import logging
>>> my_logger = logging.getLogger("cool.stuff")
>>> logbook = LogbookWidget()
>>> my_logger.addHandler(logbook.handler)
"""
return self._handler
@property
def signals(self):
return self.handler.signals