| 1 |
"""Utility functions and exceptions for debugging and error handling in DisplayCAL. |
| 2 |
|
| 3 |
It includes functionality for retrieving event object names and types, handling |
| 4 |
errors with optional logging and user notifications, and printing call stacks |
| 5 |
for debugging purposes. |
| 6 |
""" |
| 7 |
|
| 8 |
from __future__ import annotations |
| 9 |
|
| 10 |
import traceback |
| 11 |
from typing import TYPE_CHECKING |
| 12 |
|
| 13 |
from DisplayCAL.meta import WX_RECVERSION |
| 14 |
from DisplayCAL.options import DEBUG |
| 15 |
from DisplayCAL.util_str import box |
| 16 |
|
| 17 |
if TYPE_CHECKING: |
| 18 |
from types import TracebackType |
| 19 |
|
| 20 |
from DisplayCAL.wx_addons import wx # noqa: TC004 |
| 21 |
|
| 22 |
|
| 23 |
WX_EVENT_TYPES = {} |
| 24 |
|
| 25 |
|
| 26 |
def getevtobjname(event: wx.Event, window: None | wx.Window = None) -> None | str: |
| 27 |
"""Get and return the event object's name. |
| 28 |
|
| 29 |
Args: |
| 30 |
event (wx.Event): The event object to get the name from. |
| 31 |
window (None | wx.Window, optional): Optional window to search for the |
| 32 |
event object. |
| 33 |
|
| 34 |
Returns: |
| 35 |
None | str: The name of the event object, or None if it cannot be |
| 36 |
determined. |
| 37 |
""" |
| 38 |
try: |
| 39 |
event_object = event.GetEventObject() |
| 40 |
if not event_object and window: |
| 41 |
event_object = window.FindWindowById(event.GetId()) |
| 42 |
if event_object and hasattr(event_object, "GetName"): |
| 43 |
return event_object.GetName() |
| 44 |
except Exception: |
| 45 |
pass |
| 46 |
|
| 47 |
|
| 48 |
def getevttype(event: wx.Event) -> None | str: |
| 49 |
"""Get and return the event object's type. |
| 50 |
|
| 51 |
Args: |
| 52 |
event: The event object to get the type from. |
| 53 |
|
| 54 |
Returns: |
| 55 |
None | str: The name of the event type, or None if it cannot be |
| 56 |
determined. |
| 57 |
""" |
| 58 |
if not WX_EVENT_TYPES: |
| 59 |
from DisplayCAL.wx_addons import wx |
| 60 |
|
| 61 |
try: |
| 62 |
for name in dir(wx): |
| 63 |
if name.find("EVT_") == 0: |
| 64 |
attr = getattr(wx, name) |
| 65 |
if hasattr(attr, "evtType"): |
| 66 |
WX_EVENT_TYPES[attr.evtType[0]] = name |
| 67 |
except Exception: |
| 68 |
pass |
| 69 |
type_id = event.GetEventType() |
| 70 |
if type_id in WX_EVENT_TYPES: |
| 71 |
return WX_EVENT_TYPES[type_id] |
| 72 |
return None |
| 73 |
|
| 74 |
|
| 75 |
def handle_error( |
| 76 |
error: tuple[type, str, TracebackType] | Exception, |
| 77 |
parent: None | wx.Window = None, |
| 78 |
silent: bool = False, |
| 79 |
tb: bool = True, |
| 80 |
) -> None: |
| 81 |
"""Log an error string and show an error dialog. |
| 82 |
|
| 83 |
Args: |
| 84 |
error (tuple[type, str, TracebackType] | Exception): The error to handle, |
| 85 |
which can be a tuple containing the exception type, value, and |
| 86 |
traceback, or an Exception instance. |
| 87 |
parent (None | wx.Window): The parent window for the error dialog. |
| 88 |
silent (bool): If True, suppresses the dialog display. |
| 89 |
tb (bool): If True, includes the traceback in the error message. |
| 90 |
""" |
| 91 |
traceback.print_exc() |
| 92 |
msg = "" |
| 93 |
if isinstance(error, tuple): |
| 94 |
# We got a tuple. Assume (etype, value, tb) |
| 95 |
tbstr = "".join(traceback.format_exception(*error)) |
| 96 |
error = error[1] |
| 97 |
else: |
| 98 |
tbstr = traceback.format_exc() |
| 99 |
|
| 100 |
if ( |
| 101 |
tb |
| 102 |
and tbstr.strip() != "None" |
| 103 |
and isinstance(error, Exception) |
| 104 |
and ( |
| 105 |
DEBUG |
| 106 |
or not isinstance(error, OSError) |
| 107 |
or not getattr(error, "filename", None) |
| 108 |
) |
| 109 |
): |
| 110 |
# Print a traceback if in debug mode, for non OS errors, |
| 111 |
# and for OS errors not related to files |
| 112 |
errstr, tbstr = (str(v) for v in (error, tbstr)) |
| 113 |
msg = f"{errstr}\n\n{tbstr}" |
| 114 |
if msg.startswith(errstr): |
| 115 |
print(box(tbstr)) |
| 116 |
else: |
| 117 |
print(box(msg)) |
| 118 |
else: |
| 119 |
msg = str(error) |
| 120 |
print(box(msg)) |
| 121 |
|
| 122 |
if silent: |
| 123 |
return |
| 124 |
|
| 125 |
try: |
| 126 |
show_error_dialog(error, msg, parent) |
| 127 |
except Exception as exception: |
| 128 |
traceback.print_exc() |
| 129 |
print("Warning: handle_error():", str(exception)) |
| 130 |
|
| 131 |
|
| 132 |
def show_error_dialog( |
| 133 |
error: Exception, |
| 134 |
msg: str, |
| 135 |
parent: None | wx.Window = None, |
| 136 |
) -> None: |
| 137 |
"""Show an error dialog. |
| 138 |
|
| 139 |
Args: |
| 140 |
error (Exception): The error to display. |
| 141 |
msg (str): The message to display in the dialog. |
| 142 |
parent (None | wx.Window): The parent window for the dialog. |
| 143 |
""" |
| 144 |
from DisplayCAL.wx_addons import wx |
| 145 |
|
| 146 |
if wx.VERSION < WX_RECVERSION: # noqa: SIM300 |
| 147 |
msg += ( |
| 148 |
"\n\nWARNING: Your version of wxPython ({}) is outdated " |
| 149 |
"and no longer supported. You should consider updating " |
| 150 |
"to wxPython {} or newer.".format( |
| 151 |
wx.__version__, ".".join(str(n) for n in WX_RECVERSION) |
| 152 |
) |
| 153 |
) |
| 154 |
app = wx.GetApp() |
| 155 |
if app is None and parent is None: |
| 156 |
app = wx.App(redirect=False) |
| 157 |
# wxPython 3 bugfix: We also need a toplevel window |
| 158 |
frame = wx.Frame(None) |
| 159 |
parent = False |
| 160 |
else: |
| 161 |
frame = None |
| 162 |
parent = wx.GetActiveWindow() if parent is None else parent |
| 163 |
if parent: |
| 164 |
try: |
| 165 |
parent.IsShownOnScreen() |
| 166 |
except Exception: |
| 167 |
# If the parent is still being constructed, we can't use it |
| 168 |
parent = None |
| 169 |
icon = wx.ICON_INFORMATION |
| 170 |
if not isinstance(error, Info): |
| 171 |
if isinstance(error, Warning): |
| 172 |
icon = wx.ICON_WARNING |
| 173 |
elif isinstance(error, Exception): |
| 174 |
icon = wx.ICON_ERROR |
| 175 |
dlg = wx.MessageDialog( |
| 176 |
(parent if parent not in (False, None) and parent.IsShownOnScreen() else None), |
| 177 |
msg, |
| 178 |
app.AppName, |
| 179 |
wx.OK | icon, |
| 180 |
) |
| 181 |
if frame: |
| 182 |
# wxPython 3 bugfix: We need to use CallLater and MainLoop |
| 183 |
wx.CallLater(1, dlg.ShowModal) |
| 184 |
wx.CallLater(1, frame.Close) |
| 185 |
app.MainLoop() |
| 186 |
else: |
| 187 |
dlg.ShowModal() |
| 188 |
dlg.Destroy() |
| 189 |
|
| 190 |
|
| 191 |
def print_callstack() -> None: |
| 192 |
"""Print call stack.""" |
| 193 |
import inspect |
| 194 |
|
| 195 |
stack = inspect.stack() |
| 196 |
indent = "" |
| 197 |
for _frame, filename, linenum, funcname, line, _exc in reversed(stack[1:]): |
| 198 |
print(indent, funcname, filename, linenum, repr("".join(line).strip())) |
| 199 |
indent += " " |
| 200 |
|
| 201 |
|
| 202 |
class ResourceError(Exception): |
| 203 |
"""Error class for resource errors.""" |
| 204 |
|
| 205 |
|
| 206 |
class Error(Exception): |
| 207 |
"""Error class for fatal errors.""" |
| 208 |
|
| 209 |
|
| 210 |
class Info(UserWarning): |
| 211 |
"""Info class for non-fatal errors.""" |
| 212 |
|
| 213 |
|
| 214 |
class UnloggedError(Error): |
| 215 |
"""Error class for non-fatal errors that should not be logged.""" |
| 216 |
|
| 217 |
|
| 218 |
class UnloggedInfo(Info): |
| 219 |
"""Info class for non-fatal errors that should not be logged.""" |
| 220 |
|
| 221 |
|
| 222 |
class UnloggedWarning(UserWarning): |
| 223 |
"""Warning class for non-fatal errors that should not be logged.""" |
| 224 |
|
| 225 |
|
| 226 |
class DownloadError(Error): |
| 227 |
"""Error class for download errors.""" |
| 228 |
|
| 229 |
def __init__(self, *args) -> None: |
| 230 |
Error.__init__(self, *args[:-1]) |
| 231 |
self.url = args[1] |
| 232 |
|
| 233 |
|
| 234 |
class UntracedError(Error): |
| 235 |
"""Error class for errors that should not be logged.""" |
| 236 |
|
| 237 |
|
| 238 |
class Warn(UserWarning): |
| 239 |
"""Warning class for non-fatal errors.""" |