emmental/emmental/action.py
Anna Schumaker 2b5cdaa197 action: Add an ActionEntry class
This is inspried by the Gio.ActionEntry struct, which I can't figure out
how to get working in Python. I add on a few extra helpful features,
such as:

  - Automatically creating a Gio.SimpleAction
  - Tracking the desired accelerator keys
  - Binding the "enabled" state to a specificed property at construction

Signed-off-by: Anna Schumaker <Anna@NoWheyCreamery.com>
2023-06-09 09:45:58 -04:00

40 lines
1.3 KiB
Python

# Copyright 2023 (c) Anna Schumaker.
"""A custom ActionEntry that works in Python."""
from gi.repository import GObject
from gi.repository import Gio
from gi.repository import Gtk
class ActionEntry(GObject.GObject):
"""Our own AcitionEntry class to make accelerators easier."""
enabled = GObject.Property(type=bool, default=True)
def __init__(self, name: str, func: callable, *accels: tuple[str],
enabled: tuple[GObject.GObject, str] | None = None):
"""Initialize an ActionEntry."""
super().__init__()
for accel in accels:
if not Gtk.accelerator_parse(accel)[0]:
raise ValueError
self.accels = list(accels)
self.func = func
if enabled is not None:
self.enabled = enabled[0].get_property(enabled[1])
enabled[0].bind_property(enabled[1], self, "enabled")
self.action = Gio.SimpleAction(name=name, enabled=self.enabled)
self.action.connect("activate", self.__activate)
self.bind_property("enabled", self.action, "enabled")
def __activate(self, action: Gio.SimpleAction, param) -> None:
self.func()
@property
def name(self) -> str:
"""Get then name of this ActionEntry."""
return self.action.get_name()