|
| 1 | +import types |
| 2 | +from typing import Literal |
| 3 | + |
| 4 | +# ----- Base enum class |
| 5 | + |
| 6 | +# We implement a custom enum class that's much simpler than Python's enum.Enum, |
| 7 | +# and simply maps to strings or ints. The enums are classes, so IDE's provide |
| 8 | +# autocompletion, and documenting with Sphinx is easy. That does mean we need a |
| 9 | +# metaclass though. |
| 10 | + |
| 11 | + |
| 12 | +class EnumType(type): |
| 13 | + """Metaclass for enums and flags.""" |
| 14 | + |
| 15 | + def __new__(cls, name, bases, dct): |
| 16 | + # Collect and check fields |
| 17 | + member_map = {} |
| 18 | + for key, val in dct.items(): |
| 19 | + if not key.startswith("_"): |
| 20 | + val = key if val is None else val |
| 21 | + if not isinstance(val, (int, str)): |
| 22 | + raise TypeError("Enum fields must be str or int.") |
| 23 | + member_map[key] = val |
| 24 | + # Some field values may have been updated |
| 25 | + dct.update(member_map) |
| 26 | + # Create class |
| 27 | + klass = super().__new__(cls, name, bases, dct) |
| 28 | + # Attach some fields |
| 29 | + klass.__fields__ = tuple(member_map) |
| 30 | + klass.__members__ = types.MappingProxyType(member_map) # enums.Enum compat |
| 31 | + # Create bound methods |
| 32 | + for name in ["__dir__", "__iter__", "__getitem__", "__setattr__", "__repr__"]: |
| 33 | + setattr(klass, name, types.MethodType(getattr(cls, name), klass)) |
| 34 | + return klass |
| 35 | + |
| 36 | + def __dir__(cls): |
| 37 | + # Support dir(enum). Note that this order matches the definition, but dir() makes it alphabetic. |
| 38 | + return cls.__fields__ |
| 39 | + |
| 40 | + def __iter__(cls): |
| 41 | + # Support list(enum), iterating over the enum, and doing ``x in enum``. |
| 42 | + return iter([getattr(cls, key) for key in cls.__fields__]) |
| 43 | + |
| 44 | + def __getitem__(cls, key): |
| 45 | + # Support enum[key] |
| 46 | + return cls.__dict__[key] |
| 47 | + |
| 48 | + def __repr__(cls): |
| 49 | + if cls is BaseEnum: |
| 50 | + return "<rendercanvas.BaseEnum>" |
| 51 | + pkg = cls.__module__.split(".")[0] |
| 52 | + name = cls.__name__ |
| 53 | + options = [] |
| 54 | + for key in cls.__fields__: |
| 55 | + val = cls[key] |
| 56 | + options.append(f"'{key}' ({val})" if isinstance(val, int) else f"'{val}'") |
| 57 | + return f"<{pkg}.{name} enum with options: {', '.join(options)}>" |
| 58 | + |
| 59 | + def __setattr__(cls, name, value): |
| 60 | + if name.startswith("_"): |
| 61 | + super().__setattr__(name, value) |
| 62 | + else: |
| 63 | + raise RuntimeError("Cannot set values on an enum.") |
| 64 | + |
| 65 | + |
| 66 | +class BaseEnum(metaclass=EnumType): |
| 67 | + """Base class for flags and enums. |
| 68 | +
|
| 69 | + Looks like Python's builtin Enum class, but is simpler; fields are simply ints or strings. |
| 70 | + """ |
| 71 | + |
| 72 | + def __init__(self): |
| 73 | + raise RuntimeError("Cannot instantiate an enum.") |
| 74 | + |
| 75 | + |
| 76 | +# ----- The enums |
| 77 | + |
| 78 | +# The Xxxx(BaseEnum) classes are for Sphynx docs, and maybe discovery in interactive sessions. |
| 79 | +# The XxxxEnum Literals are for type checking, and static autocompletion of string args in funcs that accept an enum. |
| 80 | + |
| 81 | + |
| 82 | +CursorShapeEnum = Literal[ |
| 83 | + "default", |
| 84 | + "text", |
| 85 | + "crosshair", |
| 86 | + "pointer", |
| 87 | + "ew_resize", |
| 88 | + "ns_resize", |
| 89 | + "nesw_resize", |
| 90 | + "nwse_resize", |
| 91 | + "not_allowed", |
| 92 | + "none", |
| 93 | +] |
| 94 | + |
| 95 | + |
| 96 | +class CursorShape(BaseEnum): |
| 97 | + """The CursorShape enum specifies the suppported cursor shapes, following CSS cursor names.""" |
| 98 | + |
| 99 | + default = None #: The platform-dependent default cursor, typically an arrow. |
| 100 | + text = None #: The text input I-beam cursor shape. |
| 101 | + crosshair = None #: |
| 102 | + pointer = None #: The pointing hand cursor shape. |
| 103 | + ew_resize = "ew-resize" #: The horizontal resize/move arrow shape. |
| 104 | + ns_resize = "ns-resize" #: The vertical resize/move arrow shape. |
| 105 | + nesw_resize = ( |
| 106 | + "nesw-resize" #: The top-left to bottom-right diagonal resize/move arrow shape. |
| 107 | + ) |
| 108 | + nwse_resize = ( |
| 109 | + "nwse-resize" #: The top-right to bottom-left diagonal resize/move arrow shape. |
| 110 | + ) |
| 111 | + not_allowed = "not-allowed" #: The operation-not-allowed shape. |
| 112 | + none = "none" #: The cursor is hidden. |
| 113 | + |
| 114 | + |
| 115 | +EventTypeEnum = Literal[ |
| 116 | + "*", |
| 117 | + "resize", |
| 118 | + "close", |
| 119 | + "pointer_down", |
| 120 | + "pointer_up", |
| 121 | + "pointer_move", |
| 122 | + "pointer_enter", |
| 123 | + "pointer_leave", |
| 124 | + "double_click", |
| 125 | + "wheel", |
| 126 | + "key_down", |
| 127 | + "key_up", |
| 128 | + "char", |
| 129 | + "before_draw", |
| 130 | + "animate", |
| 131 | +] |
| 132 | + |
| 133 | + |
| 134 | +class EventType(BaseEnum): |
| 135 | + """The EventType enum specifies the possible events for a RenderCanvas. |
| 136 | +
|
| 137 | + This includes the events from the jupyter_rfb event spec (see |
| 138 | + https://jupyter-rfb.readthedocs.io/en/stable/events.html) plus some |
| 139 | + rendercanvas-specific events. |
| 140 | + """ |
| 141 | + |
| 142 | + # Jupter_rfb spec |
| 143 | + |
| 144 | + resize = None #: The canvas has changed size. Has 'width' and 'height' in logical pixels, 'pixel_ratio'. |
| 145 | + close = None #: The canvas is closed. No additional fields. |
| 146 | + pointer_down = None #: The pointing device is pressed down. Has 'x', 'y', 'button', 'butons', 'modifiers', 'ntouches', 'touches'. |
| 147 | + pointer_up = None #: The pointing device is released. Same fields as pointer_down. Can occur outside of the canvas. |
| 148 | + pointer_move = None #: The pointing device is moved. Same fields as pointer_down. Can occur outside of the canvas if the pointer is currently down. |
| 149 | + pointer_enter = None #: The pointing device is moved into the canvas. |
| 150 | + pointer_leave = None #: The pointing device is moved outside of the canvas (regardless of a button currently being pressed). |
| 151 | + double_click = None #: A double-click / long-tap. This event looks like a pointer event, but without the touches. |
| 152 | + wheel = None #: The mouse-wheel is used (scrolling), or the touchpad/touchscreen is scrolled/pinched. Has 'dx', 'dy', 'x', 'y', 'modifiers'. |
| 153 | + key_down = None #: A key is pressed down. Has 'key', 'modifiers'. |
| 154 | + key_up = None #: A key is released. Has 'key', 'modifiers'. |
| 155 | + |
| 156 | + # Pending for the spec, may become part of key_down/key_up |
| 157 | + char = None #: Experimental |
| 158 | + |
| 159 | + # Our extra events |
| 160 | + |
| 161 | + before_draw = ( |
| 162 | + None #: Event emitted right before a draw is performed. Has no extra fields. |
| 163 | + ) |
| 164 | + animate = None #: Animation event. Has 'step' representing the step size in seconds. This is stable, except when the 'catch_up' field is nonzero. |
| 165 | + |
| 166 | + |
| 167 | +UpdateModeEnum = Literal["manual", "ondemand", "continuous", "fastest"] |
| 168 | + |
| 169 | + |
| 170 | +class UpdateMode(BaseEnum): |
| 171 | + """The UpdateMode enum specifies the different modes to schedule draws for the canvas.""" |
| 172 | + |
| 173 | + manual = None #: Draw events are never scheduled. Draws only happen when you ``canvas.force_draw()``, and maybe when the GUI system issues them (e.g. when resizing). |
| 174 | + ondemand = None #: Draws are only scheduled when ``canvas.request_draw()`` is called when an update is needed. Safes your laptop battery. Honours ``min_fps`` and ``max_fps``. |
| 175 | + continuous = None #: Continuously schedules draw events, honouring ``max_fps``. Calls to ``canvas.request_draw()`` have no effect. |
| 176 | + fastest = None #: Continuously schedules draw events as fast as possible. Gives high FPS (and drains your battery). |
0 commit comments