194 lines
8.2 KiB
Python
194 lines
8.2 KiB
Python
"""Shared error dialogs; call on the Tk thread, like tkinter.messagebox.
|
|
|
|
Informational dialogs and confirmations retain their native implementations.
|
|
Error reports are immutable text, shared by the viewer, clipboard and export.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
import traceback
|
|
import tkinter as tk
|
|
from datetime import datetime
|
|
from pathlib import Path
|
|
from tkinter import filedialog, messagebox as native_messagebox, ttk
|
|
|
|
from locale_text import text
|
|
from ui_theme import theme_font, theme_section
|
|
from version_info import APP_VERSION, module_version, versioned_title
|
|
|
|
__version__ = module_version(__name__)
|
|
|
|
|
|
def __getattr__(name):
|
|
"""Delegate non-error dialogs without changing answers or confirmation flow."""
|
|
return getattr(native_messagebox, name)
|
|
|
|
|
|
def build_error_report(title, message, exception=None, *, context="") -> str:
|
|
"""Keep the original message and chained traceback, with unabridged SQL data."""
|
|
parts = [f"{datetime.now().astimezone().isoformat(timespec='seconds')} | {title}",
|
|
f"Warehouse {APP_VERSION} | Python {sys.version}"]
|
|
if context:
|
|
parts.append(context)
|
|
parts.append(str(message))
|
|
if exception is not None:
|
|
trace = traceback.TracebackException.from_exception(
|
|
exception, max_group_width=sys.maxsize, max_group_depth=sys.maxsize)
|
|
parts.append("".join(trace.format()))
|
|
# SQLAlchemy's exception text may abbreviate parameter collections.
|
|
seen = set()
|
|
pending = [exception]
|
|
while pending:
|
|
current = pending.pop()
|
|
if id(current) in seen:
|
|
continue
|
|
seen.add(id(current))
|
|
for name in ("statement", "params"):
|
|
value = getattr(current, name, None)
|
|
if value is not None:
|
|
parts.append(f"{type(current).__name__}.{name}:\n"
|
|
+ (value if isinstance(value, str) else repr(value)))
|
|
linked = current.__cause__ or (
|
|
None if current.__suppress_context__ else current.__context__)
|
|
if linked is not None:
|
|
pending.append(linked)
|
|
if isinstance(current, BaseExceptionGroup):
|
|
pending.extend(reversed(current.exceptions))
|
|
return "\n\n".join(parts)
|
|
|
|
|
|
class ErrorDialog(tk.Toplevel):
|
|
"""Resizable, selectable read-only report, also usable on small terminals."""
|
|
|
|
def __init__(self, parent, title, report):
|
|
super().__init__(parent)
|
|
self.withdraw()
|
|
self.report = report
|
|
self.title(versioned_title(title, __name__))
|
|
self.resizable(True, True)
|
|
theme = theme_section("error_dialog")
|
|
width = min(int(theme.get("width", 900)), max(200, self.winfo_screenwidth() - 24))
|
|
height = min(int(theme.get("height", 620)), max(200, self.winfo_screenheight() - 80))
|
|
self.geometry(f"{width}x{height}+0+0")
|
|
self.minsize(min(width, 420), min(height, 260))
|
|
if parent.winfo_viewable():
|
|
self.transient(parent.winfo_toplevel())
|
|
self.grid_columnconfigure(0, weight=1)
|
|
self.grid_rowconfigure(0, weight=1)
|
|
|
|
frame = ttk.Frame(self, padding=6)
|
|
frame.grid(row=0, column=0, sticky="nsew")
|
|
frame.grid_rowconfigure(0, weight=1)
|
|
frame.grid_columnconfigure(0, weight=1)
|
|
self.textbox = tk.Text(frame, wrap="none", width=1, height=1,
|
|
font=theme_font(theme, "font", ("Consolas", 10)),
|
|
background=theme.get("background", "#ffffff"),
|
|
foreground=theme.get("foreground", "#202020"), exportselection=False)
|
|
self.textbox.grid(row=0, column=0, sticky="nsew")
|
|
self.vertical = ttk.Scrollbar(frame, orient="vertical", command=self.textbox.yview)
|
|
self.vertical.grid(row=0, column=1, sticky="ns")
|
|
self.horizontal = ttk.Scrollbar(frame, orient="horizontal", command=self.textbox.xview)
|
|
self.horizontal.grid(row=1, column=0, sticky="ew")
|
|
self.textbox.configure(yscrollcommand=self.vertical.set, xscrollcommand=self.horizontal.set)
|
|
self.textbox.insert("1.0", report)
|
|
self.textbox.configure(state="disabled")
|
|
self.textbox.bind("<Control-a>", self.select_all)
|
|
self.textbox.bind("<Control-c>", self.copy_selection)
|
|
self.status = tk.StringVar(self, "")
|
|
ttk.Label(self, textvariable=self.status, wraplength=max(150, width - 20)).grid(
|
|
row=1, column=0, sticky="ew", padx=6)
|
|
buttons = ttk.Frame(self, padding=6)
|
|
buttons.grid(row=2, column=0, sticky="ew")
|
|
self.buttons = []
|
|
for i, (key, callback) in enumerate((("copy", self.copy_all),
|
|
("save", self.save_report), ("close", self.destroy))):
|
|
button = ttk.Button(buttons, text=text("errors." + key), command=callback)
|
|
row, col = (i, 0) if width < 480 else (0, i)
|
|
button.grid(row=row, column=col, sticky="ew", padx=2, pady=2)
|
|
buttons.grid_columnconfigure(col, weight=1)
|
|
self.buttons.append(button)
|
|
self.bind("<Escape>", lambda _: self.destroy())
|
|
self.deiconify()
|
|
|
|
def select_all(self, event=None):
|
|
self.textbox.tag_add("sel", "1.0", "end-1c")
|
|
return "break"
|
|
|
|
def _copy(self, value):
|
|
try:
|
|
self.clipboard_clear()
|
|
self.clipboard_append(value)
|
|
self.status.set(text("errors.copied"))
|
|
except tk.TclError as exc:
|
|
self.status.set(text("errors.copy_failed").format(error=exc))
|
|
|
|
def copy_selection(self, event=None):
|
|
if self.textbox.tag_ranges("sel"):
|
|
self._copy(self.textbox.get("sel.first", "sel.last"))
|
|
return "break"
|
|
|
|
def copy_all(self):
|
|
self._copy(self.report)
|
|
|
|
def save_report(self):
|
|
"""Save UTF-8 without truncation; a failed save leaves the report open."""
|
|
path = filedialog.asksaveasfilename(parent=self, title=text("errors.save"),
|
|
defaultextension=".txt", initialfile=f"warehouse_error_{datetime.now():%Y%m%d_%H%M%S}.txt",
|
|
filetypes=[(text("errors.text_file"), "*.txt"), (text("errors.all_files"), "*.*")])
|
|
if not path:
|
|
return
|
|
try:
|
|
Path(path).write_text(self.report, encoding="utf-8")
|
|
except OSError as exc:
|
|
self.status.set(text("errors.save_failed").format(error=exc))
|
|
else:
|
|
self.status.set(text("errors.saved").format(path=path))
|
|
|
|
|
|
def showerror(title=None, message=None, *, parent=None, exception=None, context="", **options):
|
|
"""Messagebox-compatible modal error; confirmations are never rerouted here.
|
|
|
|
Async callbacks must pass ``exception`` explicitly to retain their traceback.
|
|
Within an except block the active exception is captured automatically.
|
|
"""
|
|
if exception is None:
|
|
exception = message if isinstance(message, BaseException) else sys.exc_info()[1]
|
|
title = title or text("errors.title")
|
|
if not context and parent is not None:
|
|
context = parent.winfo_toplevel().title()
|
|
report = build_error_report(title, "" if message is None else message, exception, context=context)
|
|
if options.get("detail"):
|
|
report += "\n\n" + str(options["detail"])
|
|
owned_root = None
|
|
parent = parent if parent is not None else tk._default_root
|
|
if parent is None:
|
|
owned_root = parent = tk.Tk()
|
|
parent.withdraw()
|
|
previous_grab = parent.grab_current()
|
|
previous_grab_status = previous_grab.grab_status() if previous_grab else None
|
|
previous_focus = parent.focus_get()
|
|
dialog = None
|
|
try:
|
|
dialog = ErrorDialog(parent, title, report)
|
|
dialog.wait_visibility()
|
|
dialog.grab_set()
|
|
dialog.textbox.focus_set()
|
|
dialog.wait_window()
|
|
finally:
|
|
if dialog is not None and dialog.winfo_exists():
|
|
dialog.destroy()
|
|
try:
|
|
if previous_grab is not None and previous_grab.winfo_exists():
|
|
if previous_grab_status == "global":
|
|
previous_grab.grab_set_global()
|
|
else:
|
|
previous_grab.grab_set()
|
|
if previous_focus is not None and previous_focus.winfo_exists():
|
|
previous_focus.focus_set()
|
|
except tk.TclError:
|
|
pass
|
|
if owned_root is not None:
|
|
owned_root.destroy()
|
|
return "ok"
|