# Copyright (c) 2026 Krzysztof Rudnicki """Deciding whether a focus change was driven by the user or by the app. Split out of :mod:`gatelock._scrollable`, which owns the viewport itself. Focus-following scrolling has to answer one question -- "did the user just do something?" -- and getting it wrong is what moves the screen under someone who has touched nothing. The tracker owns only the two facts needed to answer it, so the viewport does not have to carry input bookkeeping alongside its geometry. """ from __future__ import annotations import logging import time import tkinter as tk _logger = logging.getLogger(__name__) # How long after a keypress or click a focus change still counts as the # user's doing. Long enough to cover the focus that follows an event, # short enough not to adopt the next repaint. _USER_INPUT_WINDOW_S = 0.25 class UserIntentTracker: """Records recent user input so focus moves can be attributed to it.""" def __init__(self) -> None: """Start with no recorded input, so nothing counts as user-driven.""" self._last_user_input = 0.0 self._clicked: tk.Misc | None = None def bind(self, targets: list[tk.Misc]) -> None: """Record when the user last pressed a key or a mouse button. Focus-following scrolling is gated on this: the app focuses widgets programmatically on every repaint (and gatelock re-asserts focus from its recovery tick), and a viewport that follows *those* moves the screen under a user who has touched nothing. Args: targets: Widgets to bind on. Bindings are added (``add="+"``) so they never displace the app's own handlers. """ for target in targets: target.bind("", self.note_key, add="+") target.bind("