| 1 |
# |
| 2 |
# Copyright (C) 2015 Dustin Spicuzza <[email protected]> |
| 3 |
# |
| 4 |
# This library is free software; you can redistribute it and/or |
| 5 |
# modify it under the terms of the GNU Lesser General Public |
| 6 |
# License as published by the Free Software Foundation; either |
| 7 |
# version 2.1 of the License, or (at your option) any later version. |
| 8 |
# |
| 9 |
# This library is distributed in the hope that it will be useful, |
| 10 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 12 |
# Lesser General Public License for more details. |
| 13 |
# |
| 14 |
# You should have received a copy of the GNU Lesser General Public |
| 15 |
# License along with this library; if not, write to the Free Software |
| 16 |
# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 |
| 17 |
# USA |
| 18 |
from os.path import abspath, join |
| 19 |
|
| 20 |
import inspect |
| 21 |
import warnings |
| 22 |
import sys |
| 23 |
|
| 24 |
from gi.repository import Gio |
| 25 |
from gi.repository import GLib |
| 26 |
from gi.repository import GObject |
| 27 |
from gi.repository import Gtk |
| 28 |
|
| 29 |
from xlgui import guiutil |
| 30 |
|
| 31 |
__all__ = ['GtkTemplate'] |
| 32 |
|
| 33 |
|
| 34 |
class GtkTemplateWarning(UserWarning): |
| 35 |
pass |
| 36 |
|
| 37 |
|
| 38 |
def _connect_func(builder, obj, signal_name, handler_name, connect_object, flags, cls): |
| 39 |
'''Handles GtkBuilder signal connect events''' |
| 40 |
|
| 41 |
if connect_object is None: |
| 42 |
extra = () |
| 43 |
else: |
| 44 |
extra = (connect_object,) |
| 45 |
|
| 46 |
# The handler name refers to an attribute on the template instance, |
| 47 |
# so ask GtkBuilder for the template instance |
| 48 |
template_inst = builder.get_object(cls.__gtype_name__) |
| 49 |
|
| 50 |
if template_inst is None: # This should never happen |
| 51 |
errmsg = ( |
| 52 |
"Internal error: cannot find template instance! obj: %s; " |
| 53 |
"signal: %s; handler: %s; connect_obj: %s; class: %s" |
| 54 |
% (obj, signal_name, handler_name, connect_object, cls) |
| 55 |
) |
| 56 |
warnings.warn(errmsg, GtkTemplateWarning) |
| 57 |
return |
| 58 |
|
| 59 |
handler = getattr(template_inst, handler_name) |
| 60 |
|
| 61 |
if flags == GObject.ConnectFlags.AFTER: |
| 62 |
obj.connect_after(signal_name, handler, *extra) |
| 63 |
else: |
| 64 |
obj.connect(signal_name, handler, *extra) |
| 65 |
|
| 66 |
template_inst.__connected_template_signals__.add(handler_name) |
| 67 |
|
| 68 |
|
| 69 |
def _register_template(cls, template_bytes): |
| 70 |
'''Registers the template for the widget and hooks init_template''' |
| 71 |
|
| 72 |
# This implementation won't work if there are nested templates, but |
| 73 |
# we can't do that anyways due to PyGObject limitations so it's ok |
| 74 |
|
| 75 |
cls.set_template(template_bytes) |
| 76 |
|
| 77 |
bound_methods = set() |
| 78 |
bound_widgets = set() |
| 79 |
|
| 80 |
# Walk the class, find marked callbacks and child attributes |
| 81 |
for name in dir(cls): |
| 82 |
o = getattr(cls, name, None) |
| 83 |
|
| 84 |
if inspect.ismethod(o): |
| 85 |
if hasattr(o, '_gtk_callback'): |
| 86 |
bound_methods.add(name) |
| 87 |
# Don't need to call this, as connect_func always gets called |
| 88 |
# cls.bind_template_callback_full(name, o) |
| 89 |
elif isinstance(o, _Child): |
| 90 |
cls.bind_template_child_full(name, True, 0) |
| 91 |
bound_widgets.add(name) |
| 92 |
|
| 93 |
# Have to setup a special connect function to connect at template init |
| 94 |
# because the methods are not bound yet |
| 95 |
cls.set_connect_func(_connect_func, cls) |
| 96 |
|
| 97 |
cls.__gtemplate_methods__ = bound_methods |
| 98 |
cls.__gtemplate_widgets__ = bound_widgets |
| 99 |
|
| 100 |
base_init_template = cls.init_template |
| 101 |
cls.init_template = lambda s: _init_template(s, cls, base_init_template) |
| 102 |
|
| 103 |
|
| 104 |
def _init_template(self, cls, base_init_template): |
| 105 |
'''This would be better as an override for Gtk.Widget''' |
| 106 |
|
| 107 |
# TODO: could disallow using a metaclass.. but this is good enough |
| 108 |
# .. if you disagree, feel free to fix it and issue a PR :) |
| 109 |
if self.__class__ is not cls: |
| 110 |
raise TypeError( |
| 111 |
"Inheritance from classes with @GtkTemplate decorators " |
| 112 |
"is not allowed at this time" |
| 113 |
) |
| 114 |
|
| 115 |
connected_signals = set() |
| 116 |
self.__connected_template_signals__ = connected_signals |
| 117 |
|
| 118 |
base_init_template(self) |
| 119 |
|
| 120 |
for name in self.__gtemplate_widgets__: |
| 121 |
widget = self.get_template_child(cls, name) |
| 122 |
self.__dict__[name] = widget |
| 123 |
|
| 124 |
if widget is None: |
| 125 |
# Bug: if you bind a template child, and one of them was |
| 126 |
# not present, then the whole template is broken (and |
| 127 |
# it's not currently possible for us to know which |
| 128 |
# one is broken either -- but the stderr should show |
| 129 |
# something useful with a Gtk-CRITICAL message) |
| 130 |
raise AttributeError( |
| 131 |
"A missing child widget was set using " |
| 132 |
"GtkTemplate.Child and the entire " |
| 133 |
"template is now broken (widgets: %s)" |
| 134 |
% ', '.join(self.__gtemplate_widgets__) |
| 135 |
) |
| 136 |
|
| 137 |
for name in self.__gtemplate_methods__.difference(connected_signals): |
| 138 |
errmsg = ( |
| 139 |
"Signal '%s' was declared with @GtkTemplate.Callback " |
| 140 |
+ "but was not present in template" |
| 141 |
) % name |
| 142 |
warnings.warn(errmsg, GtkTemplateWarning) |
| 143 |
|
| 144 |
|
| 145 |
# TODO: Make it easier for IDE to introspect this |
| 146 |
class _Child: |
| 147 |
""" |
| 148 |
Assign this to an attribute in your class definition and it will |
| 149 |
be replaced with a widget defined in the UI file when init_template |
| 150 |
is called |
| 151 |
""" |
| 152 |
|
| 153 |
__slots__ = [] |
| 154 |
|
| 155 |
@staticmethod |
| 156 |
def widgets(count): |
| 157 |
''' |
| 158 |
Allows declaring multiple widgets with less typing:: |
| 159 |
|
| 160 |
button \ |
| 161 |
label1 \ |
| 162 |
label2 = GtkTemplate.Child.widgets(3) |
| 163 |
''' |
| 164 |
return [_Child() for _ in range(count)] |
| 165 |
|
| 166 |
|
| 167 |
class _GtkTemplate: |
| 168 |
""" |
| 169 |
Use this class decorator to signify that a class is a composite |
| 170 |
widget which will receive widgets and connect to signals as |
| 171 |
defined in a UI template. You must call init_template to |
| 172 |
cause the widgets/signals to be initialized from the template:: |
| 173 |
|
| 174 |
@GtkTemplate(ui='foo.ui') |
| 175 |
class Foo(Gtk.Box): |
| 176 |
|
| 177 |
def __init__(self): |
| 178 |
super(Foo, self).__init__() |
| 179 |
self.init_template() |
| 180 |
|
| 181 |
The 'ui' parameter can either be a file path or a GResource resource |
| 182 |
path:: |
| 183 |
|
| 184 |
@GtkTemplate(ui='/org/example/foo.ui') |
| 185 |
class Foo(Gtk.Box): |
| 186 |
pass |
| 187 |
|
| 188 |
To connect a signal to a method on your instance, do:: |
| 189 |
|
| 190 |
@GtkTemplate.Callback |
| 191 |
def on_thing_happened(self, widget): |
| 192 |
pass |
| 193 |
|
| 194 |
To create a child attribute that is retrieved from your template, |
| 195 |
add this to your class definition:: |
| 196 |
|
| 197 |
@GtkTemplate(ui='foo.ui') |
| 198 |
class Foo(Gtk.Box): |
| 199 |
|
| 200 |
widget = GtkTemplate.Child() |
| 201 |
|
| 202 |
|
| 203 |
Note: This is implemented as a class decorator, but if it were |
| 204 |
included with PyGI I suspect it might be better to do this |
| 205 |
in the GObject metaclass (or similar) so that init_template |
| 206 |
can be called automatically instead of forcing the user to do it. |
| 207 |
|
| 208 |
.. note:: Due to limitations in PyGObject, you may not inherit from |
| 209 |
python objects that use the GtkTemplate decorator. |
| 210 |
""" |
| 211 |
|
| 212 |
__ui_path__ = None |
| 213 |
|
| 214 |
@staticmethod |
| 215 |
def Callback(f): |
| 216 |
""" |
| 217 |
Decorator that designates a method to be attached to a signal from |
| 218 |
the template |
| 219 |
""" |
| 220 |
f._gtk_callback = True |
| 221 |
return f |
| 222 |
|
| 223 |
Child = _Child |
| 224 |
|
| 225 |
@staticmethod |
| 226 |
def set_ui_path(*path): |
| 227 |
""" |
| 228 |
If using file paths instead of resources, call this *before* |
| 229 |
loading anything that uses GtkTemplate, or it will fail to load |
| 230 |
your template file |
| 231 |
|
| 232 |
:param path: one or more path elements, will be joined together |
| 233 |
to create the final path |
| 234 |
|
| 235 |
TODO: Alternatively, could wait until first class instantiation |
| 236 |
before registering templates? Would need a metaclass... |
| 237 |
""" |
| 238 |
_GtkTemplate.__ui_path__ = abspath(join(*path)) |
| 239 |
|
| 240 |
def __init__(self, ui): |
| 241 |
self.ui = ui |
| 242 |
|
| 243 |
def __call__(self, cls): |
| 244 |
if not issubclass(cls, Gtk.Widget): |
| 245 |
raise TypeError("Can only use @GtkTemplate on Widgets") |
| 246 |
|
| 247 |
# Nested templates don't work |
| 248 |
if hasattr(cls, '__gtemplate_methods__'): |
| 249 |
raise TypeError("Cannot nest template classes") |
| 250 |
|
| 251 |
# Load the template either from a resource path or a file |
| 252 |
# - Prefer the resource path first |
| 253 |
|
| 254 |
try: |
| 255 |
template_bytes = Gio.resources_lookup_data( |
| 256 |
self.ui, Gio.ResourceLookupFlags.NONE |
| 257 |
) |
| 258 |
except GLib.Error: |
| 259 |
ui = self.ui |
| 260 |
if isinstance(ui, (list, tuple)): |
| 261 |
ui = join(ui) |
| 262 |
|
| 263 |
if _GtkTemplate.__ui_path__ is not None: |
| 264 |
ui = join(_GtkTemplate.__ui_path__, ui) |
| 265 |
|
| 266 |
with open(ui, 'rb') as fp: |
| 267 |
template_bytes = GLib.Bytes.new(fp.read()) |
| 268 |
|
| 269 |
if sys.platform == 'win32': |
| 270 |
string = template_bytes.get_data().decode("utf-8") |
| 271 |
template = guiutil.get_template_translated(string) |
| 272 |
template_bytes = template.encode('utf-8') |
| 273 |
template_bytes = GLib.Bytes.new(template_bytes) |
| 274 |
|
| 275 |
_register_template(cls, template_bytes) |
| 276 |
return cls |
| 277 |
|
| 278 |
|
| 279 |
# Future shim support if this makes it into PyGI? |
| 280 |
# if hasattr(Gtk, 'GtkTemplate'): |
| 281 |
# GtkTemplate = lambda c: c |
| 282 |
# else: |
| 283 |
GtkTemplate = _GtkTemplate |