diff --git a/docs/changelog.md b/docs/changelog.md index 9683526..01dd754 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -7,7 +7,16 @@ ### 2.1 (In Development) + * [general] Improve usability and accessibility across the Scan Wizard, Advanced Mode, Region Editor, Scan Window, and About dialog: + * Add keyboard navigation to the Scan Wizard drop zone (`Tab`, `Enter`, `Space`) and video list (`Up`, `Down`, `Shift+Up`, `Shift+Down`, `Home`, `End`) + * Add `Alt+Left` and `Alt+Right` step shortcuts, `F1` help shortcut, `Escape` dialog dismissal, and keyboard-focusable tooltips + * Increase text and border contrast, use native `ttk` controls and DVR-Scan brand colors, align form labels, add output-mode descriptions, and show guidance when zero motion events are found + * Add Region Editor toolbar controls to add and delete shapes, show the current frame number, show checkmarks in the `View` menu, and add high-contrast handle borders * [bugfix] Switch open top-level menus on hover and support `Alt`/`F10` shortcuts in the Windows menu bar [#289](https://github.com/Breakthrough/DVR-Scan/issues/289) + * [bugfix] Show a message dialog in Advanced Mode when starting a scan with no input videos or an invalid start/end time range + * [bugfix] Fix a `Ctrl+N` crash in the Region Editor when the pointer is outside the canvas, and show an error dialog when a region file fails to load + * [bugfix] Fix the scan progress bar stopping below 100% when `frame-skip` is set, and clamp remaining time at `00:00` on variable framerate inputs + * [bugfix] Keep sort menu checkmarks in sync between the Scan Wizard toolbar and `File -> Sort`, clear the clipboard before copying text, use `https://` for help links, and parent child dialogs to their window ### 2.0 (2026-11-08) diff --git a/dvr_scan/app/__main__.py b/dvr_scan/app/__main__.py index 8986cc2..df747fb 100644 --- a/dvr_scan/app/__main__.py +++ b/dvr_scan/app/__main__.py @@ -129,7 +129,6 @@ def get_cli_parser(): "--debug", action="store_true", help=argparse.SUPPRESS, - default=False, ) parser.add_argument( diff --git a/dvr_scan/app/about_window.py b/dvr_scan/app/about_window.py index 61a98db..9075288 100644 --- a/dvr_scan/app/about_window.py +++ b/dvr_scan/app/about_window.py @@ -28,6 +28,27 @@ f"DVR-Scan {dvr_scan.__version__}\n\n" "Copyright \N{COPYRIGHT SIGN} Brandon Castellano.\nAll rights reserved." ) +WEBSITE_URL = "https://www.dvr-scan.com/" +ISSUES_URL = "https://github.com/Breakthrough/DVR-Scan/issues" + + +def _allow_tab_traversal(text_widget: tk.Text): + """Let Tab / Shift+Tab move focus out of a read-only Text widget instead of trapping focus.""" + + def focus_next(event): + target = event.widget.tk_focusNext() + if target is not None: + target.focus_set() + return "break" + + def focus_prev(event): + target = event.widget.tk_focusPrev() + if target is not None: + target.focus_set() + return "break" + + text_widget.bind("", focus_next) + text_widget.bind("", focus_prev) def show_about(root: tk.Misc): @@ -42,60 +63,80 @@ def show_about(root: tk.Misc): # Tk keeps no reference of its own, so this local must outlive the window (it does: the # function blocks in `wait_window` below). about_image_tk = PIL.ImageTk.PhotoImage(about_image) - canvas = tk.Canvas(window, width=about_image.width, height=about_image.height) - canvas.grid() + bg = ttk.Style().lookup("TFrame", "background") or "SystemButtonFace" + canvas = tk.Canvas( + window, + width=about_image.width, + height=about_image.height, + background=bg, + highlightthickness=0, + ) + canvas.grid(row=0, column=0, padx=8, pady=(8, 0)) canvas.create_image(0, 0, anchor=tk.NW, image=about_image_tk) - ttk.Separator(window, orient=tk.HORIZONTAL).grid(row=1, sticky="ew", padx=16.0) - ttk.Label(window, text=COPYRIGHT).grid(row=2, sticky="nw", padx=24.0, pady=24.0) - - # TODO: These should be buttons not labels. - website_link = ttk.Label( - window, text="www.dvr-scan.com", cursor="hand2", foreground="medium blue" + ttk.Separator(window, orient=tk.HORIZONTAL).grid(row=1, column=0, sticky="ew", padx=16.0) + ttk.Label(window, text=COPYRIGHT).grid( + row=2, column=0, sticky="nw", padx=24.0, pady=(16.0, 8.0) ) - website_link.grid(row=2, sticky="ne", padx=24.0, pady=24.0) - website_link.bind("", lambda _: webbrowser.open_new_tab("www.dvr-scan.com")) + + links_frame = ttk.Frame(window) + links_frame.grid(row=3, column=0, sticky="new", padx=24.0, pady=(0.0, 16.0)) + ttk.Button( + links_frame, + text="Website", + command=lambda: webbrowser.open_new_tab(WEBSITE_URL), + ).grid(row=0, column=0, padx=(0, 8)) + ttk.Button( + links_frame, + text="Report Issue", + command=lambda: webbrowser.open_new_tab(ISSUES_URL), + ).grid(row=0, column=1) version_info = get_system_version_info() about_tabs = ttk.Notebook(window) - version_tab = ttk.Frame(about_tabs) + version_tab = ttk.Frame(about_tabs, padding=8) version_area = tkinter.scrolledtext.ScrolledText(version_tab, wrap=tk.NONE, width=40, height=1) - # TODO: See if we can add another button that will copy debug logs. version_area.insert(tk.INSERT, version_info) - version_area.grid(sticky="nsew") + version_area.grid(row=0, column=0, sticky="nsew") version_area.config(state="disabled") + _allow_tab_traversal(version_area) version_tab.columnconfigure(0, weight=1) version_tab.rowconfigure(0, weight=1) - tk.Button( + + copy_reset_id = None + + def copy_version_info(): + nonlocal copy_reset_id + root.clipboard_clear() + root.clipboard_append(version_info) + root.update_idletasks() + copy_button.configure(text="Copied!") + copy_reset_id = window.after(1500, lambda: copy_button.configure(text="Copy to Clipboard")) + + copy_button = ttk.Button( version_tab, text="Copy to Clipboard", - command=lambda: root.clipboard_append(version_info), - ).grid(row=1, column=0) + command=copy_version_info, + ) + copy_button.grid(row=1, column=0, sticky="e", pady=(8, 0)) - license_tab = ttk.Frame(about_tabs) - scrollbar = tk.Scrollbar(license_tab, orient=tk.HORIZONTAL) + license_tab = ttk.Frame(about_tabs, padding=8) + scrollbar = ttk.Scrollbar(license_tab, orient=tk.HORIZONTAL) license_area = tkinter.scrolledtext.ScrolledText( license_tab, wrap=tk.NONE, width=40, xscrollcommand=scrollbar.set, height=1 ) license_area.insert(tk.INSERT, dvr_scan.get_license_info()) - license_area.grid(sticky="nsew") + license_area.grid(row=0, column=0, sticky="nsew") scrollbar.config(command=license_area.xview) - scrollbar.grid(row=1, sticky="swe") + scrollbar.grid(row=1, column=0, sticky="swe") license_area.config(state="disabled") + _allow_tab_traversal(license_area) license_tab.columnconfigure(0, weight=1) license_tab.rowconfigure(0, weight=1) - # TODO: Add tab that has some useful links like submitting bug report, etc about_tabs.add(version_tab, text="Version Info") about_tabs.add(license_tab, text="License Info") - about_tabs.grid(row=0, column=1, rowspan=4, padx=(0.0, 16.0), pady=(16.0, 16.0), sticky="nsew") - window.update() - window.columnconfigure(0, minsize=about_image.width) - window.rowconfigure(0, minsize=about_image.height) - # minsize includes padding - window.columnconfigure(1, weight=1, minsize=100) - window.rowconfigure(3, weight=1) - window.minsize(width=window.winfo_reqwidth(), height=window.winfo_reqheight()) + about_tabs.grid(row=0, column=1, rowspan=4, padx=(8.0, 16.0), pady=(16.0, 8.0), sticky="nsew") # The region editor holds a grab on its root while launched from the Advanced Mode window; # hand the grab to this dialog and give it back on close. (Tkinter maps Tk's "none" @@ -103,20 +144,31 @@ def show_about(root: tk.Misc): restore_grab = root.grab_status() is not None root.grab_release() window.transient(root) - window.focus() - window.grab_set() def dismiss(): + if copy_reset_id is not None: + window.after_cancel(copy_reset_id) window.grab_release() window.destroy() if restore_grab: root.grab_set() root.focus() + close_button = ttk.Button(window, text="Close", command=dismiss) + close_button.grid(row=4, column=0, columnspan=2, sticky="e", padx=16.0, pady=(0.0, 16.0)) + + window.update_idletasks() + window.columnconfigure(0, minsize=about_image.width) + window.rowconfigure(0, minsize=about_image.height) + # minsize includes padding + window.columnconfigure(1, weight=1, minsize=100) + window.rowconfigure(3, weight=1) + window.minsize(width=window.winfo_reqwidth(), height=window.winfo_reqheight()) + window.protocol("WM_DELETE_WINDOW", dismiss) - window.attributes("-topmost", True) - window.bind("", lambda _: window.destroy()) - window.bind("", lambda _: dismiss()) + window.bind("", lambda _: dismiss()) window.deiconify() + close_button.focus_set() + window.grab_set() window.wait_window() diff --git a/dvr_scan/app/application.py b/dvr_scan/app/application.py index 6af3a2e..782cff0 100644 --- a/dvr_scan/app/application.py +++ b/dvr_scan/app/application.py @@ -30,7 +30,9 @@ PADDING, SETTING_INPUT_WIDTH, MenuBar, + Tooltip, add_startup_mode_menu, + blend_color, fill_help_menu, fit_window_to_screen, hide_modal, @@ -57,7 +59,12 @@ to_photo, ) from dvr_scan.app.widgets import ColorPicker, Spinbox, TimecodeEntry -from dvr_scan.app.wizard import ScanWizard +from dvr_scan.app.wizard import ( + FFMPEG_MISSING_SUFFIX, + FFMPEG_OUTPUT_MODES, + RECOMMENDED_SUFFIX, + ScanWizard, +) from dvr_scan.config import ( CHOICE_MAP, CONFIG_MAP, @@ -99,6 +106,12 @@ # TODO: Allow this to be sorted by columns. # TODO: Should we have a default sort method when bulk adding videos? class InputArea: + _remove_button: ty.Optional[ttk.Button] = None + _up_button: ty.Optional[ttk.Button] = None + _down_button: ty.Optional[ttk.Button] = None + _empty_hint: ty.Optional[tk.Label] = None + _region_editor_button: ty.Optional[ttk.Button] = None + def __init__(self, root: tk.Widget): self._root = root self._region_editor: ty.Optional[RegionEditor] = None @@ -108,7 +121,7 @@ def __init__(self, root: tk.Widget): self._region_editor_video: ty.Optional[str] = None self._region_editor_size: ty.Optional[ty.Tuple[int, int]] = None self._region_editor_start_time: ty.Optional[str] = None - root.rowconfigure(0, pad=PADDING, weight=1) + root.rowconfigure(0, pad=PADDING, weight=1, minsize=150) root.rowconfigure(1, pad=PADDING) root.rowconfigure(2, pad=PADDING) root.rowconfigure(3, pad=PADDING) @@ -119,16 +132,19 @@ def __init__(self, root: tk.Widget): root.columnconfigure(column, weight=1, uniform="controls") root.columnconfigure(6, weight=12, minsize=0) - frame = tk.Frame(root) + frame = ttk.Frame(root) frame.rowconfigure(0, weight=1) frame.columnconfigure(0, weight=1) - frame.columnconfigure(1, weight=1) configure_thumbnail_rows() + # Default `Treeview` height is 10 rows, which at 58px per filmstrip row requests ~580px + # for the table alone (pushing the window past 1080p displays). 4 rows (~232px) fits + # comfortably on laptop screens while expanding smoothly when the window is resized. self._videos = ttk.Treeview( frame, columns=("duration", "framerate", "resolution", "date", "path"), style=THUMBNAIL_STYLE, + height=4, ) # Each row gets a filmstrip preview (frames sampled across the video) decoded off # the UI thread; a shared placeholder is shown until the real strip is ready. @@ -138,19 +154,36 @@ def __init__(self, root: tk.Widget): scroll_horizontal = ttk.Scrollbar(frame, orient=tk.HORIZONTAL, command=self._videos.xview) scroll_vertical = ttk.Scrollbar(frame, orient=tk.VERTICAL, command=self._videos.yview) - scroll_horizontal.grid(row=1, column=0, columnspan=6, sticky="NEW") - scroll_vertical.grid(row=0, column=6, rowspan=6, sticky="NSW") + scroll_horizontal.grid(row=1, column=0, sticky=tk.EW) + scroll_vertical.grid(row=0, column=1, sticky=tk.NS) self._videos.configure( xscrollcommand=scroll_horizontal.set, yscrollcommand=scroll_vertical.set ) self._videos.grid(row=0, column=0, sticky=tk.NSEW) - frame.grid(row=0, column=0, rowspan=2, columnspan=6, sticky=tk.NSEW) + frame.grid(row=0, column=0, rowspan=2, columnspan=7, sticky=tk.NSEW) + + style = ttk.Style() + tree_bg = ( + style.lookup("Treeview", "fieldbackground") + or style.lookup("Treeview", "background") + or "#ffffff" + ) + tree_fg = style.lookup("Treeview", "foreground") or "#000000" + hint_fg = blend_color(self._videos, tree_fg, tree_bg, 0.65) + self._empty_hint = tk.Label( + self._videos, + text="No videos added. Click Add or drag and drop video files here.", + background=tree_bg, + foreground=hint_fg, + cursor="hand2", + ) + self._empty_hint.bind("", lambda _: self.add_video()) self._videos.heading("#0", text="Name", command=lambda: self._sort_column("#0", False)) # The #0 cell holds the filmstrip preview followed by the name; size it to fit both. self._videos.column( - "#0", width=FILMSTRIP_WIDTH + 160, minwidth=FILMSTRIP_WIDTH + 40, stretch=False + "#0", width=FILMSTRIP_WIDTH + 140, minwidth=FILMSTRIP_WIDTH + 40, stretch=False ) self._videos.heading( "duration", text="Duration", command=lambda: self._sort_column("duration", False) @@ -163,13 +196,13 @@ def __init__(self, root: tk.Widget): self._videos.heading( "resolution", text="Resolution", command=lambda: self._sort_column("resolution", False) ) - self._videos.column("resolution", width=80, minwidth=80, stretch=False) + self._videos.column("resolution", width=85, minwidth=80, stretch=False) self._videos.heading("date", text="Date", command=lambda: self._sort_column("date", False)) self._videos.column("date", width=140, minwidth=80, stretch=False) self._videos.heading("path", text="Path", command=lambda: self._sort_column("path", False)) - self._videos.column("path", width=80, minwidth=80, stretch=False) + self._videos.column("path", width=140, minwidth=80, stretch=True) - self._videos.grid(row=0, column=0, columnspan=6, sticky=tk.NSEW) + self._videos.bind("<>", lambda _: self._refresh_remove_state()) # The Treeview takes keyboard focus when clicked, so these widget-level bindings only # fire while the list is focused and never interfere with text entries elsewhere. for sequence in ("<>", "", ""): @@ -177,23 +210,28 @@ def __init__(self, root: tk.Widget): for sequence in ("", ""): self._videos.bind(sequence, self._on_remove_key) - ttk.Button(root, text="Add", command=self.add_video).grid( - row=2, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING - ) + add_btn = ttk.Button(root, text="Add", command=self.add_video) + add_btn.grid(row=2, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING) + Tooltip(add_btn, f"Add input video files ({ACCELERATOR_KEY}+O)") self._remove_button = ttk.Button( root, text="Remove", state=tk.DISABLED, command=self.remove_selected ) self._remove_button.grid(row=2, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING) - ttk.Button( + Tooltip(self._remove_button, "Remove selected videos (Del)") + self._up_button = ttk.Button( root, text="Move Up", + state=tk.DISABLED, command=self._on_move_up, - ).grid(row=2, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING) - ttk.Button( + ) + self._up_button.grid(row=2, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING) + self._down_button = ttk.Button( root, text="Move Down", + state=tk.DISABLED, command=self._on_move_down, - ).grid(row=2, column=3, sticky=EXPAND_HORIZONTAL, padx=PADDING) + ) + self._down_button.grid(row=2, column=3, sticky=EXPAND_HORIZONTAL, padx=PADDING) self._set_time = tk.BooleanVar(root, value=False) self._set_region = tk.BooleanVar(root, value=False) @@ -209,36 +247,45 @@ def __init__(self, root: tk.Widget): command=self._on_set_time, ) self._set_time_button.grid(row=3, column=0, padx=PADDING, sticky=tk.W) + Tooltip(self._set_time_button, "Scan only a specific time range within the input video.") # The start/end time controls are shown only while Set Time is checked. - self._start_time_label = tk.Label(root, text="Start Time") + self._start_time_label = ttk.Label(root, text="Start Time") self._start_time = TimecodeEntry(root, value="00:00:00.000") + Tooltip(self._start_time_label, "Position in the video to start the scan (HH:MM:SS.mmm).") - self._end_time_label = tk.Label(root, text="End Time") + self._end_time_label = ttk.Label(root, text="End Time") self._end_time = TimecodeEntry(root, "00:00:00.000") + Tooltip( + self._end_time_label, + "Position in the video to end the scan (00:00:00.000 = end of video).", + ) - ttk.Checkbutton( + set_regions_check = ttk.Checkbutton( root, text="Set Regions", variable=self._set_region, onvalue=True, offvalue=False, command=self._on_use_regions, - ).grid(row=4, column=0, padx=PADDING, sticky=tk.W) + ) + set_regions_check.grid(row=4, column=0, padx=PADDING, sticky=tk.W) + Tooltip(set_regions_check, "Limit motion detection to specific polygon regions.") self._region_editor_button = ttk.Button( - root, text="Region Editor", state=tk.DISABLED, command=self._on_edit_regions + root, text="Region Editor...", state=tk.DISABLED, command=self._on_edit_regions ) self._current_region = tk.StringVar(value=NO_REGIONS_SPECIFIED_TEXT) - self._current_region_label = tk.Entry( - root, width=PATH_INPUT_WIDTH, state=tk.DISABLED, textvariable=self._current_region + self._current_region_label = ttk.Entry( + root, width=PATH_INPUT_WIDTH, state="readonly", textvariable=self._current_region ) self._region_editor_button.grid(row=4, column=1, padx=PADDING, sticky=EXPAND_HORIZONTAL) self._current_region_label.grid( - row=4, column=3, sticky=EXPAND_HORIZONTAL, padx=PADDING, columnspan=2 + row=4, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, columnspan=2 ) # Update internal state self._on_set_time() self._on_use_regions() + self._refresh_remove_state() @property def videos(self) -> ty.List[str]: @@ -270,15 +317,25 @@ def update(self, settings: ScanSettings) -> ty.Optional[ScanSettings]: def sort_by(self, col: str, descending: bool): """Reorder the video list by treeview column `col` ("#0" is the name). Sorting is - case-insensitive; date strings (YYYY-MM-DD ...) sort chronologically as text.""" + case-insensitive; framerates sort numerically; date strings sort chronologically.""" children = self._videos.get_children("") if col == "#0": items = [(self._videos.item(k, "text").casefold(), k) for k in children] + elif col == "framerate": + + def _fps_key(item_id: str) -> float: + try: + return float(self._videos.set(item_id, col)) + except ValueError: + return -1.0 + + items = [(_fps_key(k), k) for k in children] else: items = [(str(self._videos.set(k, col)).casefold(), k) for k in children] - items.sort(reverse=descending) + items.sort(key=lambda pair: pair[0], reverse=descending) for index, (_val, k) in enumerate(items): self._videos.move(k, "", index) + self._refresh_remove_state() def _sort_column(self, col, reverse): # Header-click sort: apply, then flip direction for the next click on this column. @@ -288,10 +345,21 @@ def _sort_column(self, col, reverse): def add_video(self, path: str = "", parent: ty.Optional[tk.Widget] = None): """Add a video to the list by path, or open a file dialog if no path is given. Called from the Add button, drag-and-drop, and the Scan Wizard.""" - paths = [path] if path else ask_video_paths(parent) + dialog_parent = ( + parent + if parent is not None + else ( + self._root.winfo_toplevel() + if getattr(self, "_root", None) is not None + and hasattr(self._root, "winfo_toplevel") + else None + ) + ) + paths = [path] if path else ask_video_paths(dialog_parent) if not paths: return - for info in probe_videos(paths, parent): + added_first = None + for info in probe_videos(paths, dialog_parent): item = self._videos.insert( "", tk.END, @@ -299,7 +367,11 @@ def add_video(self, path: str = "", parent: ty.Optional[tk.Widget] = None): image=self._placeholder, values=(info.duration, info.framerate, info.resolution, info.date, info.path), ) + if added_first is None: + added_first = item self._thumbnails.submit(item, lambda path=info.path: sample_video_frames(path)) + if added_first is not None and not self._videos.selection(): + self._videos.selection_set([added_first]) self._refresh_remove_state() def clear(self): @@ -311,16 +383,39 @@ def clear(self): self._refresh_remove_state() def _refresh_remove_state(self): - self._remove_button["state"] = tk.NORMAL if self._videos.get_children() else tk.DISABLED + children = list(self._videos.get_children()) + selected = list(self._videos.selection()) + indices = [idx for idx, iid in enumerate(children) if iid in selected] + if self._remove_button is not None: + self._remove_button["state"] = tk.NORMAL if indices else tk.DISABLED + if self._up_button is not None: + self._up_button["state"] = tk.NORMAL if (indices and indices[0] > 0) else tk.DISABLED + if self._down_button is not None: + can_down = bool(indices) and indices[-1] < len(children) - 1 + self._down_button["state"] = tk.NORMAL if can_down else tk.DISABLED + if self._empty_hint is not None: + if children: + self._empty_hint.place_forget() + else: + self._empty_hint.place(relx=0.5, rely=0.55, anchor=tk.CENTER) def select_all(self): """Select every video in the list.""" self._videos.selection_set(self._videos.get_children()) + self._refresh_remove_state() def remove_selected(self): """Remove the selected videos from the list.""" - for selection in self._videos.selection(): + children = list(self._videos.get_children()) + selected = list(self._videos.selection()) + if not selected: + return + lowest = min((children.index(iid) for iid in selected if iid in children), default=0) + for selection in selected: self._videos.delete(selection) + remaining = list(self._videos.get_children()) + if remaining: + self._videos.selection_set([remaining[min(lowest, len(remaining) - 1)]]) self._refresh_remove_state() def _on_select_all_key(self, _event=None): @@ -338,6 +433,7 @@ def _on_move_up(self): self._videos.move(selection, "", index - 1) else: break + self._refresh_remove_state() def _on_move_down(self): for selection in self._videos.selection()[::-1]: @@ -347,14 +443,15 @@ def _on_move_down(self): self._videos.move(next, "", index) else: break + self._refresh_remove_state() def _on_set_time(self): # TODO: When disabled, set start time 0 and end time duration of video. if self._set_time.get(): - self._start_time_label.grid(row=3, column=1, sticky=EXPAND_HORIZONTAL) + self._start_time_label.grid(row=3, column=1, padx=PADDING, sticky=tk.W) self._start_time.grid(row=3, column=2, padx=PADDING, sticky=EXPAND_HORIZONTAL) + self._end_time_label.grid(row=3, column=3, padx=PADDING, sticky=tk.W) self._end_time.grid(row=3, column=4, padx=PADDING, sticky=EXPAND_HORIZONTAL) - self._end_time_label.grid(row=3, column=3, sticky=EXPAND_HORIZONTAL) else: self._start_time_label.grid_remove() self._start_time.grid_remove() @@ -365,7 +462,7 @@ def _on_use_regions(self): if self._set_region.get(): self._region_editor_button["state"] = tk.NORMAL self._current_region_label.grid( - row=4, column=3, sticky=EXPAND_HORIZONTAL, padx=PADDING, columnspan=2 + row=4, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, columnspan=2 ) else: self._region_editor_button["state"] = tk.DISABLED @@ -428,6 +525,12 @@ def _reset_regions(self): def _on_edit_regions(self): videos = self.videos if not videos: + if hasattr(self._root, "winfo_toplevel"): + tkinter.messagebox.showinfo( + "No Videos Added", + "Add at least one video before opening the Region Editor.", + parent=self._root.winfo_toplevel(), + ) return video_path = videos[0] normalized_path = self._normalize_path(video_path) @@ -534,41 +637,43 @@ def __init__(self, root: tk.Widget): self._window.title("Input Settings") self._window.resizable(True, True) self._window.protocol("WM_DELETE_WINDOW", self._dismiss) + self._window.bind("", lambda _: self._dismiss()) self._window.rowconfigure(0, weight=1) - self._window.rowconfigure(1, weight=1) self._window.columnconfigure(0, weight=1) frame = ttk.LabelFrame(self._window, text="Video", padding=PADDING) - frame.grid(row=0, sticky=tk.NSEW, padx=PADDING, pady=PADDING) + frame.grid(row=0, column=0, sticky=tk.NSEW, padx=PADDING, pady=(PADDING, 0)) frame.rowconfigure(0, pad=PADDING, weight=1) frame.rowconfigure(1, pad=PADDING, weight=1) - frame.rowconfigure(2, pad=PADDING, weight=1) frame.columnconfigure(0, pad=PADDING, weight=1) frame.columnconfigure(1, pad=PADDING, weight=1) frame.columnconfigure(2, pad=PADDING, weight=2) frame.columnconfigure(3, pad=PADDING, weight=1) frame.columnconfigure(4, pad=PADDING, weight=1) - frame.columnconfigure(5, pad=PADDING, weight=12, minsize=0) + frame.columnconfigure(5, pad=PADDING, weight=4, minsize=0) - tk.Button(self._window, text="Close", command=self._dismiss).grid( - row=2, column=0, sticky=tk.E, padx=PADDING, pady=PADDING + input_mode_label = ttk.Label(frame, text="Input Mode") + input_mode_label.grid(row=0, column=0, sticky=tk.W, padx=PADDING, pady=PADDING) + Tooltip(input_mode_label, "Video decoding backend (pyav is recommended for accuracy).") + self._input_mode = tk.StringVar() + self._input_mode_combo = ttk.Combobox( + frame, textvariable=self._input_mode, width=SETTING_INPUT_WIDTH + ) + self._input_mode_combo.state(["readonly"]) + # Put the default PyAV backend first when available, followed by OpenCV and others. + preferred = [b for b in ("pyav", "opencv") if b in AVAILABLE_BACKENDS] + self._input_mode_combo["values"] = preferred + [ + backend for backend in AVAILABLE_BACKENDS if backend not in preferred + ] + self._input_mode_combo.grid( + row=0, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING ) - tk.Label(frame, text="Frame Skip").grid( - row=2, column=3, padx=PADDING, sticky=tk.N + EXPAND_HORIZONTAL, pady=PADDING - ) - self._frame_skip = Spinbox( - frame, - value=str(CONFIG_MAP["frame-skip"]), - from_=0.0, - to=1000.0, - increment=1.0, - ) - self._frame_skip.grid( - row=2, column=4, padx=PADDING, sticky=tk.N + EXPAND_HORIZONTAL, pady=PADDING - ) - tk.Label(frame, text="Downscale Factor").grid( - row=0, column=3, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING + downscale_label = ttk.Label(frame, text="Downscale Factor") + downscale_label.grid(row=0, column=3, sticky=tk.W, padx=PADDING, pady=PADDING) + Tooltip( + downscale_label, + "Integer factor to shrink frames during analysis for faster scanning (0 or 1 = off).", ) self._downscale_factor = Spinbox( frame, @@ -581,19 +686,29 @@ def __init__(self, root: tk.Widget): self._downscale_factor.grid( row=0, column=4, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING ) - tk.Label(frame, text="Input Mode").grid(row=0, column=0, sticky=EXPAND_HORIZONTAL) - self._input_mode = tk.StringVar() - combo = ttk.Combobox(frame, textvariable=self._input_mode, width=SETTING_INPUT_WIDTH) - combo.state(["readonly"]) - # Make sure OpenCV is always at the top. - combo["values"] = ["opencv"] + [ - backend for backend in AVAILABLE_BACKENDS if backend != "opencv" - ] - combo.grid(row=0, column=1, sticky=EXPAND_HORIZONTAL) + + frame_skip_label = ttk.Label(frame, text="Frame Skip") + frame_skip_label.grid(row=1, column=3, sticky=tk.W, padx=PADDING, pady=PADDING) + Tooltip( + frame_skip_label, + "Number of frames to skip between analyzed frames for faster scanning (0 = none).", + ) + self._frame_skip = Spinbox( + frame, + value=str(CONFIG_MAP["frame-skip"]), + from_=0.0, + to=1000.0, + increment=1.0, + ) + self._frame_skip.grid(row=1, column=4, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING) + + ttk.Button(self._window, text="Close", command=self._dismiss).grid( + row=1, column=0, sticky=tk.E, padx=PADDING, pady=PADDING + ) def show(self): logger.debug("showing input settings window") - show_modal(self._window, self._root) + show_modal(self._window, self._root, initial_focus=self._input_mode_combo) def _dismiss(self): logger.debug("closing input settings window") @@ -621,12 +736,13 @@ def __init__(self, root: tk.Widget): self._window.title("Motion Settings") self._window.resizable(True, True) self._window.protocol("WM_DELETE_WINDOW", self._dismiss) + self._window.bind("", lambda _: self._dismiss()) self._window.rowconfigure(0, weight=1) self._window.rowconfigure(1, weight=1) self._window.columnconfigure(0, weight=1) frame = ttk.LabelFrame(self._window, text="Motion", padding=PADDING) - frame.grid(row=0, sticky=tk.NSEW, padx=PADDING, pady=PADDING) + frame.grid(row=0, sticky=tk.NSEW, padx=PADDING, pady=(PADDING, 0)) frame.rowconfigure(0, pad=2 * PADDING, weight=1) frame.rowconfigure(1, pad=2 * PADDING, weight=1) frame.rowconfigure(2, pad=2 * PADDING, weight=1) @@ -639,23 +755,33 @@ def __init__(self, root: tk.Widget): frame.columnconfigure(5, pad=PADDING, weight=1) frame.columnconfigure(6, pad=PADDING, weight=12, minsize=0) - tk.Label(frame, text="Subtractor").grid(row=0, column=0, sticky=EXPAND_HORIZONTAL) + subtractor_label = ttk.Label(frame, text="Subtractor") + subtractor_label.grid(row=0, column=0, sticky=tk.W, padx=PADDING) + Tooltip( + subtractor_label, "Background subtraction algorithm (MOG2 is accurate; CNT is faster)." + ) self._bg_subtractor = tk.StringVar() - combo = ttk.Combobox(frame, textvariable=self._bg_subtractor, width=SETTING_INPUT_WIDTH) - combo.state(["readonly"]) + self._subtractor_combo = ttk.Combobox( + frame, textvariable=self._bg_subtractor, width=SETTING_INPUT_WIDTH + ) + self._subtractor_combo.state(["readonly"]) # CNT needs the contrib OpenCV build; it can be missing from pip installs where the # regular opencv-python package was installed over opencv-contrib-python. subtractors = ["MOG2"] + (["CNT"] if SubtractorCNT.is_available() else []) if SubtractorCudaMOG2.is_available(): - combo["values"] = tuple(["MOG2_CUDA"] + subtractors) + self._subtractor_combo["values"] = tuple(["MOG2_CUDA"] + subtractors) self._bg_subtractor.set("MOG2_CUDA") else: - combo["values"] = tuple(subtractors) + self._subtractor_combo["values"] = tuple(subtractors) self._bg_subtractor.set("MOG2") - combo.grid(row=0, column=1, sticky=EXPAND_HORIZONTAL) + self._subtractor_combo.grid(row=0, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING) - tk.Label(frame, text="Kernel Size").grid(row=1, column=0, sticky=EXPAND_HORIZONTAL) + kernel_label = ttk.Label(frame, text="Kernel Size") + kernel_label.grid(row=1, column=0, sticky=tk.W, padx=PADDING) + Tooltip( + kernel_label, "Noise reduction filter size in pixels (Auto scales with resolution)." + ) self._kernel_size_combobox = ttk.Combobox( frame, width=SETTING_INPUT_WIDTH, state="readonly" @@ -663,10 +789,14 @@ def __init__(self, root: tk.Widget): self._kernel_size_combobox["values"] = tuple( {0: "Off", -1: "Auto"}.get(size, f"{size}x{size}") for size in KERNEL_SIZES ) - self._kernel_size_combobox.grid(row=1, column=1, sticky=EXPAND_HORIZONTAL) + self._kernel_size_combobox.grid(row=1, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING) self._kernel_size_combobox.current(1) - tk.Label(frame, text="Threshold").grid(row=2, column=0, sticky=EXPAND_HORIZONTAL) + threshold_label = ttk.Label(frame, text="Threshold") + threshold_label.grid(row=2, column=0, sticky=tk.W, padx=PADDING) + Tooltip( + threshold_label, "Minimum motion score to trigger an event (lower = more sensitive)." + ) self._threshold = Spinbox( frame, value=str(CONFIG_MAP["threshold"]), @@ -674,10 +804,12 @@ def __init__(self, root: tk.Widget): to=255.0, increment=0.01, ) - self._threshold.grid(row=2, column=1, sticky=EXPAND_HORIZONTAL) + self._threshold.grid(row=2, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING) # Events - tk.Label(frame, text="Min. Event Length").grid(row=0, column=3, sticky=EXPAND_HORIZONTAL) + min_len_label = ttk.Label(frame, text="Min. Event Length") + min_len_label.grid(row=0, column=3, sticky=tk.W, padx=PADDING) + Tooltip(min_len_label, "Duration of sustained motion required to trigger an event.") self._min_event_length = Spinbox( frame, value=str(CONFIG_MAP["min-event-length"]), @@ -686,9 +818,11 @@ def __init__(self, root: tk.Widget): increment=DURATION_INCREMENT, suffix="s", ) - self._min_event_length.grid(row=0, column=4, sticky=EXPAND_HORIZONTAL) + self._min_event_length.grid(row=0, column=4, sticky=EXPAND_HORIZONTAL, padx=PADDING) - tk.Label(frame, text="Time Pre-Event").grid(row=1, column=3, sticky=EXPAND_HORIZONTAL) + pre_label = ttk.Label(frame, text="Time Pre-Event") + pre_label.grid(row=1, column=3, sticky=tk.W, padx=PADDING) + Tooltip(pre_label, "Extra video time included before motion starts.") self._time_before_event = Spinbox( frame, value=str(CONFIG_MAP["time-before-event"]), @@ -697,9 +831,11 @@ def __init__(self, root: tk.Widget): increment=DURATION_INCREMENT, suffix="s", ) - self._time_before_event.grid(row=1, column=4, sticky=EXPAND_HORIZONTAL) + self._time_before_event.grid(row=1, column=4, sticky=EXPAND_HORIZONTAL, padx=PADDING) - tk.Label(frame, text="Time Post-Event").grid(row=2, column=3, sticky=EXPAND_HORIZONTAL) + post_label = ttk.Label(frame, text="Time Post-Event") + post_label.grid(row=2, column=3, sticky=tk.W, padx=PADDING) + Tooltip(post_label, "Extra video time included after motion ends.") self._time_post_event = Spinbox( frame, value=str(CONFIG_MAP["time-post-event"]), @@ -708,9 +844,14 @@ def __init__(self, root: tk.Widget): increment=DURATION_INCREMENT, suffix="s", ) - self._time_post_event.grid(row=2, column=4, sticky=EXPAND_HORIZONTAL) + self._time_post_event.grid(row=2, column=4, sticky=EXPAND_HORIZONTAL, padx=PADDING) - tk.Label(frame, text="Merge Window").grid(row=3, column=3, sticky=EXPAND_HORIZONTAL) + merge_label = ttk.Label(frame, text="Merge Window") + merge_label.grid(row=3, column=3, sticky=tk.W, padx=PADDING) + Tooltip( + merge_label, + "Merge consecutive events separated by less than this gap (Auto uses Time Post-Event).", + ) self._merge_window_auto = tk.BooleanVar(value=True) self._merge_window_value = Spinbox( frame, @@ -721,7 +862,7 @@ def __init__(self, root: tk.Widget): suffix="s", state=tk.DISABLED, ) - self._merge_window_value.grid(row=3, column=4, sticky=EXPAND_HORIZONTAL) + self._merge_window_value.grid(row=3, column=4, sticky=EXPAND_HORIZONTAL, padx=PADDING) ttk.Checkbutton( frame, text="Auto", @@ -729,10 +870,10 @@ def __init__(self, root: tk.Widget): onvalue=True, offvalue=False, command=self._on_auto_merge_window, - ).grid(row=3, column=5, sticky=EXPAND_HORIZONTAL) + ).grid(row=3, column=5, sticky=tk.W, padx=PADDING) frame = ttk.LabelFrame(self._window, text="Advanced", padding=PADDING) - frame.grid(row=1, sticky=tk.NSEW, padx=PADDING, pady=PADDING) + frame.grid(row=1, sticky=tk.NSEW, padx=PADDING, pady=(PADDING, 0)) for row in range(4): frame.rowconfigure(row, pad=PADDING, weight=1) frame.columnconfigure(0, weight=1) @@ -744,18 +885,20 @@ def __init__(self, root: tk.Widget): frame.columnconfigure(6, weight=12) self._mask_output = tk.BooleanVar(value=False) - ttk.Checkbutton( + mask_check = ttk.Checkbutton( frame, text="Save Motion Mask", variable=self._mask_output, onvalue=True, offvalue=False, - ).grid(row=3, column=0, columnspan=2, sticky=tk.W, padx=PADDING, pady=PADDING) + ) + mask_check.grid(row=3, column=0, columnspan=2, sticky=tk.W, padx=PADDING, pady=PADDING) + Tooltip(mask_check, "Write a grayscale motion-mask debug video alongside output.") self._learning_rate_auto = tk.BooleanVar(value=True) - tk.Label(frame, text="Learning Rate").grid( - row=0, column=3, padx=PADDING, sticky=EXPAND_HORIZONTAL - ) + lr_label = ttk.Label(frame, text="Learning Rate") + lr_label.grid(row=0, column=3, padx=PADDING, sticky=tk.W, pady=PADDING) + Tooltip(lr_label, "How quickly the background model adapts to scene changes (0.0 to 1.0).") self._learning_rate_value = Spinbox( frame, value=0.5, @@ -774,10 +917,13 @@ def __init__(self, root: tk.Widget): onvalue=True, offvalue=False, command=self._on_auto_learning_rate, - ).grid(row=0, column=5, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING) + ).grid(row=0, column=5, padx=PADDING, sticky=tk.W, pady=PADDING) - tk.Label(frame, text="Max Threshold").grid( - row=0, column=0, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING + max_thresh_label = ttk.Label(frame, text="Max Threshold") + max_thresh_label.grid(row=0, column=0, padx=PADDING, sticky=tk.W, pady=PADDING) + Tooltip( + max_thresh_label, + "Ignore frames with motion score at or above this value (255 = disabled).", ) self._max_threshold = Spinbox( frame, @@ -790,9 +936,9 @@ def __init__(self, root: tk.Widget): row=0, column=1, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING ) - tk.Label(frame, text="Variance Threshold").grid( - row=1, column=3, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING - ) + var_label = ttk.Label(frame, text="Variance Threshold") + var_label.grid(row=1, column=3, padx=PADDING, sticky=tk.W, pady=PADDING) + Tooltip(var_label, "Pixel-to-model distance threshold for MOG2 (unused by CNT).") self._variance_threshold = Spinbox( frame, value=str(CONFIG_MAP["variance-threshold"]), @@ -804,8 +950,11 @@ def __init__(self, root: tk.Widget): row=1, column=4, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING ) - tk.Label(frame, text="Max Area").grid( - row=1, column=0, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING + max_area_label = ttk.Label(frame, text="Max Area") + max_area_label.grid(row=1, column=0, padx=PADDING, sticky=tk.W, pady=PADDING) + Tooltip( + max_area_label, + "Ignore motion whose bounding box exceeds this fraction of frame area (1.0 = off).", ) self._max_area = Spinbox( frame, @@ -816,8 +965,11 @@ def __init__(self, root: tk.Widget): ) self._max_area.grid(row=1, column=1, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING) - tk.Label(frame, text="Max Width").grid( - row=2, column=0, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING + max_width_label = ttk.Label(frame, text="Max Width") + max_width_label.grid(row=2, column=0, padx=PADDING, sticky=tk.W, pady=PADDING) + Tooltip( + max_width_label, + "Ignore motion whose bounding box exceeds this fraction of frame width (1.0 = off).", ) self._max_width = Spinbox( frame, @@ -828,8 +980,11 @@ def __init__(self, root: tk.Widget): ) self._max_width.grid(row=2, column=1, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING) - tk.Label(frame, text="Max Height").grid( - row=2, column=3, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING + max_height_label = ttk.Label(frame, text="Max Height") + max_height_label.grid(row=2, column=3, padx=PADDING, sticky=tk.W, pady=PADDING) + Tooltip( + max_height_label, + "Ignore motion whose bounding box exceeds this fraction of frame height (1.0 = off).", ) self._max_height = Spinbox( frame, @@ -840,7 +995,7 @@ def __init__(self, root: tk.Widget): ) self._max_height.grid(row=2, column=4, padx=PADDING, sticky=EXPAND_HORIZONTAL, pady=PADDING) - tk.Button(self._window, text="Close", command=self._dismiss).grid( + ttk.Button(self._window, text="Close", command=self._dismiss).grid( row=2, column=0, sticky=tk.E, padx=PADDING, pady=PADDING ) @@ -856,7 +1011,7 @@ def _on_auto_merge_window(self): def show(self): logger.debug("showing motion settings window") - show_modal(self._window, self._root) + show_modal(self._window, self._root, initial_focus=self._subtractor_combo) def _dismiss(self): logger.debug("closing motion settings window") @@ -949,10 +1104,21 @@ def __init__(self, root: tk.Widget): root.columnconfigure(2, pad=PADDING, weight=1) root.columnconfigure(3, pad=PADDING, weight=12) - tk.Label(root, text="Mode").grid( - row=0, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(0, PADDING) + ttk.Label(root, text="Mode").grid( + row=0, column=0, sticky=tk.W, padx=PADDING, pady=(0, PADDING) + ) + ffmpeg_available = is_ffmpeg_available() + mode_labels = tuple( + ( + label.removesuffix(RECOMMENDED_SUFFIX) + FFMPEG_MISSING_SUFFIX + if (not ffmpeg_available and mode in FFMPEG_OUTPUT_MODES) + else label + ) + for label, mode in OUTPUT_MODES + ) + self._output_mode_combo = ttk.Combobox( + root, width=28 if ffmpeg_available else 36, state="readonly" ) - self._output_mode_combo = ttk.Combobox(root, width=26, state="readonly") self._output_mode_combo.grid( row=0, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(0, PADDING) ) @@ -964,6 +1130,7 @@ def __init__(self, root: tk.Widget): root, text="Options...", command=self._show_options, width=SETTING_INPUT_WIDTH ) self._options_button.grid(row=0, column=2, sticky=EXPAND_HORIZONTAL, pady=(0, PADDING)) + Tooltip(self._options_button, "Configure codec, encoder arguments, and video overlays.") self._combine = tk.BooleanVar(root, value=False) self._combine_button = ttk.Checkbutton( @@ -974,22 +1141,27 @@ def __init__(self, root: tk.Widget): offvalue=False, ) self._combine_button.grid(row=0, column=3, sticky=tk.W, padx=PADDING) + Tooltip( + self._combine_button, + "Merge all detected motion events into a single compilation video.", + ) - self._output_mode_combo["values"] = tuple(label for label, _mode in OUTPUT_MODES) + self._output_mode_combo["values"] = mode_labels # Default to encoded MP4 output, unless ffmpeg is unavailable on this system. - self._output_mode = OutputMode.ENCODE if is_ffmpeg_available() else OutputMode.OPENCV + self._output_mode = OutputMode.ENCODE if ffmpeg_available else OutputMode.OPENCV self._output_dir_str = "" self._output_dir_label = tk.StringVar(root, value="Ask Me") - tk.Label(root, text="Directory").grid( + ttk.Label(root, text="Directory").grid( row=1, column=0, - sticky=EXPAND_HORIZONTAL, + sticky=tk.W, + padx=PADDING, pady=(PADDING, 0), ) ttk.Entry( - root, width=PATH_INPUT_WIDTH, state=tk.DISABLED, textvariable=self._output_dir_label + root, width=PATH_INPUT_WIDTH, state="readonly", textvariable=self._output_dir_label ).grid( row=1, column=1, @@ -1021,6 +1193,7 @@ def clear_output_directory(): self._options_window.title("Output Options") self._options_window.resizable(True, True) self._options_window.protocol("WM_DELETE_WINDOW", self._dismiss_options) + self._options_window.bind("", lambda _: self._dismiss_options()) self._options_window.rowconfigure(0, weight=1) self._options_window.rowconfigure(1, weight=1) self._options_window.columnconfigure(0, weight=1) @@ -1033,10 +1206,8 @@ def clear_output_directory(): self._ffmpeg_options.columnconfigure(1, weight=8) self._ffmpeg_options.columnconfigure(2, weight=1) - self._ffmpeg_input_label = tk.Label(self._ffmpeg_options, text="ffmpeg\nInput Args") - self._ffmpeg_input_label.grid( - row=0, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING - ) + self._ffmpeg_input_label = ttk.Label(self._ffmpeg_options, text="ffmpeg Input Args") + self._ffmpeg_input_label.grid(row=0, column=0, sticky=tk.W, padx=PADDING, pady=PADDING) self._ffmpeg_input_args = tk.StringVar(value=CONFIG_MAP["ffmpeg-input-args"]) self._ffmpeg_input_entry = ttk.Entry( self._ffmpeg_options, @@ -1047,10 +1218,8 @@ def clear_output_directory(): row=0, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING ) - self._ffmpeg_output_label = tk.Label(self._ffmpeg_options, text="ffmpeg\nOutput Args") - self._ffmpeg_output_label.grid( - row=1, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING - ) + self._ffmpeg_output_label = ttk.Label(self._ffmpeg_options, text="ffmpeg Output Args") + self._ffmpeg_output_label.grid(row=1, column=0, sticky=tk.W, padx=PADDING, pady=PADDING) self._ffmpeg_output_args = tk.StringVar(value=CONFIG_MAP["ffmpeg-output-args"]) self._ffmpeg_output_entry = ttk.Entry( self._ffmpeg_options, @@ -1061,7 +1230,7 @@ def clear_output_directory(): row=1, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING ) - tk.Button(self._options_window, text="Close", command=self._dismiss_options).grid( + ttk.Button(self._options_window, text="Close", command=self._dismiss_options).grid( row=2, column=0, sticky=tk.E, padx=PADDING, pady=PADDING ) @@ -1076,10 +1245,8 @@ def clear_output_directory(): self._opencv_options.columnconfigure(4, weight=1) self._opencv_options.columnconfigure(5, weight=12) - self._opencv_codec_label = tk.Label(self._opencv_options, text="Codec") - self._opencv_codec_label.grid( - row=0, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING - ) + self._opencv_codec_label = ttk.Label(self._opencv_options, text="Codec") + self._opencv_codec_label.grid(row=0, column=0, sticky=tk.W, padx=PADDING, pady=PADDING) self._opencv_codec = tk.StringVar(value=CONFIG_MAP["opencv-codec"]) self._opencv_codec_combo = ttk.Combobox( self._opencv_options, @@ -1091,10 +1258,8 @@ def clear_output_directory(): self._opencv_codec_combo.grid(row=0, column=1, sticky=tk.W, padx=PADDING, pady=PADDING) # Encoder args are shown in place of the codec row when the mode is ENCODE. - self._encode_args_label = tk.Label(self._opencv_options, text="Encoder\nArgs") - self._encode_args_label.grid( - row=0, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING - ) + self._encode_args_label = ttk.Label(self._opencv_options, text="Encoder Args") + self._encode_args_label.grid(row=0, column=0, sticky=tk.W, padx=PADDING, pady=PADDING) self._encode_args = tk.StringVar(value=CONFIG_MAP["encode-args"]) self._encode_args_entry = ttk.Entry( self._opencv_options, @@ -1120,8 +1285,9 @@ def clear_output_directory(): command=self._on_text_overlay, ) self._timecode_checkbutton.grid( - row=1, column=0, columnspan=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) + row=1, column=0, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) ) + Tooltip(self._timecode_checkbutton, "Draw timestamp overlay in the top-left corner.") self._frame_metrics = tk.BooleanVar(value=False) self._frame_metrics_checkbutton = ttk.Checkbutton( @@ -1135,20 +1301,21 @@ def clear_output_directory(): self._frame_metrics_checkbutton.grid( row=1, column=1, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) ) + Tooltip(self._frame_metrics_checkbutton, "Draw per-frame motion score in the top-right.") - tk.Label(self._opencv_options, text="Text Color").grid( - row=2, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) + ttk.Label(self._opencv_options, text="Text Color").grid( + row=2, column=0, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) ) self._text_font_color = ColorPicker(self._opencv_options) self._text_font_color.grid(row=2, column=1, sticky=tk.NSEW, pady=(PADDING, 0), padx=PADDING) - tk.Label(self._opencv_options, text="Background").grid( - row=2, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) + ttk.Label(self._opencv_options, text="Background").grid( + row=2, column=2, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) ) self._text_bg_color = ColorPicker(self._opencv_options) self._text_bg_color.grid(row=2, column=3, sticky=tk.NSEW, pady=(PADDING, 0), padx=PADDING) - tk.Label(self._opencv_options, text="Font Scale").grid( - row=3, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) + ttk.Label(self._opencv_options, text="Font Scale").grid( + row=3, column=0, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) ) self._text_font_scale = Spinbox( self._opencv_options, @@ -1161,8 +1328,8 @@ def clear_output_directory(): row=3, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) ) - tk.Label(self._opencv_options, text="Font Weight").grid( - row=3, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) + ttk.Label(self._opencv_options, text="Font Weight").grid( + row=3, column=2, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) ) self._text_font_thickness = Spinbox( self._opencv_options, @@ -1176,8 +1343,8 @@ def clear_output_directory(): row=3, column=3, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) ) - tk.Label(self._opencv_options, text="Text Border").grid( - row=4, column=0, sticky=EXPAND_HORIZONTAL + ttk.Label(self._opencv_options, text="Text Border").grid( + row=4, column=0, sticky=tk.W, padx=PADDING, pady=PADDING ) # TODO: Constrain to be <= text margin self._text_border = Spinbox( @@ -1192,8 +1359,8 @@ def clear_output_directory(): row=4, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING ) - tk.Label(self._opencv_options, text="Text Margin").grid( - row=4, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING + ttk.Label(self._opencv_options, text="Text Margin").grid( + row=4, column=2, sticky=tk.W, padx=PADDING, pady=PADDING ) self._text_margin = Spinbox( self._opencv_options, @@ -1217,19 +1384,22 @@ def clear_output_directory(): command=self._on_bounding_box, ) self._bounding_box_button.grid( - row=5, column=0, columnspan=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) + row=5, column=0, columnspan=2, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) + ) + Tooltip( + self._bounding_box_button, "Draw a rectangle around detected motion in output clips." ) - tk.Label(self._opencv_options, text="Line Color").grid( - row=6, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) + ttk.Label(self._opencv_options, text="Line Color").grid( + row=6, column=0, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) ) self._bounding_box_color = ColorPicker(self._opencv_options) self._bounding_box_color.grid( row=6, column=1, sticky=tk.NSEW, pady=(PADDING, 0), padx=PADDING ) - tk.Label(self._opencv_options, text="Line Thickness").grid( - row=6, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) + ttk.Label(self._opencv_options, text="Line Thickness").grid( + row=6, column=2, sticky=tk.W, padx=PADDING, pady=(PADDING, 0) ) self._bounding_box_thickness = Spinbox( self._opencv_options, @@ -1242,9 +1412,9 @@ def clear_output_directory(): row=6, column=3, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=(PADDING, 0) ) - tk.Label(self._opencv_options, text="Smooth Time").grid( - row=7, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING - ) + smooth_label = ttk.Label(self._opencv_options, text="Smooth Time") + smooth_label.grid(row=7, column=0, sticky=tk.W, padx=PADDING, pady=PADDING) + Tooltip(smooth_label, "Temporal smoothing duration for bounding box edges.") self._bounding_box_smooth_time = Spinbox( self._opencv_options, str(CONFIG_MAP["bounding-box-smooth-time"]), @@ -1257,9 +1427,9 @@ def clear_output_directory(): row=7, column=1, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING ) - tk.Label(self._opencv_options, text="Min. Box Size").grid( - row=7, column=2, sticky=EXPAND_HORIZONTAL, padx=PADDING, pady=PADDING - ) + min_box_label = ttk.Label(self._opencv_options, text="Min. Box Size") + min_box_label.grid(row=7, column=2, sticky=tk.W, padx=PADDING, pady=PADDING) + Tooltip(min_box_label, "Minimum box side length relative to the frame's largest dimension.") self._bounding_box_min_size = Spinbox( self._opencv_options, value=str(CONFIG_MAP["bounding-box-min-size"]), @@ -1285,27 +1455,36 @@ def _show_options(self): self._opencv_codec_combo.grid_remove() self._encode_args_label.grid() self._encode_args_entry.grid() + first_focus = self._encode_args_entry else: self._opencv_options.configure(text="OpenCV Options") self._opencv_codec_label.grid() self._opencv_codec_combo.grid() self._encode_args_label.grid_remove() self._encode_args_entry.grid_remove() - self._opencv_options.grid(row=0, column=0, sticky=tk.NSEW, padx=PADDING, pady=PADDING) + first_focus = self._opencv_codec_combo + self._opencv_options.grid( + row=0, column=0, sticky=tk.NSEW, padx=PADDING, pady=(PADDING, 0) + ) self._ffmpeg_options.grid_remove() else: - self._ffmpeg_options.grid(row=0, sticky=tk.NSEW, padx=PADDING, pady=PADDING) + self._ffmpeg_options.grid(row=0, sticky=tk.NSEW, padx=PADDING, pady=(PADDING, 0)) self._opencv_options.grid_remove() + first_focus = self._ffmpeg_input_entry self._on_text_overlay() self._on_bounding_box() - show_modal(self._options_window, self._root) + show_modal(self._options_window, self._root, initial_focus=first_focus) def _dismiss_options(self): hide_modal(self._options_window, focus=self._options_button) def _on_select(self): - output_path = tkinter.filedialog.askdirectory(title="Set Output Directory", mustexist=True) + output_path = tkinter.filedialog.askdirectory( + title="Set Output Directory", + mustexist=True, + parent=self._root.winfo_toplevel(), + ) if output_path: self._output_dir_label.set(output_path) self._output_dir_str = output_path @@ -1447,10 +1626,11 @@ def __init__( ) self._combo.grid(row=0, column=0, sticky=EXPAND_HORIZONTAL, padx=PADDING) self._combo.bind("<>", lambda _: self._on_combo_selected()) + Tooltip(self._combo, "Apply a built-in or saved settings preset.") - ttk.Button(root, text="Save As...", command=on_save, width=SETTING_INPUT_WIDTH).grid( - row=0, column=1, sticky=EXPAND_HORIZONTAL - ) + save_btn = ttk.Button(root, text="Save As...", command=on_save, width=SETTING_INPUT_WIDTH) + save_btn.grid(row=0, column=1, sticky=EXPAND_HORIZONTAL) + Tooltip(save_btn, "Save the current settings as a reusable preset.") def refresh(self, preset_list: ty.List[presets.Preset]): """Update the list of presets shown in the dropdown.""" @@ -1498,8 +1678,10 @@ def __init__(self, root: tk.Tk, frame: tk.Widget): variable=self._scan_only, onvalue=True, offvalue=False, + command=self._refresh_open_state, ) self._scan_only_button.grid(row=1, column=0, sticky=tk.W) + Tooltip(self._scan_only_button, "Detect motion events without saving output video clips.") self._open_on_completion = tk.BooleanVar(frame, value=True) self._open_on_completion_button = ttk.Checkbutton( @@ -1511,6 +1693,11 @@ def __init__(self, root: tk.Tk, frame: tk.Widget): ) self._open_on_completion_button.grid(row=1, column=1, sticky=tk.W) + def _refresh_open_state(self): + self._open_on_completion_button["state"] = ( + tk.DISABLED if self._scan_only.get() else tk.NORMAL + ) + def disable(self): self._start_button["text"] = "Scanning..." self._start_button["state"] = tk.DISABLED @@ -1521,7 +1708,7 @@ def enable(self): self._start_button["text"] = "Start" self._start_button["state"] = tk.NORMAL self._scan_only_button["state"] = tk.NORMAL - self._open_on_completion_button["state"] = tk.NORMAL + self._refresh_open_state() @property def scan_only(self) -> bool: @@ -1530,6 +1717,7 @@ def scan_only(self) -> bool: @scan_only.setter def scan_only(self, newval: bool): self._scan_only.set(newval) + self._refresh_open_state() @property def open_on_completion(self) -> bool: @@ -1633,6 +1821,9 @@ def __init__( self._scan_window: ty.Optional[ScanWindow] = None self._wizard: ty.Optional["ScanWizard"] = None self._root.bind("<>", lambda _: self._start_scan()) + self._root.bind("", lambda _: self._root.event_generate("<>")) + self._root.bind("", lambda _: self._input_area.add_video(parent=self._root)) + self._root.bind("", lambda _: self._input_area.add_video(parent=self._root)) self._root.protocol("WM_DELETE_WINDOW", self._destroy) self._create_menubar() @@ -1696,6 +1887,12 @@ def _create_menubar(self): self._menubar.frame.grid(row=0, column=0, sticky=tk.EW) file_menu = self._menubar.add_menu("File", underline=0) + file_menu.add_command( + label="Add Videos...", + underline=0, + accelerator=f"{ACCELERATOR_KEY}+O", + command=lambda: self._input_area.add_video(parent=self._root), + ) file_menu.add_command( label="Scan Wizard", underline=5, @@ -1705,6 +1902,7 @@ def _create_menubar(self): file_menu.add_command( label="Start Scan", underline=0, + accelerator=f"{ACCELERATOR_KEY}+Enter", command=lambda: self._root.event_generate("<>"), ) file_menu.add_separator() @@ -1853,9 +2051,25 @@ def _start_scan(self): # Once we start a scan, the scan window should grab input focus until it is closed. assert self._scan_window is None - # TODO: Instead of just returning None below if the settings are invalid or we can't start - # the scan (e.g. no input videos selected), we should throw an exception and catch it here. - # We should then display a messagebox to the user indicating why the scan couldn't start. + if not self._input_area.videos: + tkinter.messagebox.showwarning( + title=WINDOW_TITLE, + message="Add at least one video to scan.", + parent=self._root, + ) + return + if self._input_area.start_end_time: + start, end = self._input_area.start_end_time + end_frame = FrameTimecode(end, 1000.0).frame_num + if end_frame and end_frame <= FrameTimecode(start, 1000.0).frame_num: + tkinter.messagebox.showerror( + title="Invalid Time Range", + message="End Time must be after Start Time (or set to 00:00:00.000 " + "to scan until the end of the video).", + parent=self._root, + ) + return + settings = self._get_settings() if not settings: return @@ -1912,6 +2126,7 @@ def _reset_config(self): title="Reset Settings", message="All settings will be reset. Do you want to continue?", icon=tkinter.messagebox.WARNING, + parent=self._dialog_parent(), ): return self._reload_config(ConfigRegistry()) @@ -2003,6 +2218,7 @@ def _on_preset_selected(self, preset: presets.Preset): tkinter.messagebox.showerror( title="Preset Load Failure", message=f"Failed to load preset: {preset.name}. See log messages for details.", + parent=self._dialog_parent(), ) self._preset_area.set_active(self._active_preset) return @@ -2024,6 +2240,7 @@ def _on_save_preset(self): message="Preset names must start with a letter or number, and can only " "contain letters, numbers, spaces, and ()-_. characters.\n\n" "Built-in presets cannot be overwritten.", + parent=self._root, ) return if name == presets.DEFAULT_PRESET_NAME: @@ -2031,6 +2248,7 @@ def _on_save_preset(self): title="Save As User Default", message="Existing user config will be overwritten. Do you want to continue?", icon=tkinter.messagebox.WARNING, + parent=self._root, ): return elif presets.preset_path(name).exists(): @@ -2038,6 +2256,7 @@ def _on_save_preset(self): title="Overwrite Preset", message=f"A preset named {name} already exists. Do you want to overwrite it?", icon=tkinter.messagebox.WARNING, + parent=self._root, ): return try: @@ -2047,6 +2266,7 @@ def _on_save_preset(self): tkinter.messagebox.showerror( title="Preset Save Failure", message="Failed to save preset. See log messages for details.", + parent=self._root, ) return logger.debug(f"saved preset to {path}") @@ -2098,7 +2318,9 @@ def _get_settings(self) -> ty.Optional[ScanSettings]: # We will create files but an output directory wasn't set ahead of time - prompt the # user to select one. output_dir = tkinter.filedialog.askdirectory( - title="Set Output Directory", mustexist=True + title="Set Output Directory", + mustexist=True, + parent=self._root, ) if not output_dir: return None diff --git a/dvr_scan/app/common.py b/dvr_scan/app/common.py index dcbae1e..8da99be 100644 --- a/dvr_scan/app/common.py +++ b/dvr_scan/app/common.py @@ -30,8 +30,10 @@ PADDING = 8 SETTING_INPUT_WIDTH = 12 MAX_THRESHOLD = 255.0 +# Dominant slate-blue from the DVR-Scan logo (`docs/assets/dvr-scan.svg` and `docs/style.css`). +BRAND_COLOR = "#59606d" -HELP_GUIDE_URL = "www.dvr-scan.com/guide" +HELP_GUIDE_URL = "https://www.dvr-scan.com/guide" DISCORD_URL = "https://discord.gg/69kf6f2Exb" # Hover-darken factor for menubar headings: multiply each RGB channel of the bar background @@ -39,6 +41,8 @@ _MENUBAR_HOVER_FACTOR = 0.85 _MENUBAR_POLL_MS = 25 _MENUBAR_REOPEN_GUARD_SEC = 0.08 +_TOOLTIP_MAX_WIDTH = 320 +_TOOLTIP_MARGIN = 8 def register_icon(root: tk.Tk): @@ -60,6 +64,15 @@ def _darken(widget: tk.Widget, color: str, factor: float = _MENUBAR_HOVER_FACTOR return f"#{red:02x}{green:02x}{blue:02x}" +def blend_color(widget: tk.Widget, foreground: str, background: str, opacity: float) -> str: + """Blend `foreground` toward `background` at `opacity` (1.0 = full foreground), returned + as a #rrggbb string. Used to derive theme-aware secondary text and border colors.""" + fg = [channel // 256 for channel in widget.winfo_rgb(foreground)] + bg = [channel // 256 for channel in widget.winfo_rgb(background)] + blended = (int(f * opacity + b * (1.0 - opacity)) for f, b in zip(fg, bg, strict=True)) + return "#{:02x}{:02x}{:02x}".format(*blended) + + def fit_window_to_screen( window: ty.Union[tk.Tk, tk.Toplevel], margin_x: int = 40, margin_y: int = 120 ) -> bool: @@ -101,7 +114,10 @@ def fill_help_menu(menu: tk.Menu, root: tk.Misc): """Append the Help entries shared by every window (guide, Discord, logs, About) to `menu`. `root` is the window the About dialog is shown over.""" menu.add_command( - label="Help Guide", underline=0, command=lambda: webbrowser.open_new_tab(HELP_GUIDE_URL) + label="Help Guide", + underline=0, + accelerator="F1", + command=lambda: webbrowser.open_new_tab(HELP_GUIDE_URL), ) menu.add_command( label="Discord", underline=0, command=lambda: webbrowser.open_new_tab(DISCORD_URL) @@ -109,16 +125,18 @@ def fill_help_menu(menu: tk.Menu, root: tk.Misc): menu.add_separator() menu.add_command(label="Open Logs", underline=5, command=lambda: open_path(log_folder())) menu.add_command(label="About DVR-Scan", underline=0, command=lambda: show_about(root)) + toplevel = root.winfo_toplevel() + toplevel.bind("", lambda _: webbrowser.open_new_tab(HELP_GUIDE_URL), add="+") -def show_modal(window: tk.Toplevel, parent: tk.Misc): +def show_modal(window: tk.Toplevel, parent: tk.Misc, initial_focus: ty.Optional[tk.Misc] = None): """Show `window` as a modal dialog over `parent` (the grab blocks input to other windows until `hide_modal`). Returns immediately: `wait_window` only returns once the window is destroyed, so waiting here would leave a nested event loop running for each time a reusable dialog is opened.""" window.transient(parent) window.deiconify() - window.focus() + (initial_focus if initial_focus is not None else window).focus_set() window.grab_set() @@ -130,6 +148,83 @@ def hide_modal(window: tk.Toplevel, focus: tk.Misc): focus.focus() +class Tooltip: + """A minimal hover and keyboard-focus tooltip, e.g. to label icon-only buttons and + explain technical settings.""" + + def __init__(self, widget: tk.Widget, text: str): + self._widget = widget + self._text = text + self._tip: ty.Optional[tk.Toplevel] = None + self._pointer_inside = False + widget.bind("", self._on_enter, add="+") + widget.bind("", self._on_leave, add="+") + widget.bind("", self._on_focus_in, add="+") + widget.bind("", self._hide, add="+") + widget.bind("", self._hide, add="+") + widget.bind("", self._hide, add="+") + # Tear down a visible tip if the widget is hidden (`grid_remove`) or destroyed. + widget.bind("", self._on_unmap, add="+") + widget.bind("", self._on_unmap, add="+") + + def _on_enter(self, _event=None): + self._pointer_inside = True + self._show() + + def _on_leave(self, _event=None): + self._pointer_inside = False + self._hide() + + def _on_focus_in(self, _event=None): + # Only show on keyboard focus traversal: clicking a hovered button fires + # `` (hiding the tip) and then ``, which should not re-open it. + if not self._pointer_inside: + self._show() + + def _on_unmap(self, _event=None): + self._pointer_inside = False + self._hide() + + def _show(self, _event=None): + if ( + self._tip is not None + or not self._widget.winfo_exists() + or not self._widget.winfo_viewable() + ): + return + self._tip = tk.Toplevel(self._widget) + self._tip.wm_overrideredirect(True) + tk.Label( + self._tip, + text=self._text, + justify=tk.LEFT, + foreground="#1a1a1a", + background="#ffffe0", + relief=tk.SOLID, + borderwidth=1, + padx=6, + pady=3, + wraplength=_TOOLTIP_MAX_WIDTH, + ).pack() + self._tip.update_idletasks() + tip_w = self._tip.winfo_reqwidth() + tip_h = self._tip.winfo_reqheight() + screen_w = self._widget.winfo_screenwidth() + screen_h = self._widget.winfo_screenheight() + x = self._widget.winfo_rootx() + min(16, self._widget.winfo_width() // 2) + y = self._widget.winfo_rooty() + self._widget.winfo_height() + 4 + if x + tip_w + _TOOLTIP_MARGIN > screen_w: + x = max(_TOOLTIP_MARGIN, screen_w - tip_w - _TOOLTIP_MARGIN) + if y + tip_h + _TOOLTIP_MARGIN > screen_h: + y = max(_TOOLTIP_MARGIN, self._widget.winfo_rooty() - tip_h - 4) + self._tip.wm_geometry(f"+{x}+{y}") + + def _hide(self, _event=None): + if self._tip is not None: + self._tip.destroy() + self._tip = None + + class MenuBar: """A custom menubar built from `tk.Menubutton` headings so the top-level menus get a real hover highlight. The native Windows menubar (`toplevel["menu"] = ...`) exposes no diff --git a/dvr_scan/app/region_editor.py b/dvr_scan/app/region_editor.py index 77b2251..ece23ac 100644 --- a/dvr_scan/app/region_editor.py +++ b/dvr_scan/app/region_editor.py @@ -29,7 +29,7 @@ import PIL.ImageTk from scenedetect import FrameTimecode, VideoOpenFailure, open_video -from dvr_scan.app.common import MenuBar, fill_help_menu, register_icon +from dvr_scan.app.common import MenuBar, Tooltip, fill_help_menu, register_icon from dvr_scan.region import Point, Size, bound_point, load_regions, save_regions WINDOW_TITLE = "DVR-Scan Region Editor" @@ -218,6 +218,10 @@ def __init__( self._panning: bool = False self._controls_window: tk.Toplevel = None self._region_selector: ttk.Combobox = None + self._delete_region_button: ty.Optional[ttk.Button] = None + self._frame_label: ty.Optional[ttk.Label] = None + self._mask_var: ty.Optional[tk.BooleanVar] = None + self._aa_var: ty.Optional[tk.BooleanVar] = None self._context_menu: tk.Menu = None # Clones of the normal state variables since sometimes we can still interact with the main @@ -291,6 +295,8 @@ def seek_to_frame(self, frame_num: int) -> bool: self._seek_widget.set(target) finally: self._updating_seek_widget = False + if self._frame_label is not None and self._total_frames > 0: + self._frame_label.configure(text=f"{target + 1} / {self._total_frames}") self._original_frame = self._source_frame[:: self._scale, :: self._scale, :].copy() self._frame = self._original_frame.copy() self._redraw = True @@ -374,10 +380,16 @@ def _update_ui_state(self): self._region_selector["values"] = tuple( f"Shape {i + 1}" for i in range(len(self._regions)) ) or ("",) - assert self._active_shape is not None - self._region_selector.current(self._active_shape) + active_idx = ( + self._active_shape + if (self._active_shape is not None and self._active_shape < len(self._regions)) + else 0 + ) + self._region_selector.current(active_idx) self._region_selector.config(state="readonly" if self._regions else "disabled") self._region_selector.selection_clear() + if self._delete_region_button is not None: + self._delete_region_button.configure(state=tk.NORMAL if self._regions else tk.DISABLED) def _copy_scan_command_to_clipboard(self): region_info = [] @@ -385,6 +397,7 @@ def _copy_scan_command_to_clipboard(self): region_info.append("-a %s" % " ".join(f"{x} {y}" for x, y in shape)) data = " ".join(region_info) scan_command = f"dvr-scan -i {self._settings.video_path} {data}" + self._root.clipboard_clear() self._root.clipboard_append(scan_command) logger.info( f"Region data copied to clipboard. To scan via command-line, run:\n{scan_command}" @@ -523,6 +536,13 @@ def _draw(self): color, thickness=cv2.FILLED, ) + cv2.rectangle( + frame, + start, + end, + (0, 0, 0), + thickness=1, + ) self._frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) self._image = PIL.ImageTk.PhotoImage(image=PIL.Image.fromarray(self._frame)) @@ -705,35 +725,51 @@ def set_scale(val: str): # Disable resize since we are probably using the mouse to control this widget. self._rescale(allow_resize=False) - frame = tk.Frame(self._root) + self._mask_var = tk.BooleanVar(self._root, value=self._settings.mask_source) + self._aa_var = tk.BooleanVar(self._root, value=self._settings.use_aa) + + frame = ttk.Frame(self._root, padding=(8, 4)) frame.grid(row=4, column=0, sticky="ew", columnspan=2) - frame.columnconfigure(4, weight=1) + frame.columnconfigure(6, weight=1) frame.rowconfigure(0, weight=1) self._scale_widget = ttk.Scale( frame, orient=tk.HORIZONTAL, - length=200, + length=160, from_=MAX_DOWNSCALE_FACTOR, to=MIN_DOWNSCALE_FACTOR, command=set_scale, value=self._scale, ) - tk.Label(frame, text="Active Region", anchor=tk.W).grid( - row=0, column=0, sticky=tk.W, padx=8.0 + ttk.Label(frame, text="Active Region", anchor=tk.W).grid( + row=0, column=0, sticky=tk.W, padx=(0, 8.0) ) self._region_selector = ttk.Combobox( frame, values=list(f"Shape {i + 1}" for i in range(len(self._regions))), - width=12, + width=11, justify=tk.CENTER, ) self._region_selector.state(["readonly"]) self._region_selector.grid(row=0, column=1, sticky="w") self._region_selector.current(0) self._region_selector.bind("<>", lambda _: self._on_shape_select()) - # Looks weird when the widget takes focus, but still seems to work when we redirect focus to - # the root. - self._region_selector.bind("", lambda _: self._root.focus()) + + add_region_button = ttk.Button( + frame, text="+ Add", width=6, command=lambda: self._add_region(use_mouse=False) + ) + add_region_button.grid(row=0, column=2, padx=(6.0, 4.0)) + Tooltip(add_region_button, f"Add a new detection region ({KEYBIND_REGION_ADD})") + + self._delete_region_button = ttk.Button( + frame, text="Delete", width=7, command=self._delete_region + ) + self._delete_region_button.grid(row=0, column=3, padx=(0.0, 8.0)) + Tooltip( + self._delete_region_button, + f"Delete the active detection region ({KEYBIND_REGION_DELETE})", + ) + if self._ensure_video_open() and self._total_frames > 1: def set_frame(val: str): @@ -747,24 +783,42 @@ def set_frame(val: str): finally: self._updating_seek_widget = False - tk.Label(frame, text="Frame", anchor=tk.W).grid( - row=0, column=2, sticky=tk.W, padx=(16.0, 8.0) + ttk.Label(frame, text="Frame", anchor=tk.W).grid( + row=0, column=4, sticky=tk.W, padx=(8.0, 6.0) ) self._seek_widget = ttk.Scale( frame, orient=tk.HORIZONTAL, - length=160, + length=140, from_=0, to=max(1, self._total_frames - 1), command=set_frame, value=self._current_frame_num, ) - self._seek_widget.grid(row=0, column=3, sticky="w", padx=(0, 8.0)) - ttk.Button(frame, text="Toggle Mask", command=self._toggle_mask).grid( - row=0, column=10, padx=8.0 + self._seek_widget.grid(row=0, column=5, sticky="w", padx=(0, 6.0)) + Tooltip(self._seek_widget, "Seek video preview (, / . for +/-1 frame, < / > for +/-10)") + self._frame_label = ttk.Label( + frame, + text=f"{self._current_frame_num + 1} / {self._total_frames}", + anchor=tk.W, + ) + self._frame_label.grid(row=0, column=6, sticky="w", padx=(0, 8.0)) + + ttk.Label(frame, text="Zoom", anchor=tk.E).grid( + row=0, column=8, sticky=tk.E, padx=(8.0, 6.0) + ) + self._scale_widget.grid(row=0, column=9, sticky="e", padx=(0, 8.0)) + mask_check = ttk.Checkbutton( + frame, + text="Toggle Mask", + variable=self._mask_var, + command=self._on_mask_var_changed, ) - self._scale_widget.grid(row=0, column=9, sticky="e", padx=8.0) - tk.Label(frame, text="Zoom", anchor=tk.E).grid(row=0, column=8, sticky=tk.E, padx=(0, 8.0)) + mask_check.grid(row=0, column=10, padx=6.0) + Tooltip(mask_check, f"Preview masked detection area ({KEYBIND_MASK})") + controls_button = ttk.Button(frame, text="Controls...", command=self._show_help) + controls_button.grid(row=0, column=11, padx=(4.0, 0.0)) + Tooltip(controls_button, f"Show keyboard and mouse controls ({KEYBIND_HELP})") self._bind_mouse() self._bind_keyboard() @@ -823,12 +877,17 @@ def _create_menubar(self): ) view_menu = self._menubar.add_menu("View", underline=0) - view_menu.add_command( - label="Mask Mode", command=self._toggle_mask, accelerator=KEYBIND_MASK, underline=0 + view_menu.add_checkbutton( + label="Mask Mode", + variable=self._mask_var, + command=self._on_mask_var_changed, + accelerator=KEYBIND_MASK, + underline=0, ) - view_menu.add_command( + view_menu.add_checkbutton( label="Antialiasing", - command=self._toggle_antialiasing, + variable=self._aa_var, + command=self._on_aa_var_changed, accelerator=KEYBIND_TOGGLE_AA, underline=0, ) @@ -860,123 +919,145 @@ def _create_menubar(self): self._update_ui_state() def _show_help(self): - if self._controls_window is None: - self._controls_window = tk.Toplevel(master=self._root) - self._controls_window.withdraw() - self._controls_window.title("Controls") - self._controls_window.resizable(True, True) - self._controls_window.transient(self._root) - - def dismiss(): - self._controls_window.destroy() - self._controls_window = None - self._root.focus() + if self._controls_window is not None and self._controls_window.winfo_exists(): + self._controls_window.deiconify() + self._controls_window.lift() + self._controls_window.focus_set() + return - self._controls_window.protocol("WM_DELETE_WINDOW", dismiss) - self._controls_window.attributes("-topmost", True) - self._controls_window.bind("", lambda _: dismiss()) - self._controls_window.bind("", lambda _: self._root.focus()) + self._controls_window = tk.Toplevel(master=self._root) + self._controls_window.withdraw() + self._controls_window.title("Region Editor Controls") + self._controls_window.resizable(True, True) + self._controls_window.transient(self._root) + + def dismiss(_event=None): + win = self._controls_window + self._controls_window = None + if win is not None and win.winfo_exists(): + win.destroy() + if self._root is not None and self._root.winfo_exists(): + self._root.focus() - def handle_escape(_: tk.Event): - self._controls_window.destroy() - self._controls_window = None + self._controls_window.protocol("WM_DELETE_WINDOW", dismiss) + self._controls_window.bind("", dismiss) - self._controls_window.bind("", handle_escape) + regions = ttk.Labelframe(self._controls_window, text="Regions", padding=8.0) + regions.columnconfigure(0, weight=1) + regions.columnconfigure(1, weight=1) - regions = ttk.Labelframe(self._controls_window, text="Regions", padding=8.0) - regions.columnconfigure(0, weight=1) - regions.columnconfigure(1, weight=1) + ttk.Label(regions, text="Add Point").grid(row=0, column=0, sticky="w", pady=2) + ttk.Label(regions, text="Left Click | Keyboard: +", justify=tk.RIGHT).grid( + row=0, column=1, sticky="e", padx=(16, 0), pady=2 + ) - ttk.Label(regions, text="Add Point").grid(row=0, column=0, sticky="w") - ttk.Label(regions, text="Left Click\nKeyboard: +", justify=tk.RIGHT).grid( - row=0, column=1, sticky="e" - ) + ttk.Label(regions, text="Remove Point").grid(row=1, column=0, sticky="w", pady=2) + ttk.Label(regions, text="Right Click | Keyboard: -", justify=tk.RIGHT).grid( + row=1, column=1, sticky="e", padx=(16, 0), pady=2 + ) - ttk.Label(regions, text="Remove Point").grid(row=1, column=0, sticky="w") - ttk.Label(regions, text="Right Click\nKeyboard: -", justify=tk.RIGHT).grid( - row=1, column=1, sticky="e" - ) + ttk.Label(regions, text="Move Point").grid(row=2, column=0, sticky="w", pady=2) + ttk.Label(regions, text="Left Click + Drag").grid( + row=2, column=1, sticky="e", padx=(16, 0), pady=2 + ) - ttk.Label(regions, text="Move Point").grid(row=2, column=0, sticky="w") - ttk.Label(regions, text="Left Click + Drag").grid(row=2, column=1, sticky="e") - - ttk.Label(regions, text="").grid(row=4, column=0, sticky="w") - - ttk.Label(regions, text="Add/Remove Shape").grid(row=5, column=0, sticky="w") - ttk.Label( - regions, - text=f"Mouse: Right Click\nKeyboard: {KEYBIND_REGION_ADD}", - justify=tk.RIGHT, - ).grid(row=5, column=1, sticky="e") - - ttk.Label(regions, text="Active Shape").grid(row=6, column=0, sticky="w") - ttk.Label( - regions, - text="Mouse: Right Click\nKeyboard: " - f"{KEYBIND_REGION_NEXT}/{KEYBIND_REGION_PREVIOUS}", - justify=tk.RIGHT, - ).grid(row=6, column=1, sticky="e") - - viewport = ttk.Labelframe(self._controls_window, text="Viewport", padding=8.0) - viewport.columnconfigure(0, weight=1) - viewport.columnconfigure(1, weight=1) - - ttk.Label(viewport, text="Zoom").grid(row=0, column=0, sticky="w") - ttk.Label( - viewport, - text=f"Mouse: {ACCELERATOR_KEY} + Scroll\nKeyboard: " - f"{KEYBIND_DOWNSCALE_INC}/{KEYBIND_DOWNSCALE_DEC}", - justify=tk.RIGHT, - ).grid(row=0, column=1, sticky="e") - - ttk.Label(viewport, text="Move/Pan").grid(row=3, column=0, sticky="w") - ttk.Label(viewport, text=f"{ACCELERATOR_KEY} + Left Click").grid( - row=3, column=1, sticky="e" - ) + ttk.Label(regions, text="Add / Delete Shape").grid(row=3, column=0, sticky="w", pady=2) + ttk.Label( + regions, + text=f"Right Click | {KEYBIND_REGION_ADD} / {KEYBIND_REGION_DELETE}", + justify=tk.RIGHT, + ).grid(row=3, column=1, sticky="e", padx=(16, 0), pady=2) + + ttk.Label(regions, text="Select Shape").grid(row=4, column=0, sticky="w", pady=2) + ttk.Label( + regions, + text=f"1-9 | {KEYBIND_REGION_NEXT} / {KEYBIND_REGION_PREVIOUS}", + justify=tk.RIGHT, + ).grid(row=4, column=1, sticky="e", padx=(16, 0), pady=2) + + viewport = ttk.Labelframe(self._controls_window, text="Viewport", padding=8.0) + viewport.columnconfigure(0, weight=1) + viewport.columnconfigure(1, weight=1) + + ttk.Label(viewport, text="Zoom").grid(row=0, column=0, sticky="w", pady=2) + zoom_keys = f"{KEYBIND_DOWNSCALE_INC} / {KEYBIND_DOWNSCALE_DEC}" + ttk.Label( + viewport, + text=f"{ACCELERATOR_KEY} + Scroll | {zoom_keys}", + justify=tk.RIGHT, + ).grid(row=0, column=1, sticky="e", padx=(16, 0), pady=2) + + ttk.Label(viewport, text="Move / Pan").grid(row=1, column=0, sticky="w", pady=2) + ttk.Label(viewport, text=f"{ACCELERATOR_KEY} + Left Click + Drag").grid( + row=1, column=1, sticky="e", padx=(16, 0), pady=2 + ) - ttk.Label(viewport, text="Seek Frame").grid(row=4, column=0, sticky="w") - ttk.Label(viewport, text="Keyboard: , / .").grid(row=4, column=1, sticky="e") + ttk.Label(viewport, text="Step Frame (+/-1, +/-10)").grid( + row=2, column=0, sticky="w", pady=2 + ) + ttk.Label(viewport, text=", / . | < / >").grid( + row=2, column=1, sticky="e", padx=(16, 0), pady=2 + ) - ttk.Label(viewport, text="Toggle Mask Mode").grid(row=5, column=0, sticky="w") - ttk.Label(viewport, text=f"Keyboard: {KEYBIND_MASK}").grid(row=5, column=1, sticky="e") + ttk.Label(viewport, text="Toggle Mask Mode").grid(row=3, column=0, sticky="w", pady=2) + ttk.Label(viewport, text=KEYBIND_MASK).grid( + row=3, column=1, sticky="e", padx=(16, 0), pady=2 + ) - ttk.Label(viewport, text="Toggle Antialiasing").grid(row=6, column=0, sticky="w") - ttk.Label(viewport, text=f"Keyboard: {KEYBIND_TOGGLE_AA}").grid( - row=6, column=1, sticky="e" - ) + ttk.Label(viewport, text="Toggle Antialiasing").grid(row=4, column=0, sticky="w", pady=2) + ttk.Label(viewport, text=KEYBIND_TOGGLE_AA).grid( + row=4, column=1, sticky="e", padx=(16, 0), pady=2 + ) - general = ttk.Labelframe(self._controls_window, text="General", padding=8.0) - general.columnconfigure(0, weight=1) - general.columnconfigure(1, weight=1) + general = ttk.Labelframe(self._controls_window, text="General", padding=8.0) + general.columnconfigure(0, weight=1) + general.columnconfigure(1, weight=1) - ttk.Label(general, text="Start Scan").grid(row=0, column=0, sticky="w") - ttk.Label(general, text=f"Keyboard: {KEYBIND_START_SCAN}").grid( - row=0, column=1, sticky="e" + row_idx = 0 + if not self._launched_from_app: + ttk.Label(general, text="Start Scan").grid(row=row_idx, column=0, sticky="w", pady=2) + ttk.Label(general, text=KEYBIND_START_SCAN).grid( + row=row_idx, column=1, sticky="e", padx=(16, 0), pady=2 ) + row_idx += 1 - ttk.Label(general, text="Quit").grid(row=1, column=0, sticky="w") - ttk.Label(general, text=f"Keyboard: {KEYBIND_QUIT}").grid(row=1, column=1, sticky="e") - - ttk.Label(general, text="Show Help").grid(row=2, column=0, sticky="w") - ttk.Label(general, text=f"Keyboard: {KEYBIND_HELP}").grid(row=2, column=1, sticky="e") - - ttk.Label(general, text="Copy Scan Command").grid(row=3, column=0, sticky="w") - ttk.Label(general, text=f"Keyboard: {KEYBIND_COPY_COMMAND}").grid( - row=3, column=1, sticky="e" - ) + close_label = "Close Editor" if self._launched_from_app else "Quit" + ttk.Label(general, text=close_label).grid(row=row_idx, column=0, sticky="w", pady=2) + ttk.Label(general, text=KEYBIND_QUIT).grid( + row=row_idx, column=1, sticky="e", padx=(16, 0), pady=2 + ) + row_idx += 1 - regions.grid(row=0, sticky="nsew", padx=8.0, pady=8.0) - viewport.grid(row=1, sticky="nsew", padx=8.0, pady=8.0) - general.grid(row=2, sticky="nsew", padx=8.0, pady=8.0) + ttk.Label(general, text="Undo / Redo").grid(row=row_idx, column=0, sticky="w", pady=2) + ttk.Label(general, text=f"{KEYBIND_UNDO} / {KEYBIND_REDO}").grid( + row=row_idx, column=1, sticky="e", padx=(16, 0), pady=2 + ) + row_idx += 1 - self._controls_window.columnconfigure(0, weight=1) - self._controls_window.rowconfigure(0, weight=1) - self._controls_window.rowconfigure(1, weight=1) - self._controls_window.rowconfigure(2, weight=1) - self._controls_window.update() + ttk.Label(general, text="Copy CLI Scan Command").grid( + row=row_idx, column=0, sticky="w", pady=2 + ) + ttk.Label(general, text=KEYBIND_COPY_COMMAND).grid( + row=row_idx, column=1, sticky="e", padx=(16, 0), pady=2 + ) + regions.grid(row=0, column=0, sticky="nsew", padx=8.0, pady=(8.0, 4.0)) + viewport.grid(row=1, column=0, sticky="nsew", padx=8.0, pady=4.0) + general.grid(row=2, column=0, sticky="nsew", padx=8.0, pady=4.0) + close_btn = ttk.Button(self._controls_window, text="Close", command=dismiss) + close_btn.grid(row=3, column=0, sticky="e", padx=8.0, pady=8.0) + + self._controls_window.columnconfigure(0, weight=1) + self._controls_window.rowconfigure(0, weight=1) + self._controls_window.rowconfigure(1, weight=1) + self._controls_window.rowconfigure(2, weight=1) + self._controls_window.update_idletasks() + self._controls_window.minsize( + width=self._controls_window.winfo_reqwidth(), + height=self._controls_window.winfo_reqheight(), + ) self._controls_window.deiconify() - self._root.focus() + close_btn.focus_set() def _adjust_downscale(self, amount: int, allow_resize=True): # scale is clamped to MIN_DOWNSCALE_FACTOR/MAX_DOWNSCALE_FACTOR. @@ -1057,6 +1138,11 @@ def _prompt_load(self): return if not os.path.exists(load_path): logger.error(f"File does not exist: {load_path}") + tkinter.messagebox.showerror( + "Region Load Failure", + f"Region file does not exist:\n{load_path}", + parent=self._root, + ) return regions = [] try: @@ -1067,6 +1153,11 @@ def _prompt_load(self): if not reason: reason = "Could not parse region file!" logger.error(f"Error loading region from {load_path}: {reason}") + tkinter.messagebox.showerror( + "Region Load Failure", + f"Failed to load region file:\n\n{reason}", + parent=self._root, + ) else: logger.debug( "Loaded %d region%s from region file:\n%s", @@ -1101,22 +1192,36 @@ def _delete_point(self): def _toggle_antialiasing(self): self._settings.use_aa = not self._settings.use_aa + if self._aa_var is not None: + self._aa_var.set(self._settings.use_aa) self._redraw = True logger.debug("AA: %s", "ON" if self._settings.use_aa else "OFF") if self._scale >= MAX_DOWNSCALE_AA_LEVEL: logger.warning("AA is disabled due to current scale factor.") self._draw() + def _on_aa_var_changed(self): + if self._aa_var is not None and self._settings.use_aa != self._aa_var.get(): + self._toggle_antialiasing() + def _toggle_mask(self): self._settings.mask_source = not self._settings.mask_source + if self._mask_var is not None: + self._mask_var.set(self._settings.mask_source) logger.debug("Masking: %s", "ON" if self._settings.mask_source else "OFF") self._redraw = True self._draw() + def _on_mask_var_changed(self): + if self._mask_var is not None and self._settings.mask_source != self._mask_var.get(): + self._toggle_mask() + def _on_shape_select(self): if self._regions: self._select_region(self._region_selector.current()) self._region_selector.selection_clear() + if self._editor_canvas is not None: + self._editor_canvas.focus_set() def _add_point(self, drag: bool = False) -> bool: if self._nearest_points is not None: @@ -1240,15 +1345,6 @@ def _handle_mouse_input(self, event, point: Point): self._draw() - def _on_mouse_leave(self): - logger.debug("mouse left window") - if not (self._dragging or self._panning): - self._curr_mouse_pos = None - self._hover_point = None - self._nearest_points = None - self._redraw = True - self._draw() - def _cancel_active_action(self): logger.debug("cancelling active action") if self._dragging: @@ -1381,17 +1477,22 @@ def _activate_context_menu(self, e: tk.Event): ) self._context_menu.post(e.x_root, e.y_root) - def _add_region(self): + def _add_region(self, use_mouse: bool = True): if self._dragging: return - # Add a box around the current mouse position that's roughly 20% of the frame. + # Add a box around the current mouse position (or frame center if invoked from the + # toolbar / keyboard while the pointer is outside the canvas) covering ~20% of the frame. width, height = ( max(1, self._source_size.w // 10), max(1, self._source_size.h // 10), ) - - top_left = Point(x=self._curr_mouse_pos.x - width, y=self._curr_mouse_pos.y - height) + center = ( + self._curr_mouse_pos + if (use_mouse and self._curr_mouse_pos is not None) + else Point(x=self._source_size.w // 2, y=self._source_size.h // 2) + ) + top_left = Point(x=center.x - width, y=center.y - height) points = [ top_left, Point(x=top_left.x + 2 * width, y=top_left.y), diff --git a/dvr_scan/app/scan_window.py b/dvr_scan/app/scan_window.py index 0d19151..0da324a 100644 --- a/dvr_scan/app/scan_window.py +++ b/dvr_scan/app/scan_window.py @@ -40,6 +40,8 @@ from dvr_scan.video_input import BackendUnavailable, VideoStreamConcat, open_input TITLE = "Scanning..." +RESULTS_TITLE = "Scan Results" +STOPPED_TITLE = "Scan Stopped" logger = getLogger("dvr_scan") @@ -60,6 +62,25 @@ PREVIEW_COLUMN_WIDTH = FILMSTRIP_WIDTH + 12 +def format_progress_stats( + elapsed: float, + processed: int, + total: ty.Optional[int], + rate: ty.Optional[float], +) -> ty.Tuple[str, str, str]: + """Format `(elapsed_str, rate_str, remaining_str)` from tqdm progress metrics. + Clamps remaining time at 0 so VFR or frame-skip overshoot never shows negative time.""" + effective_rate = rate or (processed / elapsed if elapsed else None) + elapsed_str = tqdm.format_interval(elapsed) + if effective_rate: + rate_str = f"{effective_rate:.2f}" + remaining = max(0.0, (total - processed) / effective_rate) if total else None + remaining_str = tqdm.format_interval(remaining) if remaining is not None else "?" + else: + rate_str, remaining_str = "N/A", "?" + return elapsed_str, rate_str, remaining_str + + # Raised when a scan cannot be set up (by creating a `ScanProgressView` or `ScanWindow`): # the input mode is unavailable on this system, the inputs can't be opened or combined (e.g. # different resolutions, a deleted file), or the output can't be created (e.g. ffmpeg @@ -142,12 +163,19 @@ def __init__( # Widgets self._progress = tk.IntVar(self.frame, value=0) self._progress_bar = ttk.Progressbar(self.frame, variable=self._progress) - self._events_label = tk.Label(self.frame) - self._elapsed_label = tk.Label(self.frame) - self._remaining_label = tk.Label(self.frame) - self._processed_label = tk.Label(self.frame) - self._speed_label = tk.Label(self.frame) - self._total_label = tk.Label(self.frame) + self._events_label = ttk.Label( + self.frame, + text="Events Found: 0", + font=("TkDefaultFont", 10, "bold"), + anchor=tk.CENTER, + ) + self._elapsed_label = ttk.Label(self.frame, text="Elapsed: 00:00", anchor=tk.E) + self._remaining_label = ttk.Label( + self.frame, text="Preparing scan...", anchor=tk.CENTER, justify=tk.CENTER + ) + self._processed_label = ttk.Label(self.frame, text="Processed: 0 frames", anchor=tk.W) + self._speed_label = ttk.Label(self.frame, text="Rate: N/A FPS", anchor=tk.E) + self._total_label = ttk.Label(self.frame, text="Total: ? frames", anchor=tk.W) # Layout self.frame.columnconfigure(0, weight=1) @@ -158,13 +186,13 @@ def __init__( self.frame.rowconfigure(3, weight=32) self.frame.rowconfigure(4, weight=1) self.frame.rowconfigure(5, weight=1) - self._events_label.grid(row=0, column=0, columnspan=2, sticky=tk.NSEW, pady=(PADDING, 0)) - self._progress_bar.grid(sticky=tk.NSEW, row=1, columnspan=2, pady=PADDING, padx=PADDING) - self._remaining_label.grid(row=2, column=0, columnspan=2, sticky=tk.NSEW) - self._processed_label.grid(row=4, column=0, sticky=tk.NW, padx=PADDING) - self._speed_label.grid(row=4, column=1, sticky=tk.NE, padx=PADDING) - self._total_label.grid(row=5, column=0, sticky=tk.NW, padx=PADDING) - self._elapsed_label.grid(row=5, column=1, sticky=tk.NE, padx=PADDING) + self._events_label.grid(row=0, column=0, columnspan=2, sticky=tk.EW, pady=(PADDING * 2, 0)) + self._progress_bar.grid(sticky=tk.EW, row=1, columnspan=2, pady=PADDING, padx=PADDING * 2) + self._remaining_label.grid(row=2, column=0, columnspan=2, sticky=tk.EW, padx=PADDING) + self._processed_label.grid(row=4, column=0, sticky=tk.NW, padx=PADDING * 2) + self._speed_label.grid(row=4, column=1, sticky=tk.NE, padx=PADDING * 2) + self._total_label.grid(row=5, column=0, sticky=tk.NW, padx=PADDING * 2, pady=(0, PADDING)) + self._elapsed_label.grid(row=5, column=1, sticky=tk.NE, padx=PADDING * 2, pady=(0, PADDING)) self._scan_finished = threading.Event() self._start_time = 0.0 @@ -244,21 +272,24 @@ def _on_scan_started(self, num_frames: int): def _on_processed_frame(self, progress_bar: tqdm, num_events: int): self.num_events = num_events - self.frames_processed += 1 + # `progress_bar.n` includes skipped frames (`1 + frame_skip` per step, updated right + # after this callback), so use it to keep the progress bar aligned with total frames. + bar_pos = getattr(progress_bar, "n", None) + if isinstance(bar_pos, (int, float)): + self.frames_processed = max(self.frames_processed + 1, int(bar_pos) + 1) + else: + self.frames_processed += 1 curr = time.time_ns() # Update internal state used for UI labels using the progress bar in the scanner. if (curr - self._last_stats_update_ns) > STATS_UPDATE_RATE_NS: self._last_stats_update_ns = curr stats = progress_bar.format_dict - elapsed, processed, total = stats["elapsed"], stats["n"], stats["total"] - rate = stats["rate"] or (processed / elapsed if elapsed else None) - self.elapsed = tqdm.format_interval(elapsed) - if rate: - self.rate = f"{rate:.2f}" - remaining = (total - processed) / rate if total else None - self._remaining = tqdm.format_interval(remaining) if remaining is not None else "?" - else: - self.rate, self._remaining = "N/A", "?" + self.elapsed, self.rate, self._remaining = format_progress_stats( + elapsed=stats["elapsed"], + processed=stats["n"], + total=stats["total"], + rate=stats["rate"], + ) def _do_scan(self): # We'll handle any errors in the main Tkinter thread via the on_finished callback. @@ -306,9 +337,14 @@ def __init__(self, root: tk.Tk, settings: ScanSettings, on_destroyed: ty.Callabl self._root = tk.Toplevel(master=root) self._root.withdraw() self._root.title(TITLE) + self._root.transient(root) self._root.resizable(True, True) + self._root.minsize(width=420, height=220) self._on_destroyed = on_destroyed - self._results_table: ty.Optional[ttk.Frame] = None + output_dir = settings.get("output-dir") + self._output_dir: ty.Optional[str] = ( + str(output_dir) if output_dir and not settings.get("scan-only") else None + ) try: self._view = ScanProgressView(self._root, settings, self._on_finished) except BaseException: @@ -318,27 +354,32 @@ def __init__(self, root: tk.Tk, settings: ScanSettings, on_destroyed: ty.Callabl self._root.bind("<>", self.stop) self._root.protocol("WM_DELETE_WINDOW", self.prompt_stop) + self._root.bind("", lambda _: self.prompt_stop()) self._root.columnconfigure(0, weight=1) self._root.rowconfigure(0, weight=1) self._view.frame.grid(row=0, column=0, sticky=tk.NSEW) - buttons = tk.Frame(self._root) - buttons.rowconfigure(0, weight=1) + buttons = ttk.Frame(self._root) buttons.columnconfigure(0, weight=1) - buttons.columnconfigure(1, weight=1) - buttons.columnconfigure(2, weight=1) - self._stop_button = tk.Button(buttons, text="Stop", command=self.prompt_stop) - self._save_button = tk.Button( + self._stop_button = ttk.Button(buttons, text="Stop", command=self.prompt_stop) + self._open_dir_button = ttk.Button( + buttons, + text="Open Output Folder", + command=lambda: open_path(self._output_dir) if self._output_dir else None, + ) + self._save_button = ttk.Button( buttons, text="Save Report...", command=self._on_save_report, state=tk.DISABLED ) - self._close_button = tk.Button( + self._close_button = ttk.Button( buttons, text="Close", command=self._destroy, state=tk.DISABLED ) - self._stop_button.grid(row=0, column=0, pady=PADDING, sticky=tk.NSEW, padx=PADDING) - self._save_button.grid(row=0, column=1, pady=PADDING, sticky=tk.NSEW, padx=PADDING) - self._close_button.grid(row=0, column=2, pady=PADDING, sticky=tk.NSEW, padx=PADDING) - buttons.grid(row=1, column=0, sticky=tk.NSEW) + self._stop_button.grid(row=0, column=1, pady=PADDING, padx=(PADDING, 0)) + self._open_dir_button.grid(row=0, column=2, pady=PADDING, padx=(PADDING, 0)) + self._open_dir_button.grid_remove() + self._save_button.grid(row=0, column=3, pady=PADDING, padx=(PADDING, 0)) + self._close_button.grid(row=0, column=4, pady=PADDING, padx=PADDING) + buttons.grid(row=1, column=0, sticky=tk.EW) def _on_finished(self): if self._view.error is not None: @@ -352,21 +393,44 @@ def _on_finished(self): return logger.debug("scan complete") self._stop_button["state"] = tk.DISABLED + self._stop_button.grid_remove() self._close_button["state"] = tk.NORMAL - # Nothing left to stop: closing the window now just closes it. + # Nothing left to stop: closing the window or pressing Escape now just closes it. self._root.protocol("WM_DELETE_WINDOW", self._destroy) + self._root.bind("", lambda _: self._destroy()) + self._root.title(STOPPED_TITLE if self._view.was_stopped else RESULTS_TITLE) # A report is only meaningful for a completed scan that produced an event list. if self._view.result is not None and not self._view.was_stopped: self._save_button["state"] = tk.NORMAL + if self._output_dir: + self._open_dir_button.grid() self._show_results(self._view.result.event_list) + self._close_button.focus_set() def _show_results(self, event_list: ty.List[MotionEvent]): - """Swap the progress view for a table of detected events with thumbnails.""" + """Swap the progress view for a summary and table of detected events.""" self._view.frame.grid_remove() - table = build_event_table(self._root, self._view.input_paths, event_list) - table.grid(row=0, column=0, sticky=tk.NSEW, padx=PADDING, pady=(PADDING, 0)) - self._results_table = table - self._root.minsize(width=780, height=360) + panel = ttk.Frame(self._root) + panel.columnconfigure(0, weight=1) + panel.rowconfigure(1, weight=1) + summary = scan_summary_text(self._view) + ttk.Label(panel, text=summary, anchor=tk.W, justify=tk.LEFT).grid( + row=0, column=0, sticky=tk.EW, pady=(0, PADDING) + ) + if event_list: + table = build_event_table(panel, self._view.input_paths, event_list) + table.grid(row=1, column=0, sticky=tk.NSEW) + self._root.minsize(width=780, height=360) + else: + empty_msg = ( + f"{NO_EVENTS_TEXT}\n\n" + "Try lowering the Threshold in Settings > Motion (or picking the " + "High Sensitivity preset) and scanning again." + ) + ttk.Label(panel, text=empty_msg, anchor=tk.NW, justify=tk.LEFT).grid( + row=1, column=0, sticky=tk.NSEW, pady=PADDING + ) + panel.grid(row=0, column=0, sticky=tk.NSEW, padx=PADDING, pady=(PADDING, 0)) def _on_save_report(self): if self._view.result is None: @@ -450,6 +514,18 @@ def provide(): return [make(event) for event in event_list], release +NO_EVENTS_TEXT = "No motion events were detected with the current settings." + + +def scan_summary_text(view: ScanProgressView) -> str: + """One sentence that summarizes a completed scan. Shared by the wizard and scan window.""" + return ( + f"Scan complete: found {len(view.result.event_list)} motion event(s) " + f"in {view.frames_processed} frames " + f"(elapsed {view.elapsed}, {view.rate} FPS)." + ) + + def build_event_table( parent: tk.Widget, input_paths: ty.List[str], event_list: ty.List[MotionEvent] ) -> ttk.Frame: diff --git a/dvr_scan/app/video_list.py b/dvr_scan/app/video_list.py index a31cc7e..43a84d3 100644 --- a/dvr_scan/app/video_list.py +++ b/dvr_scan/app/video_list.py @@ -39,7 +39,7 @@ import tkinter.ttk as ttk import typing as ty -from dvr_scan.app.common import PADDING +from dvr_scan.app.common import BRAND_COLOR, PADDING, Tooltip, blend_color from dvr_scan.app.inputs import ( VideoInfo, ask_video_paths, @@ -90,44 +90,6 @@ class _Row: text_labels: ty.List[tk.Label] -class _Tooltip: - """A minimal hover tooltip, used to label the icon-only toolbar buttons.""" - - def __init__(self, widget: tk.Widget, text: str): - self._widget = widget - self._text = text - self._tip: ty.Optional[tk.Toplevel] = None - widget.bind("", self._show, add="+") - widget.bind("", self._hide, add="+") - widget.bind("", self._hide, add="+") - # Tear down a visible tip if the button is destroyed while hovered. - widget.bind("", self._hide, add="+") - - def _show(self, _event=None): - if self._tip is not None or not self._widget.winfo_exists(): - return - x = self._widget.winfo_rootx() + self._widget.winfo_width() // 2 - y = self._widget.winfo_rooty() + self._widget.winfo_height() + 2 - self._tip = tk.Toplevel(self._widget) - self._tip.wm_overrideredirect(True) - self._tip.wm_geometry(f"+{x}+{y}") - tk.Label( - self._tip, - text=self._text, - justify=tk.LEFT, - background="#ffffe0", - relief=tk.SOLID, - borderwidth=1, - padx=4, - pady=1, - ).pack() - - def _hide(self, _event=None): - if self._tip is not None: - self._tip.destroy() - self._tip = None - - class VideoList: """Scrollable list of input videos with stacked metadata rows and a vertical icon toolbar. Built into `root`, mirroring the `InputArea` API used by the Scan Wizard.""" @@ -148,11 +110,21 @@ def __init__(self, root: tk.Widget, on_add: ty.Optional[ty.Callable[[], None]] = style = ttk.Style() self._bg = style.lookup("TFrame", "background") or "#f0f0f0" self._fg = style.lookup("TLabel", "foreground") or "black" + self._detail_fg = blend_color(root, self._fg, self._bg, 0.72) self._select_bg = style.lookup("Treeview", "selectbackground") or "#0078d7" self._select_fg = style.lookup("Treeview", "selectforeground") or "#ffffff" # Scrollable region: a canvas hosting an inner frame that holds the row widgets. - self._canvas = tk.Canvas(root, background=self._bg, highlightthickness=0) + # `takefocus=True` plus a 1px highlight ring lets keyboard users Tab into the list + # and see focus clearly while navigating rows with Up/Down/Home/End. + self._canvas = tk.Canvas( + root, + background=self._bg, + highlightthickness=1, + highlightbackground=self._bg, + highlightcolor=BRAND_COLOR, + takefocus=True, + ) self._canvas.grid(row=0, column=0, sticky=tk.NSEW) scroll = ttk.Scrollbar(root, orient=tk.VERTICAL, command=self._canvas.yview) scroll.grid(row=0, column=1, sticky=tk.NS) @@ -172,18 +144,23 @@ def __init__(self, root: tk.Widget, on_add: ty.Optional[ty.Callable[[], None]] = ) self._bind_mousewheel(self._canvas) self._bind_mousewheel(self._rows_frame) - # Clicking empty space (not on a row) clears the selection. Row widgets are children - # of the rows frame, but Tk delivers a click only to the widget under the pointer, so - # these fire only for the uncovered area. - self._canvas.bind("", self.clear_selection, add="+") - self._rows_frame.bind("", self.clear_selection, add="+") + # Clicking empty space (not on a row) clears the selection and focuses the list. + # Row widgets are children of the rows frame, but Tk delivers a click only to the + # widget under the pointer, so these fire only for the uncovered area. + self._canvas.bind("", self._on_empty_click, add="+") + self._rows_frame.bind("", self._on_empty_click, add="+") + self._bind_keyboard_navigation() + + # Shared sort menu variables so the toolbar popup and File > Sort stay in sync. + self._sort_field = tk.StringVar(root, value=SORT_FIELDS[0][1]) + self._sort_descending = tk.BooleanVar(root, value=SORT_FIELDS[0][2]) # Vertical icon toolbar: Add / Remove / Up / Down then Sort, so the arrows point the # same direction the selected row moves. toolbar = ttk.Frame(root) toolbar.grid(row=0, column=2, sticky=tk.N, padx=(PADDING, 0)) self._add_button = self._toolbar_button( - toolbar, 0, ADD_GLYPH, "Add videos", self._on_add_clicked + toolbar, 0, ADD_GLYPH, "Add videos (Ctrl+O)", self._on_add_clicked ) self._remove_button = self._toolbar_button( toolbar, 1, REMOVE_GLYPH, "Remove selected (Del)", self.remove_selected @@ -199,10 +176,11 @@ def __init__(self, root: tk.Widget, on_add: ty.Optional[ty.Callable[[], None]] = self._thumbnails = ThumbnailLoader(self._canvas, apply_image=self._apply_thumbnail) self._rows: ty.Dict[str, _Row] = {} self._order: ty.List[str] = [] - # Selected row iids, and the anchor row (last plain-clicked or toggled) that Shift+click - # extends a range from. + # Selected row iids, the anchor row (last plain-clicked or toggled) that Shift+click / + # Shift+arrow extends a range from, and the keyboard cursor row. self._selected: ty.Set[str] = set() self._anchor: ty.Optional[str] = None + self._cursor: ty.Optional[str] = None # Monotonic counter for unique row iids ("row-0", "row-1", ...). Never reset, even on # clear(), so a thumbnail job for a removed row can't collide with a reused iid. self._counter = 0 @@ -213,9 +191,23 @@ def _toolbar_button( ) -> ttk.Button: button = ttk.Button(parent, text=glyph, width=TOOLBAR_BUTTON_WIDTH, command=command) button.grid(row=row, column=0, pady=(0, PADDING)) - _Tooltip(button, tip) + Tooltip(button, tip) return button + def _bind_keyboard_navigation(self): + self._canvas.bind("", lambda _: self._move_selection(-1, extend=False)) + self._canvas.bind("", lambda _: self._move_selection(1, extend=False)) + self._canvas.bind("", lambda _: self._move_selection(-1, extend=True)) + self._canvas.bind("", lambda _: self._move_selection(1, extend=True)) + self._canvas.bind("", lambda _: self._select_boundary(last=False, extend=False)) + self._canvas.bind("", lambda _: self._select_boundary(last=True, extend=False)) + self._canvas.bind("", lambda _: self._select_boundary(last=False, extend=True)) + self._canvas.bind("", lambda _: self._select_boundary(last=True, extend=True)) + + def _on_empty_click(self, _event=None): + self._focus_canvas() + self.clear_selection() + def _bind_mousewheel(self, widget: tk.Widget): widget.bind("", self._on_mousewheel, add="+") @@ -265,8 +257,11 @@ def remove_selected(self): # The auto-selected row also becomes the anchor so a following Shift+click # extends from it, as it would after a plain click. self._anchor = self._order[min(lowest, len(self._order) - 1)] + self._cursor = self._anchor self._selected = {self._anchor} self._paint_selection() + else: + self._cursor = None self._refresh_button_state() def _on_add_clicked(self): @@ -306,6 +301,8 @@ def key(iid: str) -> str: raise ValueError(f"unknown sort column: {col!r}") self._order.sort(key=key, reverse=descending) + self._sort_field.set(col) + self._sort_descending.set(descending) self._regrid() self._refresh_button_state() @@ -317,6 +314,7 @@ def clear(self): self._order.clear() self._selected = set() self._anchor = None + self._cursor = None # Drop pending thumbnail jobs so they don't target deleted rows, then start fresh. self._thumbnails.cancel() self._thumbnails = ThumbnailLoader(self._canvas, apply_image=self._apply_thumbnail) @@ -343,16 +341,16 @@ def _add_row(self, info: VideoInfo): ) detail_one = tk.Label( frame, - text=f"{info.duration} {info.date}", + text=f"{info.duration} \N{MIDDLE DOT} {info.date}", background=self._bg, - foreground=self._fg, + foreground=self._detail_fg, anchor=tk.W, ) detail_two = tk.Label( frame, - text=f"{info.resolution} {info.framerate} FPS", + text=f"{info.resolution} \N{MIDDLE DOT} {info.framerate} FPS", background=self._bg, - foreground=self._fg, + foreground=self._detail_fg, anchor=tk.W, ) name_label.grid(row=0, column=1, sticky=tk.EW) @@ -399,10 +397,15 @@ def _selected_indices(self) -> ty.List[int]: """Sorted display indices (into `_order`) of the selected rows.""" return [index for index, iid in enumerate(self._order) if iid in self._selected] + def _focus_canvas(self): + self._canvas.focus_set() + def _on_click(self, iid: str): """Plain click: select only this row and make it the range anchor.""" + self._focus_canvas() self._selected = {iid} self._anchor = iid + self._cursor = iid self._paint_selection() self._refresh_button_state() @@ -412,6 +415,8 @@ def _on_shift_click(self, iid: str): if self._anchor is None or self._anchor not in self._order: self._on_click(iid) return + self._focus_canvas() + self._cursor = iid first, last = sorted((self._order.index(self._anchor), self._order.index(iid))) self._selected = set(self._order[first : last + 1]) self._paint_selection() @@ -419,24 +424,90 @@ def _on_shift_click(self, iid: str): def _on_toggle_click(self, iid: str): """Ctrl+click (Command+click on macOS): toggle this row and make it the anchor.""" + self._focus_canvas() if iid in self._selected: self._selected.discard(iid) else: self._selected.add(iid) self._anchor = iid + self._cursor = iid self._paint_selection() self._refresh_button_state() + def _move_selection(self, delta: int, extend: bool = False) -> str: + """Keyboard Up/Down handler: move selection (or extend range from anchor with Shift) + by `delta` rows and scroll the target row into view.""" + if not self._order: + return "break" + current = self._cursor if self._cursor in self._order else self._anchor + if current not in self._order: + indices = self._selected_indices() + if indices: + current = self._order[indices[-1 if delta > 0 else 0]] + else: + target_iid = self._order[0 if delta > 0 else -1] + self._on_click(target_iid) + self._scroll_row_into_view(target_iid) + return "break" + curr_idx = self._order.index(current) + target_idx = max(0, min(len(self._order) - 1, curr_idx + delta)) + target_iid = self._order[target_idx] + if extend: + if self._anchor not in self._order: + self._anchor = current + self._cursor = target_iid + first, last = sorted((self._order.index(self._anchor), target_idx)) + self._selected = set(self._order[first : last + 1]) + self._paint_selection() + self._refresh_button_state() + else: + self._on_click(target_iid) + self._scroll_row_into_view(target_iid) + return "break" + + def _select_boundary(self, last: bool, extend: bool = False) -> str: + """Keyboard Home/End handler: jump selection (or extend range) to first/last row.""" + if not self._order: + return "break" + target_idx = len(self._order) - 1 if last else 0 + target_iid = self._order[target_idx] + if extend: + self._on_shift_click(target_iid) + else: + self._on_click(target_iid) + self._scroll_row_into_view(target_iid) + return "break" + + def _scroll_row_into_view(self, iid: str): + """Scroll the canvas vertically if needed so row `iid` is fully visible.""" + row = self._rows.get(iid) + if row is None or not row.frame.winfo_exists(): + return + self._rows_frame.update_idletasks() + total_h = self._rows_frame.winfo_height() + canvas_h = self._canvas.winfo_height() + if total_h <= 0 or canvas_h <= 0 or total_h <= canvas_h: + return + row_top = row.frame.winfo_y() + row_bottom = row_top + row.frame.winfo_height() + view_top, view_bottom = self._canvas.yview() + visible_top = view_top * total_h + visible_bottom = view_bottom * total_h + if row_top < visible_top: + self._canvas.yview_moveto(max(0.0, row_top / total_h)) + elif row_bottom > visible_bottom: + self._canvas.yview_moveto(min(1.0, (row_bottom - canvas_h) / total_h)) + def _paint_selection(self): """Recolor every row to reflect `_selected`.""" for row_iid, row in self._rows.items(): selected = row_iid in self._selected background = self._select_bg if selected else self._bg - foreground = self._select_fg if selected else self._fg for widget in row.selectable: widget.configure(background=background) - for label in row.text_labels: - label.configure(foreground=foreground) + for idx, label in enumerate(row.text_labels): + fg = self._select_fg if selected else (self._fg if idx == 0 else self._detail_fg) + label.configure(foreground=fg) def _on_move_up(self): """Move each selected row up one slot, preserving their relative order. No-op if @@ -452,6 +523,7 @@ def _on_move_up(self): self._order[index - 1], ) self._regrid() + self._scroll_row_into_view(self._order[indices[0] - 1]) self._refresh_button_state() def _on_move_down(self): @@ -466,6 +538,7 @@ def _on_move_down(self): self._order[index + 1], ) self._regrid() + self._scroll_row_into_view(self._order[indices[-1] + 1]) self._refresh_button_state() def _open_sort(self): @@ -476,9 +549,10 @@ def _open_sort(self): def build_sort_menu(self, parent: tk.Misc) -> tk.Menu: """Build a menu that sorts this list: a radio group of `SORT_FIELDS`, then Ascending/Descending. Picking a field applies that field's default direction. - Used for the toolbar's Sort popup and the Scan Wizard's File > Sort menu.""" - field = tk.StringVar(parent, value=SORT_FIELDS[0][1]) - descending = tk.BooleanVar(parent, value=SORT_FIELDS[0][2]) + Used for the toolbar's Sort popup and the Scan Wizard's File > Sort menu; both + menus share the same variables so their checkmarks stay in sync.""" + field = self._sort_field + descending = self._sort_descending def apply(): self.sort_by(field.get(), descending.get()) diff --git a/dvr_scan/app/widgets.py b/dvr_scan/app/widgets.py index 884c76c..de44b56 100644 --- a/dvr_scan/app/widgets.py +++ b/dvr_scan/app/widgets.py @@ -24,25 +24,41 @@ class ColorPicker: def __init__( self, root: tk.Widget, initial_color: str = "#FF0000", padding=PADDING, sticky=tk.EW ): - self._frame = tk.Frame(root) + self._frame = ttk.Frame(root) self._frame.columnconfigure(0, weight=1) - self._frame.columnconfigure(1, weight=1) + self._frame.columnconfigure(1, weight=2) self._frame.rowconfigure(0, weight=1) - self._color = tk.Label(self._frame, bg=initial_color, width=2) - self._color.grid(row=0, column=0, sticky=sticky, padx=(0, padding)) - - def set_color(): - color = tkinter.colorchooser.askcolor(self._color["bg"]) + self._color = tk.Label( + self._frame, + bg=initial_color, + width=3, + relief=tk.SOLID, + borderwidth=1, + cursor="hand2", + ) + self._color.grid(row=0, column=0, sticky=sticky, padx=(0, padding // 2)) + + def set_color(_event=None): + if str(self._set_button["state"]) == str(tk.DISABLED): + return + color = tkinter.colorchooser.askcolor( + self._color["bg"], + title="Select Color", + parent=self._frame.winfo_toplevel(), + ) if color and color[1]: self._color["bg"] = color[1] - self._set_button = tk.Button(self._frame, text="Set Color", command=set_color) - self._set_button.grid(row=0, column=1, sticky=sticky, padx=(padding, 0)) + self._color.bind("", set_color) + self._set_button = ttk.Button(self._frame, text="Set Color...", command=set_color) + self._set_button.grid(row=0, column=1, sticky=sticky, padx=(padding // 2, 0)) self.grid = self._frame.grid def __setitem__(self, key, item): self._set_button[key] = item + if key == "state": + self._color.configure(cursor="" if str(item) == str(tk.DISABLED) else "hand2") def __getitem__(self, key): return self._set_button[key] diff --git a/dvr_scan/app/wizard.py b/dvr_scan/app/wizard.py index 9a3555b..21894b8 100644 --- a/dvr_scan/app/wizard.py +++ b/dvr_scan/app/wizard.py @@ -31,21 +31,26 @@ import dvr_scan import dvr_scan.presets as presets from dvr_scan.app.common import ( + BRAND_COLOR, MAX_THRESHOLD, PADDING, MenuBar, + Tooltip, add_startup_mode_menu, + blend_color, fill_help_menu, register_icon, ) from dvr_scan.app.inputs import handle_drop from dvr_scan.app.region_editor import ACCELERATOR_KEY from dvr_scan.app.scan_window import ( + NO_EVENTS_TEXT, SCAN_SETUP_ERRORS, ScanProgressView, build_event_table, prompt_stop_scan, save_report, + scan_summary_text, show_scan_setup_error, ) from dvr_scan.app.video_list import VideoList @@ -59,13 +64,15 @@ MIN_WIZARD_WIDTH = 780 MIN_WIZARD_HEIGHT = 440 LOGO_SIZE = 200 -# The drop-zone logo and text sit at this opacity at rest and brighten to full while a file -# is dragged over the zone. +# The drop-zone logo sits at this opacity at rest and brightens to full while active. DROP_ZONE_OPACITY = 0.70 DROP_ZONE_ACTIVE_OPACITY = 1.0 -# CTA text color (the logo's dominant slate-blue); blended toward the background to match the -# logo's at-rest opacity. +# CTA text color (the logo's dominant slate-blue); blended at 0.85 rest opacity so 9pt hint +# text still meets WCAG AA (>= 4.5:1) on light gray. DROP_ZONE_TEXT_COLOR = "#474d57" +DROP_ZONE_TEXT_OPACITY = 0.85 +DROP_ZONE_BORDER_OPACITY = 0.45 +DROP_ZONE_MARGIN = 16 MAX_SUMMARY_VIDEOS = 5 # Output modes which run ffmpeg, and the label suffix shown for them when it is missing. FFMPEG_OUTPUT_MODES = frozenset({OutputMode.ENCODE, OutputMode.FFMPEG, OutputMode.COPY}) @@ -94,16 +101,6 @@ def _faded_logo( return PIL.ImageTk.PhotoImage(PIL.Image.alpha_composite(base, logo)) -def _blend(widget: tk.Widget, foreground: str, background: str, opacity: float) -> str: - """Blend `foreground` toward `background` at `opacity` (1.0 = full foreground), returned - as a #rrggbb string. Labels can't be alpha-composited, so this fakes text opacity to - match the faded logo.""" - fg = [channel // 256 for channel in widget.winfo_rgb(foreground)] - bg = [channel // 256 for channel in widget.winfo_rgb(background)] - blended = (int(f * opacity + b * (1.0 - opacity)) for f, b in zip(fg, bg, strict=True)) - return "#{:02x}{:02x}{:02x}".format(*blended) - - class _VideosStep: """Step 1: add input videos. Shows a logo drop zone until videos are added, then swaps to the input list. Doubles as the app's landing screen.""" @@ -130,7 +127,10 @@ def __init__( self._can_accept_drop = can_accept_drop self._on_load_config = on_load_config self._cta_logo = None + self._cta_border = None self._drag_active = False + self._hover_active = False + self._focus_active = False self._input_frame = ttk.Frame(self.frame) # The list's "+" button goes through the same browse path as the drop zone and @@ -138,18 +138,27 @@ def __init__( self.input_area = VideoList(self._input_frame, on_add=on_browse) self._input_frame.grid(row=0, column=0, sticky=tk.NSEW) - background = ttk.Style().lookup("TFrame", "background") or "white" + style = ttk.Style() + background = style.lookup("TFrame", "background") or "white" self._drop_zone = tk.Canvas( - self.frame, background=background, highlightthickness=0, cursor="hand2" + self.frame, + background=background, + highlightthickness=0, + cursor="hand2", + takefocus=True, ) - # At-rest vs. drag-over variants: the logo and text brighten to full opacity while a - # file is dragged over the zone. + # At-rest vs. active variants: the logo, text, and solid slate border brighten on + # hover, keyboard focus, or while a file is dragged over the zone. self._logo = _faded_logo(self._drop_zone, background, DROP_ZONE_OPACITY) self._logo_active = _faded_logo(self._drop_zone, background, DROP_ZONE_ACTIVE_OPACITY) - self._text_color = _blend( - self._drop_zone, DROP_ZONE_TEXT_COLOR, background, DROP_ZONE_OPACITY + self._text_color = blend_color( + self._drop_zone, DROP_ZONE_TEXT_COLOR, background, DROP_ZONE_TEXT_OPACITY ) self._text_color_active = DROP_ZONE_TEXT_COLOR + self._border_color = blend_color( + self._drop_zone, BRAND_COLOR, background, DROP_ZONE_BORDER_OPACITY + ) + self._border_color_active = BRAND_COLOR # The CTA text is a real Label (embedded in the canvas via create_window) rather than # a canvas text item: canvas text uses grayscale anti-aliasing and looks soft, while a # Label renders with the same crisp ClearType as the rest of the UI. @@ -171,8 +180,16 @@ def __init__( foreground=self._text_color, cursor="hand2", ) - for widget in (self._drop_zone, self._cta_label, self._cta_hint): + self._drop_zone_widgets = (self._drop_zone, self._cta_label, self._cta_hint) + for widget in self._drop_zone_widgets: widget.bind("", self._on_drop_zone_click) + widget.bind("", self._sync_hover) + widget.bind("", self._sync_hover) + self._drop_zone.bind("", self._on_drop_zone_click) + self._drop_zone.bind("", self._on_drop_zone_click) + self._drop_zone.bind("", lambda _: self._set_focus_active(True)) + self._drop_zone.bind("", lambda _: self._set_focus_active(False)) + self._drop_zone.bind("", self._on_drop_zone_unmap) self._drop_zone.bind("", lambda _: self._draw_drop_zone()) self._drop_zone.grid(row=0, column=0, sticky=tk.NSEW) @@ -187,32 +204,82 @@ def __init__( self._refresh() def _on_drop_zone_click(self, _event=None): + if self._drop_zone.winfo_exists(): + self._drop_zone.focus_set() if self._on_browse is not None: self._on_browse() + return "break" def _draw_drop_zone(self): canvas = self._drop_zone canvas.delete("all") - center_x = canvas.winfo_width() // 2 - center_y = canvas.winfo_height() // 2 - logo = self._logo_active if self._drag_active else self._logo - self._cta_logo = canvas.create_image(center_x, center_y - 60, image=logo) + width = canvas.winfo_width() + height = canvas.winfo_height() + center_x = width // 2 + center_y = height // 2 + if width > 2 * DROP_ZONE_MARGIN and height > 2 * DROP_ZONE_MARGIN: + self._cta_border = canvas.create_rectangle( + DROP_ZONE_MARGIN, + DROP_ZONE_MARGIN, + width - DROP_ZONE_MARGIN, + height - DROP_ZONE_MARGIN, + ) + else: + self._cta_border = None + self._cta_logo = canvas.create_image(center_x, center_y - 60, image=self._logo) canvas.create_window(center_x, center_y + 76, window=self._cta_label) canvas.create_window(center_x, center_y + 104, window=self._cta_hint) + self._apply_drop_zone_visuals() - def _set_drag_active(self, active: bool): - """Brighten (or restore) the logo/text as a file is dragged over the drop zone.""" - if self._drag_active == active or not self._drop_zone.winfo_exists(): + def _apply_drop_zone_visuals(self): + if not self._drop_zone.winfo_exists(): return - self._drag_active = active + active = self._drag_active or self._hover_active or self._focus_active if self._cta_logo is not None: self._drop_zone.itemconfigure( self._cta_logo, image=self._logo_active if active else self._logo ) + if self._cta_border is not None: + border_color = self._border_color_active if active else self._border_color + self._drop_zone.itemconfigure( + self._cta_border, + outline=border_color, + width=2 if (self._focus_active or self._drag_active) else 1, + ) color = self._text_color_active if active else self._text_color self._cta_label.configure(foreground=color) self._cta_hint.configure(foreground=color) + def _sync_hover(self, _event=None): + if not self._drop_zone.winfo_exists() or not self._drop_zone.winfo_viewable(): + self._set_hover_active(False) + return + px, py = self._drop_zone.winfo_pointerxy() + hovered = self._drop_zone.winfo_containing(px, py) + self._set_hover_active(hovered in self._drop_zone_widgets) + + def _on_drop_zone_unmap(self, _event=None): + self._hover_active = False + self._drag_active = False + self._apply_drop_zone_visuals() + + def _set_hover_active(self, active: bool): + if self._hover_active != active: + self._hover_active = active + self._apply_drop_zone_visuals() + + def _set_focus_active(self, active: bool): + if self._focus_active != active: + self._focus_active = active + self._apply_drop_zone_visuals() + + def _set_drag_active(self, active: bool): + """Brighten (or restore) the logo/text as a file is dragged over the drop zone.""" + if self._drag_active == active or not self._drop_zone.winfo_exists(): + return + self._drag_active = active + self._apply_drop_zone_visuals() + def _on_drag_enter(self, event): if self._can_accept_drop is not None and not self._can_accept_drop(): return event.action @@ -245,6 +312,12 @@ def _refresh(self): else: self._input_frame.grid_remove() self._drop_zone.grid() + try: + focused = self._window.focus_get() + except (KeyError, tk.TclError): + focused = None + if focused is not None and str(focused).startswith(str(self._input_frame)): + self._drop_zone.focus_set() if self._on_state_changed is not None: self._on_state_changed() @@ -300,22 +373,25 @@ def __init__( self.config = presets.load_preset(presets.default_preset()) self.frame.columnconfigure(1, weight=1) + style = ttk.Style() + fg = style.lookup("TLabel", "foreground") or "black" + bg = style.lookup("TFrame", "background") or "#f0f0f0" + hint_fg = blend_color(self.frame, fg, bg, 0.75) - tk.Label(self.frame, text="Preset").grid( + ttk.Label(self.frame, text="Preset").grid( row=0, column=0, sticky=tk.W, padx=PADDING, pady=PADDING ) self._combo = ttk.Combobox(self.frame, state="readonly") self._combo.grid(row=0, column=1, sticky=tk.EW, padx=PADDING, pady=PADDING) self._combo.bind("<>", lambda _: self._on_selected()) - self._preset_desc = tk.Label(self.frame, text="", anchor=tk.W, justify=tk.LEFT) - self._preset_desc.grid( - row=1, column=0, columnspan=2, sticky=tk.W, padx=PADDING, pady=(0, PADDING) + self._preset_desc = ttk.Label( + self.frame, text="", anchor=tk.W, justify=tk.LEFT, foreground=hint_fg ) + self._preset_desc.grid(row=1, column=1, sticky=tk.EW, padx=PADDING, pady=(0, PADDING * 2)) - tk.Label(self.frame, text="Sensitivity Threshold").grid( - row=2, column=0, sticky=tk.W, padx=PADDING, pady=PADDING - ) + threshold_label = ttk.Label(self.frame, text="Sensitivity Threshold") + threshold_label.grid(row=2, column=0, sticky=tk.W, padx=PADDING, pady=PADDING) self._threshold = Spinbox( self.frame, value=str(self.config.get("threshold")), @@ -324,10 +400,27 @@ def __init__( increment=0.01, ) self._threshold.grid(row=2, column=1, sticky=tk.W, padx=PADDING, pady=PADDING) - tk.Label( + Tooltip( + threshold_label, + "Minimum motion score required to trigger an event (0.0 to 255.0; default 0.15).", + ) + self._threshold_hint = ttk.Label( self.frame, - text="Lower values detect smaller amounts of motion.", - ).grid(row=3, column=0, columnspan=2, sticky=tk.W, padx=PADDING) + text="Lower values detect smaller amounts of motion (default: 0.15).", + foreground=hint_fg, + anchor=tk.W, + justify=tk.LEFT, + ) + self._threshold_hint.grid(row=3, column=1, sticky=tk.EW, padx=PADDING) + self.frame.bind( + "", + lambda e: self._update_wrap(max(200, e.width - 180)), + add="+", + ) + + def _update_wrap(self, width: int): + self._preset_desc.configure(wraplength=width) + self._threshold_hint.configure(wraplength=width) @property def preset_name(self) -> str: @@ -432,6 +525,23 @@ class _OutputStep: ("Scan Only (report)", None), ] + _MODE_DESCRIPTIONS: ty.Dict[ty.Optional[OutputMode], str] = { + OutputMode.ENCODE: ( + "Saves each motion event as an MP4 video clip with audio. Works with most players." + ), + OutputMode.OPENCV: ( + "Saves each motion event as an AVI video clip (video only; does not require ffmpeg)." + ), + OutputMode.FFMPEG: ("Re-encodes each event directly from the source file with ffmpeg."), + OutputMode.COPY: ( + "Copies stream data without re-encoding (very fast, but cuts align to keyframes)." + ), + None: ( + "Finds and lists motion events without saving video clips. You can save a CSV or " + "JSON report afterwards." + ), + } + def __init__( self, root: tk.Widget, @@ -441,12 +551,17 @@ def __init__( self.frame = ttk.Frame(root) self.frame.columnconfigure(1, weight=1) self._videos_step = videos_step - # Checked once: it spawns a process. A combobox can't disable single entries, so - # modes which need ffmpeg are labelled as unavailable and rejected by `validate`. + # A combobox can't disable single entries, so modes that need ffmpeg are labelled as + # unavailable when ffmpeg is missing and rejected by `validate`. self._ffmpeg_available = is_ffmpeg_available() self._modes = self.mode_choices(self._ffmpeg_available) - tk.Label(self.frame, text="Mode").grid( + style = ttk.Style() + fg = style.lookup("TLabel", "foreground") or "black" + bg = style.lookup("TFrame", "background") or "#f0f0f0" + hint_fg = blend_color(self.frame, fg, bg, 0.75) + + ttk.Label(self.frame, text="Mode").grid( row=0, column=0, sticky=tk.W, padx=PADDING, pady=PADDING ) self._mode_combo = ttk.Combobox(self.frame, state="readonly") @@ -456,18 +571,30 @@ def __init__( self._mode_combo.bind("<>", lambda _: self._on_mode_changed()) self._mode_combo.grid(row=0, column=1, columnspan=2, sticky=tk.EW, padx=PADDING) + self._mode_desc = ttk.Label( + self.frame, text="", anchor=tk.W, justify=tk.LEFT, foreground=hint_fg + ) + self._mode_desc.grid( + row=1, column=1, columnspan=2, sticky=tk.EW, padx=PADDING, pady=(0, PADDING * 2) + ) + self._directory = "" self._user_selected_dir = False self._directory_label = tk.StringVar(self.frame, value="No Directory Selected") - tk.Label(self.frame, text="Directory").grid( - row=1, column=0, sticky=tk.W, padx=PADDING, pady=PADDING + ttk.Label(self.frame, text="Directory").grid( + row=2, column=0, sticky=tk.W, padx=PADDING, pady=PADDING ) self._dir_entry = ttk.Entry( - self.frame, state=tk.DISABLED, textvariable=self._directory_label + self.frame, state="readonly", textvariable=self._directory_label ) - self._dir_entry.grid(row=1, column=1, sticky=tk.EW, padx=PADDING, pady=PADDING) + self._dir_entry.grid(row=2, column=1, sticky=tk.EW, padx=PADDING, pady=PADDING) self._select_button = ttk.Button(self.frame, text="Select...", command=self._on_select) - self._select_button.grid(row=1, column=2, sticky=tk.EW, padx=PADDING, pady=PADDING) + self._select_button.grid(row=2, column=2, sticky=tk.EW, padx=PADDING, pady=PADDING) + self.frame.bind( + "", + lambda e: self._mode_desc.configure(wraplength=max(200, e.width - 120)), + add="+", + ) if settings is not None: self.sync_from_settings(settings) @@ -494,11 +621,14 @@ def mode_choices( def _on_mode_changed(self): self._mode_combo.selection_clear() + self._mode_desc["text"] = self._MODE_DESCRIPTIONS.get(self.output_mode, "") if self.scan_only: self._select_button["state"] = tk.DISABLED + self._dir_entry["state"] = tk.DISABLED self._directory_label.set("Not used in Scan Only mode") else: self._select_button["state"] = tk.NORMAL + self._dir_entry["state"] = "readonly" self._directory_label.set( self._directory if self._directory else "No Directory Selected" ) @@ -613,43 +743,73 @@ def __init__( self._preset_step = preset_step self._output_step = output_step self._get_overrides = get_overrides - self._summary = tk.Label(self.frame, justify=tk.LEFT, anchor=tk.NW) - self.frame.rowconfigure(0, weight=1) + self._value_labels: ty.List[ttk.Label] = [] + self._rows_container = ttk.Frame(self.frame) + self._rows_container.columnconfigure(1, weight=1) self.frame.columnconfigure(0, weight=1) - self._summary.grid(row=0, column=0, sticky=tk.NSEW, padx=PADDING, pady=PADDING) + self._rows_container.grid(row=0, column=0, sticky=tk.NSEW, padx=PADDING, pady=PADDING) + self.frame.bind("", self._on_configure, add="+") + + def _on_configure(self, event): + wrap = max(220, event.width - 180) + for label in self._value_labels: + if label.winfo_exists(): + label.configure(wraplength=wrap) def on_show(self): # Ensure output step has populated its default directory if the user jumped here. self._output_step.on_show() + for child in self._rows_container.winfo_children(): + child.destroy() + self._value_labels.clear() + videos = self._videos_step.input_area.videos video_names = [Path(video).name for video in videos[:MAX_SUMMARY_VIDEOS]] if len(videos) > MAX_SUMMARY_VIDEOS: video_names.append(f"... and {len(videos) - MAX_SUMMARY_VIDEOS} more") - lines = [ - f"Videos ({len(videos)}):", - *(f" {name}" for name in video_names), - "", - f"Preset: {self._preset_step.preset_name}", - f"Sensitivity Threshold: {self._preset_step.threshold:g}", - "", - f"Output: {self._output_step.mode_label}", + + entries: ty.List[ty.Tuple[str, str]] = [ + (f"Videos ({len(videos)})", "\n".join(video_names) if video_names else "None"), + ("Preset", self._preset_step.preset_name), + ("Sensitivity Threshold", f"{self._preset_step.threshold:g}"), + ("Output Mode", self._output_step.mode_label), ] if not self._output_step.scan_only: - lines.append(f"Directory: {self._output_step.directory}") - lines += self._override_lines() - self._summary["text"] = "\n".join(lines) + entries.append(("Output Directory", self._output_step.directory)) + + override_items = self._override_lines() + if override_items: + entries.append(("From Advanced Mode", "\n".join(override_items))) + + wrap = max(220, self.frame.winfo_width() - 180) + for row_idx, (heading, value) in enumerate(entries): + ttk.Label( + self._rows_container, + text=heading, + font=("TkDefaultFont", 9, "bold"), + anchor=tk.NW, + ).grid(row=row_idx, column=0, sticky=tk.NW, padx=(0, PADDING * 2), pady=(0, PADDING)) + val_label = ttk.Label( + self._rows_container, + text=value, + anchor=tk.NW, + justify=tk.LEFT, + wraplength=wrap, + ) + val_label.grid(row=row_idx, column=1, sticky=tk.EW, pady=(0, PADDING)) + self._value_labels.append(val_label) def _override_lines(self) -> ty.List[str]: overrides = self._get_overrides() if self._get_overrides is not None else {} if not overrides: return [] - lines = ["", "From Advanced Mode:"] + lines = [] if "start-time" in overrides: - lines.append(f" Start Time: {overrides['start-time']}") + lines.append(f"Start Time: {overrides['start-time']}") if "end-time" in overrides: - lines.append(f" End Time: {overrides['end-time']}") + lines.append(f"End Time: {overrides['end-time']}") if "regions" in overrides: - lines.append(f" Regions: {len(overrides['regions'])}") + lines.append(f"Regions: {len(overrides['regions'])}") return lines def validate(self) -> ty.Optional[str]: @@ -741,7 +901,7 @@ def __init__( self._window.rowconfigure(2, weight=1) self._window.columnconfigure(0, weight=1) - self._header = tk.Label(self._window, font=("TkDefaultFont", 12, "bold")) + self._header = ttk.Label(self._window, font=("TkDefaultFont", 12, "bold")) self._header.grid(row=1, column=0, sticky=tk.W, padx=PADDING, pady=PADDING) content = ttk.Frame(self._window) @@ -915,6 +1075,27 @@ def apply_to_advanced(self, motion_window, output_area, scan_area): def show(self): self._window.deiconify() self._window.focus() + self._focus_step_control() + + def _focus_step_control(self): + """Move keyboard focus onto an appropriate control for the visible step so focus + never remains stuck on a hidden step widget.""" + if self._scanning: + self._stop_button.focus_set() + return + if self._step_index == 0: + if self.videos: + self._next_button.focus_set() + else: + self._videos_step._drop_zone.focus_set() + elif self._step_index == 1: + self._preset_step._combo.focus_set() + elif self._step_index == 2: + self._output_step._mode_combo.focus_set() + elif self._step_index == self._summary_index: + self._next_button.focus_set() + elif self._step_index == self._scan_index: + self._new_scan_button.focus_set() def hide(self): self._window.withdraw() @@ -953,6 +1134,7 @@ def _show_step(self, index: int): if index == self._scan_index: return self._show_form_nav() + self._focus_step_control() def _show_form_nav(self): self._stop_button.grid_remove() @@ -991,6 +1173,7 @@ def _show_scanning_nav(self): self._stop_button["state"] = tk.NORMAL self._advanced_button["state"] = tk.DISABLED self._back_button["state"] = tk.DISABLED + self._stop_button.focus_set() def _show_report_nav(self): self._stop_button.grid_remove() @@ -1013,6 +1196,7 @@ def _show_report_nav(self): else: self._save_report_button.grid_remove() self._new_scan_button.grid() + self._new_scan_button.focus_set() def _on_open_output_dir(self): if self._last_output_dir: @@ -1086,6 +1270,8 @@ def _create_menubar(self): self._menubar.frame.grid(row=0, column=0, sticky=tk.EW) self._window.bind("", lambda _: self._browse_videos()) self._window.bind("", lambda _: self._browse_videos()) + self._window.bind("", lambda _: self._on_back()) + self._window.bind("", lambda _: self._on_next()) # Video list shortcuts. On Windows, Tk's <> virtual event also maps to # Ctrl+A; when both match, Tk runs only the physical binding, so the handler fires # once per key press. @@ -1195,17 +1381,22 @@ def _build_report_panel(self, view: ScanProgressView) -> ttk.Frame: panel.rowconfigure(1, weight=1) panel.columnconfigure(0, weight=1) - summary = ( - f"Scan complete: found {len(result.event_list)} motion event(s) " - f"in {view.frames_processed} frames " - f"(elapsed {view.elapsed}, {view.rate} FPS)." - ) - tk.Label(panel, text=summary, anchor=tk.W, justify=tk.LEFT).grid( + ttk.Label(panel, text=scan_summary_text(view), anchor=tk.W, justify=tk.LEFT).grid( row=0, column=0, columnspan=2, sticky=tk.EW, padx=PADDING, pady=PADDING ) - table = build_event_table(panel, view.input_paths, result.event_list) - table.grid(row=1, column=0, columnspan=2, sticky=tk.NSEW, padx=(PADDING, 0)) + if result.event_list: + table = build_event_table(panel, view.input_paths, result.event_list) + table.grid(row=1, column=0, columnspan=2, sticky=tk.NSEW, padx=(PADDING, 0)) + else: + empty_msg = ( + f"{NO_EVENTS_TEXT}\n\n" + "Use < Back to lower the Sensitivity Threshold or choose the " + "High Sensitivity preset, then scan again." + ) + ttk.Label(panel, text=empty_msg, anchor=tk.NW, justify=tk.LEFT).grid( + row=1, column=0, columnspan=2, sticky=tk.NSEW, padx=PADDING, pady=PADDING + ) return panel def _build_stopped_panel(self, view: ScanProgressView) -> ttk.Frame: @@ -1223,10 +1414,10 @@ def _build_error_panel(self, error: Exception) -> ttk.Frame: def _build_message_panel(self, heading: str, body: str) -> ttk.Frame: panel = ttk.Frame(self._scan_step.body) panel.columnconfigure(0, weight=1) - tk.Label(panel, text=heading, font=("TkDefaultFont", 12, "bold"), anchor=tk.W).grid( + ttk.Label(panel, text=heading, font=("TkDefaultFont", 12, "bold"), anchor=tk.W).grid( row=0, column=0, sticky=tk.EW, padx=PADDING, pady=(PADDING, 0) ) - tk.Label(panel, text=body, anchor=tk.W, justify=tk.LEFT).grid( + ttk.Label(panel, text=body, anchor=tk.W, justify=tk.LEFT, wraplength=720).grid( row=1, column=0, sticky=tk.EW, padx=PADDING, pady=PADDING ) return panel diff --git a/tests/test_application.py b/tests/test_application.py index 51ba856..e00875c 100644 --- a/tests/test_application.py +++ b/tests/test_application.py @@ -1024,6 +1024,218 @@ def test_event_table_destroy_cancels_loader_and_releases_video(tk_root, traffic_ assert _bgerrors(tk_root) == "" +# --- Usability & accessibility pass coverage ---------------------------------------------- + + +def test_format_progress_stats_clamps_remaining_and_handles_edge_cases(): + from dvr_scan.app.scan_window import format_progress_stats + + # Normal mid-scan + elapsed, rate, remaining = format_progress_stats(10.0, processed=250, total=500, rate=25.0) + assert elapsed == "00:10" + assert rate == "25.00" + assert remaining == "00:10" + + # VFR / frame-skip overshoot: remaining clamps at 00:00 instead of going negative + elapsed, rate, remaining = format_progress_stats(10.0, processed=550, total=500, rate=55.0) + assert remaining == "00:00" + + # Sub-1 FPS and unknown total + elapsed, rate, remaining = format_progress_stats(4.0, processed=2, total=None, rate=None) + assert rate == "0.50" + assert remaining == "?" + + # Zero elapsed and no rate yet + elapsed, rate, remaining = format_progress_stats(0.0, processed=0, total=100, rate=None) + assert rate == "N/A" + assert remaining == "?" + + +def test_scan_progress_view_tracks_skipped_frames(tk_root, monkeypatch): + from types import SimpleNamespace + + import dvr_scan.app.scan_window as scan_window + + monkeypatch.setattr(scan_window, "init_scanner", lambda _settings: _FakeScanner()) + view = scan_window.ScanProgressView(tk_root, _scan_settings(), lambda: None) + fake_bar = SimpleNamespace( + n=10, + format_dict={"elapsed": 1.0, "n": 10, "total": 20, "rate": 10.0}, + ) + view._on_processed_frame(fake_bar, num_events=2) + assert view.frames_processed == 11 + assert view.num_events == 2 + + +def test_input_area_refresh_remove_state_tracks_selection_and_bounds(): + class _Btn: + def __init__(self): + self.state = "disabled" + + def __setitem__(self, key, value): + assert key == "state" + self.state = value + + area = InputArea.__new__(InputArea) + tree = _SelectableTree(["row-0", "row-1", "row-2"]) + area._videos = tree + area._remove_button = _Btn() + area._up_button = _Btn() + area._down_button = _Btn() + + # Rows present, none selected -> all disabled + area._refresh_remove_state() + assert (area._remove_button.state, area._up_button.state, area._down_button.state) == ( + "disabled", + "disabled", + "disabled", + ) + + # First row selected -> Remove & Move Down enabled, Move Up disabled + tree.selection_set(["row-0"]) + area._refresh_remove_state() + assert (area._remove_button.state, area._up_button.state, area._down_button.state) == ( + "normal", + "disabled", + "normal", + ) + + # Middle row selected -> all enabled + tree.selection_set(["row-1"]) + area._refresh_remove_state() + assert (area._remove_button.state, area._up_button.state, area._down_button.state) == ( + "normal", + "normal", + "normal", + ) + + # Last row selected -> Move Down disabled + tree.selection_set(["row-2"]) + area._refresh_remove_state() + assert (area._remove_button.state, area._up_button.state, area._down_button.state) == ( + "normal", + "normal", + "disabled", + ) + + +def test_input_area_sort_by_framerate_sorts_numerically(): + class _FpsTree: + def __init__(self): + self.order = ["a", "b", "c"] + self.fps = {"a": "120", "b": "4.98241", "c": "29.97"} + + def get_children(self, _parent=""): + return list(self.order) + + def selection(self): + return [] + + def set(self, iid, col): + assert col == "framerate" + return self.fps[iid] + + def move(self, iid, _parent, index): + self.order.remove(iid) + self.order.insert(index, iid) + + area = InputArea.__new__(InputArea) + area._videos = _FpsTree() + area.sort_by("framerate", descending=False) + assert area._videos.order == ["b", "c", "a"] + area.sort_by("framerate", descending=True) + assert area._videos.order == ["a", "c", "b"] + + +def test_start_scan_shows_dialogs_for_empty_list_and_invalid_time_range(monkeypatch): + from types import SimpleNamespace + + from dvr_scan.app.application import Application + + app = Application.__new__(Application) + app._scan_window = None + app._root = "root-win" + warnings = [] + errors = [] + monkeypatch.setattr( + application.tkinter.messagebox, "showwarning", lambda **kw: warnings.append(kw) + ) + monkeypatch.setattr(application.tkinter.messagebox, "showerror", lambda **kw: errors.append(kw)) + + app._input_area = SimpleNamespace(videos=[], start_end_time=None) + app._start_scan() + assert len(warnings) == 1 and warnings[0]["parent"] == "root-win" + + app._input_area = SimpleNamespace( + videos=["a.mp4"], start_end_time=("00:00:05.000", "00:00:02.000") + ) + app._start_scan() + assert len(errors) == 1 and errors[0]["parent"] == "root-win" + + +def test_region_editor_add_region_without_mouse_pos_uses_frame_center(): + from dvr_scan.app.region_editor import RegionEditor + + editor = RegionEditor( + frame=_frame(100, 80, 0), + initial_shapes=SHAPES, + initial_scale=1, + debug_mode=False, + video_path="a.mp4", + save_path=None, + ) + assert editor._curr_mouse_pos is None + editor._draw = lambda: None + editor._add_region() + assert len(list(editor.shapes)) == 2 + added = list(editor.shapes)[-1] + assert added[0] == Point(40, 32) + assert added[2] == Point(60, 48) + + +def test_tooltip_shows_on_focus_and_hides_cleanly(tk_root): + import tkinter as tk + import tkinter.ttk as ttk + + from dvr_scan.app.common import Tooltip + + win = tk.Toplevel(tk_root) + win.deiconify() + frame = ttk.Frame(win) + frame.grid() + btn = ttk.Button(frame, text="+") + btn.grid() + win.update() + + tip = Tooltip(btn, "Add videos") + tip._on_focus_in() + assert tip._tip is not None and tip._tip.winfo_exists() + + # Clicking while hovered hides the tip and does not re-open it on click ``. + tip._on_enter() + tip._hide() + tip._on_focus_in() + assert tip._tip is None + + # Unmapping a hovered/focused parent frame (`grid_remove`) tears down any open tooltip. + tip._on_enter() + assert tip._tip is not None and tip._tip.winfo_exists() + frame.grid_remove() + win.update() + assert tip._tip is None + assert tip._pointer_inside is False + assert _bgerrors(tk_root) == "" + + +def test_gui_cli_parser_leaves_debug_suppressed(): + from dvr_scan.app.__main__ import get_cli_parser + + args = get_cli_parser().parse_args([]) + assert not hasattr(args, "debug") + args_debug = get_cli_parser().parse_args(["--debug"]) + assert args_debug.debug is True + + @pytest.mark.skipif(__import__("os").name != "nt", reason="Custom MenuBar is Windows-only") def test_menubar_switches_open_menu_on_hover(tk_root): import tkinter as tk diff --git a/tests/test_video_list.py b/tests/test_video_list.py index 0fa97e2..e98d2ee 100644 --- a/tests/test_video_list.py +++ b/tests/test_video_list.py @@ -35,6 +35,10 @@ def _list_with(rows: dict, order: list) -> VideoList: area = VideoList.__new__(VideoList) area._rows = rows area._order = order + area._cursor = None + area._canvas = SimpleNamespace(focus_set=lambda: None) + area._sort_field = SimpleNamespace(set=lambda _value: None) + area._sort_descending = SimpleNamespace(set=lambda _value: None) return area @@ -209,6 +213,7 @@ def _selectable_list(count: int) -> VideoList: area.regrids = [] area._regrid = lambda: area.regrids.append(list(area._order)) area._paint_selection = lambda: None + area._scroll_row_into_view = lambda _iid: None area._refresh_button_state = lambda: None return area @@ -606,3 +611,87 @@ def test_first_video_resolution(): assert area.first_video_resolution == (1280, 720) area._rows["b"].info.resolution = "N/A" assert area.first_video_resolution is None + + +# --- Keyboard navigation and shared sort state -------------------------------------------- + + +def test_move_selection_up_and_down_from_unselected_and_clamps(): + area = _selectable_list(3) + + # Down with nothing selected selects the first row. + assert area._move_selection(1) == "break" + assert area._selected == {"r0"} + assert area._anchor == "r0" + + # Down advances one row at a time and clamps at the end. + area._move_selection(1) + assert area._selected == {"r1"} + area._move_selection(1) + assert area._selected == {"r2"} + area._move_selection(1) + assert area._selected == {"r2"} + + # Up moves back and clamps at the start. + area._move_selection(-1) + assert area._selected == {"r1"} + area._move_selection(-1) + assert area._selected == {"r0"} + area._move_selection(-1) + assert area._selected == {"r0"} + + +def test_move_selection_shift_extends_and_contracts_from_anchor(): + area = _selectable_list(4) + area._on_click("r1") + + area._move_selection(1, extend=True) + assert area._selected == {"r1", "r2"} + assert area._anchor == "r1" + + area._move_selection(1, extend=True) + assert area._selected == {"r1", "r2", "r3"} + + # Shift+Up contracts back toward anchor and then extends upward past it. + area._move_selection(-1, extend=True) + assert area._selected == {"r1", "r2"} + area._move_selection(-1, extend=True) + assert area._selected == {"r1"} + area._move_selection(-1, extend=True) + assert area._selected == {"r0", "r1"} + assert area._anchor == "r1" + + +def test_select_boundary_home_and_end_and_shift_extend(): + area = _selectable_list(4) + area._select_boundary(last=True) + assert area._selected == {"r3"} + + area._select_boundary(last=False) + assert area._selected == {"r0"} + + area._on_click("r1") + area._select_boundary(last=True, extend=True) + assert area._selected == {"r1", "r2", "r3"} + area._select_boundary(last=False, extend=True) + assert area._selected == {"r0", "r1"} + + +def test_sort_by_updates_shared_sort_variables(): + area = _selectable_list(2) + + class _Var: + def __init__(self, val): + self.val = val + + def get(self): + return self.val + + def set(self, val): + self.val = val + + area._sort_field = _Var("#0") + area._sort_descending = _Var(True) + area.sort_by("date", descending=False) + assert area._sort_field.get() == "date" + assert area._sort_descending.get() is False diff --git a/tests/test_wizard.py b/tests/test_wizard.py index ba13990..3e5c8ac 100644 --- a/tests/test_wizard.py +++ b/tests/test_wizard.py @@ -500,6 +500,8 @@ def _output_step(ffmpeg_available: bool, mode_index: int = 0, directory: str = " step._directory = directory step._user_selected_dir = bool(directory) step._select_button = {} + step._mode_desc = {} + step._dir_entry = {} step._directory_label = SimpleNamespace(set=lambda _value: None) return step @@ -706,11 +708,9 @@ def test_summary_lists_advanced_mode_overrides(): "regions": [[1], [2]], } assert step._override_lines() == [ - "", - "From Advanced Mode:", - " Start Time: 00:00:02.000", - " End Time: 00:00:05.000", - " Regions: 2", + "Start Time: 00:00:02.000", + "End Time: 00:00:05.000", + "Regions: 2", ] step._get_overrides = lambda: {} assert step._override_lines() == [] @@ -831,3 +831,83 @@ def test_fast_scan_preset_hidden_without_cnt(monkeypatch, cnt_available): names = [preset.name for preset in presets_module.list_available_presets()] assert ("Fast Scan" in names) == cnt_available assert "High Sensitivity" in names and "Low Sensitivity" in names + + +def test_drop_zone_text_meets_wcag_aa_contrast(): + """The 9pt drop-zone hint text at rest must achieve at least 4.5:1 contrast against the + standard light theme background (#f0f0f0) to satisfy WCAG 2.1 AA.""" + from dvr_scan.app.wizard import DROP_ZONE_TEXT_COLOR, DROP_ZONE_TEXT_OPACITY + + bg_rgb = (0xF0, 0xF0, 0xF0) + fg_hex = DROP_ZONE_TEXT_COLOR.lstrip("#") + fg_rgb = (int(fg_hex[0:2], 16), int(fg_hex[2:4], 16), int(fg_hex[4:6], 16)) + blended = tuple( + int(f * DROP_ZONE_TEXT_OPACITY + b * (1.0 - DROP_ZONE_TEXT_OPACITY)) + for f, b in zip(fg_rgb, bg_rgb, strict=True) + ) + + def rel_luminance(rgb): + channels = [] + for channel in rgb: + s = channel / 255.0 + channels.append(s / 12.92 if s <= 0.04045 else ((s + 0.055) / 1.055) ** 2.4) + return 0.2126 * channels[0] + 0.7152 * channels[1] + 0.0722 * channels[2] + + lum_bg = rel_luminance(bg_rgb) + lum_fg = rel_luminance(blended) + lighter, darker = max(lum_bg, lum_fg), min(lum_bg, lum_fg) + contrast_ratio = (lighter + 0.05) / (darker + 0.05) + assert contrast_ratio >= 4.5, f"Expected >= 4.5:1 WCAG AA contrast, got {contrast_ratio:.2f}:1" + + +def test_output_step_updates_mode_description_and_readonly_entry_state(): + step = _output_step(ffmpeg_available=True, mode_index=0, directory="/out") + step._mode_desc = {"text": ""} + step._dir_entry = {"state": "disabled"} + + step._on_mode_changed() + assert "MP4" in step._mode_desc["text"] + assert step._dir_entry["state"] == "readonly" + + # Scan Only disables the directory entry and explains why. + step._mode_combo.current(4) + step._on_mode_changed() + assert "without saving video clips" in step._mode_desc["text"] + assert step._dir_entry["state"] == "disabled" + + +def test_videos_step_drop_zone_uses_solid_border_and_clears_hover_on_unmap(): + import tkinter as tk + + from tkinterdnd2 import TkinterDnD + + from dvr_scan.app.common import BRAND_COLOR + from dvr_scan.app.wizard import _VideosStep + + try: + root = TkinterDnD.Tk() + except tk.TclError as ex: + pytest.skip(f"TkinterDnD is not available: {ex}") + root.withdraw() + try: + win = tk.Toplevel(root) + win.geometry("600x400") + step = _VideosStep(win, win) + step.frame.pack(fill=tk.BOTH, expand=True) + win.update() + + assert step._cta_border is not None + # Never uses dashed lines in either rest or active states. + assert step._drop_zone.itemcget(step._cta_border, "dash") == "" + step._set_focus_active(True) + assert step._drop_zone.itemcget(step._cta_border, "dash") == "" + assert step._drop_zone.itemcget(step._cta_border, "outline") == BRAND_COLOR + + # Unmapping the drop zone resets hover and drag states cleanly. + step._set_hover_active(True) + step._set_drag_active(True) + step._on_drop_zone_unmap() + assert step._hover_active is False + assert step._drag_active is False + finally: + root.destroy()