| 1 |
# pygobject - Python bindings for the GObject library |
| 2 |
# Copyright (C) 2012 Simon Feltman |
| 3 |
# |
| 4 |
# gi/_signalhelper.py: GObject signal binding decorator object |
| 5 |
# |
| 6 |
# This library is free software; you can redistribute it and/or |
| 7 |
# modify it under the terms of the GNU Lesser General Public |
| 8 |
# License as published by the Free Software Foundation; either |
| 9 |
# version 2.1 of the License, or (at your option) any later version. |
| 10 |
# |
| 11 |
# This library is distributed in the hope that it will be useful, |
| 12 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 14 |
# Lesser General Public License for more details. |
| 15 |
# |
| 16 |
# You should have received a copy of the GNU Lesser General Public |
| 17 |
# License along with this library; if not, see <http://www.gnu.org/licenses/>. |
| 18 |
|
| 19 |
from . import _gi |
| 20 |
|
| 21 |
|
| 22 |
class Signal(str): |
| 23 |
"""Object which gives a nice API for creating and binding signals. |
| 24 |
|
| 25 |
:param name: |
| 26 |
Name of signal or callable closure when used as a decorator. |
| 27 |
:type name: str or callable |
| 28 |
:param callable func: |
| 29 |
Callable closure method. |
| 30 |
:param GObject.SignalFlags flags: |
| 31 |
Flags specifying when to run closure. |
| 32 |
:param type return_type: |
| 33 |
Return type of the Signal. |
| 34 |
:param list arg_types: |
| 35 |
List of argument types specifying the signals function signature |
| 36 |
:param str doc: |
| 37 |
Documentation of signal object. |
| 38 |
:param callable accumulator: |
| 39 |
Accumulator method with the signature: |
| 40 |
func(ihint, return_accu, handler_return, accu_data) -> boolean |
| 41 |
:param object accu_data: |
| 42 |
User data passed to the accumulator. |
| 43 |
|
| 44 |
:Example: |
| 45 |
|
| 46 |
.. code-block:: python |
| 47 |
|
| 48 |
class Spam(GObject.Object): |
| 49 |
velocity = 0 |
| 50 |
|
| 51 |
@GObject.Signal |
| 52 |
def pushed(self): |
| 53 |
self.velocity += 1 |
| 54 |
|
| 55 |
@GObject.Signal(flags=GObject.SignalFlags.RUN_LAST) |
| 56 |
def pulled(self): |
| 57 |
self.velocity -= 1 |
| 58 |
|
| 59 |
stomped = GObject.Signal('stomped', arg_types=(int,)) |
| 60 |
|
| 61 |
@GObject.Signal |
| 62 |
def annotated_signal(self, a:int, b:str): |
| 63 |
"Python3 annotation support for parameter types. |
| 64 |
|
| 65 |
def on_pushed(obj): |
| 66 |
print(obj) |
| 67 |
|
| 68 |
spam = Spam() |
| 69 |
spam.pushed.connect(on_pushed) |
| 70 |
spam.pushed.emit() |
| 71 |
""" |
| 72 |
|
| 73 |
class BoundSignal(str): |
| 74 |
"""Temporary binding object which can be used for connecting signals |
| 75 |
without specifying the signal name string to connect. |
| 76 |
""" |
| 77 |
|
| 78 |
def __new__(cls, name, *args, **kargs): |
| 79 |
return str.__new__(cls, name) |
| 80 |
|
| 81 |
def __init__(self, signal, gobj): |
| 82 |
str.__init__(self) |
| 83 |
self.signal = signal |
| 84 |
self.gobj = gobj |
| 85 |
|
| 86 |
def __repr__(self): |
| 87 |
return f'BoundSignal("{self}")' |
| 88 |
|
| 89 |
def __call__(self, *args, **kargs): |
| 90 |
"""Call the signals closure.""" |
| 91 |
return self.signal.func(self.gobj, *args, **kargs) |
| 92 |
|
| 93 |
def connect(self, callback, *args, **kargs): |
| 94 |
"""Same as GObject.Object.connect except there is no need to specify |
| 95 |
the signal name. |
| 96 |
""" |
| 97 |
return self.gobj.connect(self, callback, *args, **kargs) |
| 98 |
|
| 99 |
def connect_detailed(self, callback, detail, *args, **kargs): |
| 100 |
"""Same as GObject.Object.connect except there is no need to specify |
| 101 |
the signal name. In addition concats "::<detail>" to the signal name |
| 102 |
when connecting; for use with notifications like "notify" when a property |
| 103 |
changes. |
| 104 |
""" |
| 105 |
return self.gobj.connect(self + "::" + detail, callback, *args, **kargs) |
| 106 |
|
| 107 |
def disconnect(self, handler_id): |
| 108 |
"""Same as GObject.Object.disconnect.""" |
| 109 |
self.gobj.disconnect(handler_id) |
| 110 |
|
| 111 |
def emit(self, *args, **kargs): |
| 112 |
"""Same as GObject.Object.emit except there is no need to specify |
| 113 |
the signal name. |
| 114 |
""" |
| 115 |
return self.gobj.emit(str(self), *args, **kargs) |
| 116 |
|
| 117 |
def __new__(cls, name="", *args, **kargs): |
| 118 |
if callable(name): |
| 119 |
name = name.__name__ |
| 120 |
return str.__new__(cls, name) |
| 121 |
|
| 122 |
def __init__( |
| 123 |
self, |
| 124 |
name="", |
| 125 |
func=None, |
| 126 |
flags=_gi.SIGNAL_RUN_FIRST, |
| 127 |
return_type=None, |
| 128 |
arg_types=None, |
| 129 |
doc="", |
| 130 |
accumulator=None, |
| 131 |
accu_data=None, |
| 132 |
): |
| 133 |
if func is None and callable(name): |
| 134 |
func = name |
| 135 |
|
| 136 |
if func and not doc: |
| 137 |
doc = func.__doc__ |
| 138 |
|
| 139 |
str.__init__(self) |
| 140 |
|
| 141 |
if func and not (return_type or arg_types): |
| 142 |
return_type, arg_types = get_signal_annotations(func) |
| 143 |
if arg_types is None: |
| 144 |
arg_types = () |
| 145 |
|
| 146 |
self.func = func |
| 147 |
self.flags = flags |
| 148 |
self.return_type = return_type |
| 149 |
self.arg_types = arg_types |
| 150 |
self.__doc__ = doc |
| 151 |
self.accumulator = accumulator |
| 152 |
self.accu_data = accu_data |
| 153 |
|
| 154 |
def __get__(self, instance, owner=None): |
| 155 |
"""Returns a BoundSignal when accessed on an object instance.""" |
| 156 |
if instance is None: |
| 157 |
return self |
| 158 |
return self.BoundSignal(self, instance) |
| 159 |
|
| 160 |
def __call__(self, obj, *args, **kargs): |
| 161 |
"""Allows for instantiated Signals to be used as a decorator or calling |
| 162 |
of the underlying signal method. |
| 163 |
""" |
| 164 |
# If obj is a GObject, than we call this signal as a closure otherwise |
| 165 |
# it is used as a re-application of a decorator. |
| 166 |
if isinstance(obj, _gi.GObject): |
| 167 |
self.func(obj, *args, **kargs) |
| 168 |
else: |
| 169 |
# If self is already an allocated name, use it otherwise create a new named |
| 170 |
# signal using the closure name as the name. |
| 171 |
name = str(self) if str(self) else obj.__name__ |
| 172 |
# Return a new value of this type since it is based on an immutable string. |
| 173 |
return type(self)( |
| 174 |
name=name, |
| 175 |
func=obj, |
| 176 |
flags=self.flags, |
| 177 |
return_type=self.return_type, |
| 178 |
arg_types=self.arg_types, |
| 179 |
doc=self.__doc__, |
| 180 |
accumulator=self.accumulator, |
| 181 |
accu_data=self.accu_data, |
| 182 |
) |
| 183 |
return None |
| 184 |
|
| 185 |
def copy(self, newName=None): |
| 186 |
"""Returns a renamed copy of the Signal.""" |
| 187 |
return type(self)( |
| 188 |
name=newName, |
| 189 |
func=self.func, |
| 190 |
flags=self.flags, |
| 191 |
return_type=self.return_type, |
| 192 |
arg_types=self.arg_types, |
| 193 |
doc=self.__doc__, |
| 194 |
accumulator=self.accumulator, |
| 195 |
accu_data=self.accu_data, |
| 196 |
) |
| 197 |
|
| 198 |
def get_signal_args(self): |
| 199 |
"""Returns a tuple of: (flags, return_type, arg_types, accumulator, accu_data).""" |
| 200 |
return ( |
| 201 |
self.flags, |
| 202 |
self.return_type, |
| 203 |
self.arg_types, |
| 204 |
self.accumulator, |
| 205 |
self.accu_data, |
| 206 |
) |
| 207 |
|
| 208 |
|
| 209 |
class SignalOverride(Signal): |
| 210 |
"""Specialized sub-class of Signal which can be used as a decorator for overriding |
| 211 |
existing signals on GObjects. |
| 212 |
|
| 213 |
:Example: |
| 214 |
|
| 215 |
.. code-block:: python |
| 216 |
|
| 217 |
class MyWidget(Gtk.Widget): |
| 218 |
@GObject.SignalOverride |
| 219 |
def configure_event(self): |
| 220 |
pass |
| 221 |
""" |
| 222 |
|
| 223 |
def get_signal_args(self): |
| 224 |
"""Returns the string 'override'.""" |
| 225 |
return "override" |
| 226 |
|
| 227 |
|
| 228 |
def get_signal_annotations(func): |
| 229 |
"""Attempt pulling python 3 function annotations off of 'func' for |
| 230 |
use as a signals type information. Returns an ordered nested tuple |
| 231 |
of (return_type, (arg_type1, arg_type2, ...)). If the given function |
| 232 |
does not have annotations then (None, tuple()) is returned. |
| 233 |
""" |
| 234 |
arg_types = () |
| 235 |
return_type = None |
| 236 |
|
| 237 |
if hasattr(func, "__annotations__"): |
| 238 |
# import inspect only when needed because it takes ~10 msec to load |
| 239 |
import inspect |
| 240 |
|
| 241 |
spec = inspect.getfullargspec(func) |
| 242 |
arg_types = tuple( |
| 243 |
spec.annotations[arg] for arg in spec.args if arg in spec.annotations |
| 244 |
) |
| 245 |
if "return" in spec.annotations: |
| 246 |
return_type = spec.annotations["return"] |
| 247 |
|
| 248 |
return return_type, arg_types |
| 249 |
|
| 250 |
|
| 251 |
def install_signals(cls): |
| 252 |
"""Adds Signal instances on a GObject derived class into the '__gsignals__' |
| 253 |
dictionary to be picked up and registered as real GObject signals. |
| 254 |
""" |
| 255 |
gsignals = cls.__dict__.get("__gsignals__", {}) |
| 256 |
newsignals = {} |
| 257 |
for name, signal in cls.__dict__.items(): |
| 258 |
if isinstance(signal, Signal): |
| 259 |
signalName = str(signal) |
| 260 |
# Fixup a signal which is unnamed by using the class variable name. |
| 261 |
# Since Signal is based on string which immutable, |
| 262 |
# we must copy and replace the class variable. |
| 263 |
if not signalName: |
| 264 |
signalName = name |
| 265 |
signal = signal.copy(name) |
| 266 |
setattr(cls, name, signal) |
| 267 |
if signalName in gsignals: |
| 268 |
raise ValueError(f'Signal "{name}" has already been registered.') |
| 269 |
newsignals[signalName] = signal |
| 270 |
gsignals[signalName] = signal.get_signal_args() |
| 271 |
|
| 272 |
cls.__gsignals__ = gsignals |
| 273 |
|
| 274 |
# Setup signal closures by adding the specially named |
| 275 |
# method to the class in the form of "do_<signal_name>". |
| 276 |
for name, signal in newsignals.items(): |
| 277 |
if signal.func is not None: |
| 278 |
funcName = "do_" + name.replace("-", "_") |
| 279 |
if not hasattr(cls, funcName): |
| 280 |
setattr(cls, funcName, signal.func) |