diff --git a/src/libei/_capi/loader.py b/src/libei/_capi/loader.py index 3e34b48..a3c421b 100644 --- a/src/libei/_capi/loader.py +++ b/src/libei/_capi/loader.py @@ -25,12 +25,18 @@ class LazyLibrary: """A ctypes.CDLL that only opens the library on first real use.""" def __init__(self, soname: str) -> None: + """Remember the soname; nothing is opened until first use.""" self._soname = soname self._lib: ctypes.CDLL | None = None self._load_error: OSError | None = None self._lock = threading.Lock() def _ensure_loaded(self) -> ctypes.CDLL: + """Return the opened library, opening it on first call. + + Raises LibraryNotFoundError on every later call too after a failure: + the failed load is cached rather than retried. + """ # Double-checked: the unlocked read is the fast path taken by every # call after the first, and the repeated check inside the lock is # what makes it safe -- two threads can both fall through the first @@ -91,6 +97,7 @@ def function( cache: dict[str, Any] = {} def call(*args: Any) -> Any: + """Resolve the C function on first call, then pass straight through.""" # Resolution happens here, on first call, not at bind time -- # that is the whole point of this module (see its docstring). bound = cache.get("f") diff --git a/src/libei/_cobject.py b/src/libei/_cobject.py index bf47dd5..fcd33c5 100644 --- a/src/libei/_cobject.py +++ b/src/libei/_cobject.py @@ -66,6 +66,7 @@ class CObject: _instances_lock: ClassVar[threading.RLock] def __init_subclass__(cls, **kwargs: Any) -> None: + """Give each wrapper hierarchy one identity cache, shared by subclasses.""" super().__init_subclass__(**kwargs) # One cache per wrapper *hierarchy*, not per class. Only a root # wrapper class -- one whose only CObject ancestor is CObject @@ -98,6 +99,7 @@ def __init_subclass__(cls, **kwargs: Any) -> None: cls._instances_lock = threading.RLock() def __init__(self, pointer: int, *, _adopt: bool = False) -> None: + """Take a reference on a non-NULL pointer and cache this wrapper for it.""" if not pointer: raise ValueError(f"{type(self).__name__} cannot wrap a NULL pointer") self._pointer = pointer @@ -121,6 +123,7 @@ def __init__(self, pointer: int, *, _adopt: bool = False) -> None: @property def _as_parameter_(self) -> int: + """The raw pointer ctypes passes to C -- an error once it is released.""" if self._pointer == 0: raise RuntimeError( f"{type(self).__name__} has already been released; " @@ -159,6 +162,7 @@ def release(self) -> None: @classmethod def _get_or_create(cls: type[T], pointer: int | None, *, adopt: bool) -> T | None: + """The wrapper already caching this pointer, or a new one; None for NULL.""" if not pointer: return None if not cls._wrappable: @@ -232,6 +236,7 @@ def adopt(cls: type[T], pointer: int | None) -> T | None: return cls._get_or_create(pointer, adopt=True) def __eq__(self, other: object) -> bool: + """Equal when the types match and the wrapped pointers are the same.""" if not isinstance(other, CObject): return NotImplemented if type(self) is not type(other): @@ -245,6 +250,7 @@ def __eq__(self, other: object) -> bool: return self._pointer == other._pointer def __hash__(self) -> int: + """Stable for the object's life: the original pointer, not the live one.""" # Deliberately keyed on _hash_key, not _pointer: release() zeroes # _pointer, and an object whose hash changes mid-life vanishes # from any set or dict it was placed in. Two wrappers can share a diff --git a/src/libei/ei.py b/src/libei/ei.py index 99f9203..6e74814 100644 --- a/src/libei/ei.py +++ b/src/libei/ei.py @@ -67,6 +67,7 @@ def _next_emulating_sequence() -> int: + """The next emulating-event sequence number: 32-bit, and never 0.""" # Masked into uint32 to match the C parameter. libei asks callers to # keep wraparound detection "reasonable"; skipping 0 keeps the value # away from anything that might read as unset. @@ -192,6 +193,8 @@ class KeymapType(enum.IntEnum): class _LogPriority(enum.IntEnum): + """The log levels, as the integers the C library passes to its handler.""" + DEBUG = 10 INFO = 20 WARNING = 30 @@ -329,6 +332,7 @@ class Region(CObject): _unref_func = staticmethod(_capi.libei.region_unref) def __repr__(self) -> str: + """The size and position, as WxH+X+Y.""" w, h = self.dimension x, y = self.position return f"" @@ -510,6 +514,7 @@ class Device(CObject): _unref_func = staticmethod(_capi.libei.device_unref) def __repr__(self) -> str: + """Name, device type and capabilities -- what tells two devices apart.""" caps = "|".join(c.name or str(c.value) for c in self.capabilities) return f"" @@ -692,6 +697,7 @@ class Seat(CObject): _unref_func = staticmethod(_capi.libei.seat_unref) def __repr__(self) -> str: + """The seat's name and capabilities.""" caps = "|".join(c.name or str(c.value) for c in self.capabilities) return f"" @@ -774,6 +780,7 @@ class Ping(CObject): _unref_func = staticmethod(_capi.libei.ping_unref) def __repr__(self) -> str: + """The ping's id, which is all a ping carries.""" return f"" @property @@ -801,6 +808,7 @@ class Event(CObject): _unref_func = staticmethod(_capi.libei.event_unref) def __repr__(self) -> str: + """The event type by name, or the raw value for one we do not model.""" event_type = self.event_type label = event_type.name if isinstance(event_type, EventType) else event_type return f"" @@ -1008,6 +1016,11 @@ def pong(self) -> Ping: def _log_callback(_ei: int, priority: int, message: bytes, _context: int) -> None: + """Forward libei's log lines into the logging module. + + Runs inside a ctypes callback, where an exception is printed to stderr + and then dropped, so every lookup below falls back rather than raising. + """ # Look up the raw int, not _LogPriority(priority): constructing the # enum from an unrecognized value raises ValueError immediately, which # would happen *before* .get()'s default ever gets a chance to apply @@ -1227,6 +1240,7 @@ class Sender(Context): @classmethod def _new(cls) -> int: + """A new sender from the C library, or an error if it returned NULL.""" pointer = _capi.libei.new_sender(c_void_p(None)) if not pointer: raise Error("ei_new_sender() returned NULL") @@ -1250,6 +1264,7 @@ class Receiver(Context): @classmethod def _new(cls) -> int: + """A new receiver from the C library, or an error if it returned NULL.""" pointer = _capi.libei.new_receiver(c_void_p(None)) if not pointer: raise Error("ei_new_receiver() returned NULL") diff --git a/src/libei/eis.py b/src/libei/eis.py index eeb7397..b1cbd25 100644 --- a/src/libei/eis.py +++ b/src/libei/eis.py @@ -159,6 +159,8 @@ class Flag(enum.IntEnum): class _LogPriority(enum.IntEnum): + """The log levels, as the integers libeis passes to its log handler.""" + DEBUG = 10 INFO = 20 WARNING = 30 @@ -456,6 +458,7 @@ class Device(CObject): _unref_func = staticmethod(_capi.libeis.device_unref) def __repr__(self) -> str: + """Name, device type and capabilities -- what tells two devices apart.""" caps = "|".join(c.name or str(c.value) for c in self.capabilities) return f"" @@ -709,6 +712,7 @@ class Seat(CObject): _unref_func = staticmethod(_capi.libeis.seat_unref) def __repr__(self) -> str: + """The seat's name and capabilities.""" caps = "|".join(c.name or str(c.value) for c in self.capabilities) return f"" @@ -770,6 +774,7 @@ class Client(CObject): _unref_func = staticmethod(_capi.libeis.client_unref) def __repr__(self) -> str: + """The client's name and which side of the protocol it is on.""" return f"" @property @@ -840,6 +845,7 @@ class Ping(CObject): _unref_func = staticmethod(_capi.libeis.ping_unref) def __repr__(self) -> str: + """The ping's id, which is all a ping carries.""" return f"" @property @@ -867,6 +873,7 @@ class Event(CObject): _unref_func = staticmethod(_capi.libeis.event_unref) def __repr__(self) -> str: + """The event type by name, or the raw value for one we do not model.""" event_type = self.event_type label = event_type.name if isinstance(event_type, EventType) else event_type return f"" @@ -1079,6 +1086,11 @@ def pong(self) -> Ping: def _log_callback(_eis: int, priority: int, message: bytes, _context: int) -> None: + """Forward libeis's log lines into the logging module. + + The same constraint as ei.py's callback of that name: it runs inside a + ctypes callback, so it falls back rather than raising. + """ # See ei.py's _log_callback: look up the raw int, not # _LogPriority(priority), which would raise ValueError before .get()'s # default could apply -- silently, since this runs inside a ctypes @@ -1208,6 +1220,7 @@ def add_client(self) -> int: @classmethod def _new(cls) -> int: + """A new server from the C library, or an error if it returned NULL.""" pointer = _capi.libeis.new(c_void_p(None)) if not pointer: raise Error("eis_new() returned NULL") diff --git a/src/libei/oeffis.py b/src/libei/oeffis.py index ddaee8e..46da3d9 100644 --- a/src/libei/oeffis.py +++ b/src/libei/oeffis.py @@ -122,6 +122,11 @@ def __init__(self) -> None: self._state = _EventType.NONE def __del__(self) -> None: + """Release the session, closing the EIS fd if nobody claimed it. + + Safe on a half-built object: __init__ can raise before every + attribute exists, and this still runs. + """ # getattr() with defaults rather than plain attribute access: # __init__ raises DisconnectedError when oeffis_new() returns NULL, # and Python still calls __del__ on the half-built object, where diff --git a/src/libei/portal.py b/src/libei/portal.py index ade9780..a4da350 100644 --- a/src/libei/portal.py +++ b/src/libei/portal.py @@ -427,18 +427,21 @@ def on_response( params: Any, *_a: Any, ) -> None: + """Record the first reply and quit the loop; later replies are ignored.""" if result: # both subscriptions may fire; the first reply wins return result["code"], result["results"] = params.unpack() loop.quit() def on_timeout() -> bool: + """Stop the loop and record that it timed out rather than finished.""" nonlocal timed_out timed_out = True loop.quit() return False # one-shot; GLib removes the source when this is False def subscribe(path: str) -> None: + """Subscribe to Response on one path, keeping the handle alive.""" subscriptions.append( connection.signal_subscribe( busname, @@ -685,12 +688,20 @@ def close(self) -> None: self._connection = None def __enter__(self) -> RemoteDesktopSession: + """Return self: entering performs no action of its own.""" return self def __exit__(self, *_exc: Any) -> None: + """Close the session on the way out, whatever happened.""" self.close() def __del__(self) -> None: + """Close the fd only: __del__ can run during interpreter shutdown. + + A synchronous D-Bus round trip there may hang or fail with nothing + left able to report it, so the D-Bus half of close() is deliberately + not attempted. + """ # Deliberately only the fd, not the D-Bus half of close(): __del__ # can run during interpreter shutdown, where a synchronous D-Bus # round trip may hang or fail in ways nothing can report. Closing an @@ -1037,6 +1048,7 @@ def on_signal( params: Any, *_a: Any, ) -> None: + """Record the first matching signal; anything else is logged and dropped.""" if result: # a subscription that outlives its own wait can fire twice return args = params.unpack() @@ -1058,6 +1070,7 @@ def on_signal( loop.quit() def on_timeout() -> bool: + """Stop the loop and record that it timed out rather than finished.""" nonlocal timed_out timed_out = True loop.quit() @@ -1487,12 +1500,15 @@ def close(self) -> None: self._connection = None def __enter__(self) -> InputCaptureSession: + """Return self: entering performs no action of its own.""" return self def __exit__(self, *_exc: Any) -> None: + """Close the session on the way out, whatever happened.""" self.close() def __del__(self) -> None: + """Close the fd only, for the reason RemoteDesktopSession.__del__ gives.""" # See RemoteDesktopSession.__del__ for why this closes only the fd. if getattr(self, "_eis_fd_claimed", True): return