Debian Codegraph @

gi/overrides/Gdk.py

raw
1 # Copyright (C) 2009 Johan Dahlin <[email protected]>
2 # 2010 Simon van der Linden <[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
19 import sys
20 import warnings
21
22 from ..overrides import override, strip_boolean_result
23 from ..module import get_introspection_module
24 from gi import PyGIDeprecationWarning, require_version, get_option
25
26 Gdk = get_introspection_module("Gdk")
27 GDK3 = Gdk._version == "3.0"
28 GDK4 = Gdk._version == "4.0"
29
30 __all__ = []
31
32
33 # https://bugzilla.gnome.org/show_bug.cgi?id=673396
34 try:
35 require_version("GdkX11", Gdk._version)
36 from gi.repository import GdkX11
37
38 GdkX11
39 except (ValueError, ImportError):
40 pass
41
42 if GDK3:
43 # Gdk.Color was deprecated since 3.14 and dropped in Gtk-4.0
44 class Color(Gdk.Color):
45 MAX_VALUE = 65535
46
47 def __init__(self, red, green, blue):
48 Gdk.Color.__init__(self)
49 self.red = red
50 self.green = green
51 self.blue = blue
52
53 def __eq__(self, other):
54 if not isinstance(other, Gdk.Color):
55 return False
56 return self.equal(other)
57
58 # This is required (even when __eq__ is defined) in order
59 # for != operator to work as expected
60 def __ne__(self, other):
61 return not self == other
62
63 def __repr__(self):
64 return f"Gdk.Color(red={self.red}, green={self.green}, blue={self.blue})"
65
66 red_float = property(
67 fget=lambda self: self.red / float(self.MAX_VALUE),
68 fset=lambda self, v: setattr(self, "red", int(v * self.MAX_VALUE)),
69 )
70
71 green_float = property(
72 fget=lambda self: self.green / float(self.MAX_VALUE),
73 fset=lambda self, v: setattr(self, "green", int(v * self.MAX_VALUE)),
74 )
75
76 blue_float = property(
77 fget=lambda self: self.blue / float(self.MAX_VALUE),
78 fset=lambda self, v: setattr(self, "blue", int(v * self.MAX_VALUE)),
79 )
80
81 def to_floats(self):
82 """Return (red_float, green_float, blue_float) triple."""
83 return (self.red_float, self.green_float, self.blue_float)
84
85 @staticmethod
86 def from_floats(red, green, blue):
87 """Return a new Color object from red/green/blue values from 0.0 to 1.0."""
88 return Color(
89 int(red * Color.MAX_VALUE),
90 int(green * Color.MAX_VALUE),
91 int(blue * Color.MAX_VALUE),
92 )
93
94 Color = override(Color)
95 __all__.append("Color")
96
97
98 # Introduced since Gtk-3.0
99 class RGBA(Gdk.RGBA):
100 def __init__(self, red=1.0, green=1.0, blue=1.0, alpha=1.0):
101 Gdk.RGBA.__init__(self)
102 self.red = red
103 self.green = green
104 self.blue = blue
105 self.alpha = alpha
106
107 def __eq__(self, other):
108 if not isinstance(other, Gdk.RGBA):
109 return False
110 return self.equal(other)
111
112 # This is required (even when __eq__ is defined) in order
113 # for != operator to work as expected
114 def __ne__(self, other):
115 return not self == other
116
117 def __repr__(self):
118 return f"Gdk.RGBA(red={self.red:f}, green={self.green:f}, blue={self.blue:f}, alpha={self.alpha:f})"
119
120 def __iter__(self):
121 """Iterator which allows easy conversion to tuple and list types."""
122 yield self.red
123 yield self.green
124 yield self.blue
125 yield self.alpha
126
127 if GDK3:
128
129 def to_color(self):
130 """Converts this RGBA into a Color instance which excludes alpha."""
131 return Color(
132 int(self.red * Color.MAX_VALUE),
133 int(self.green * Color.MAX_VALUE),
134 int(self.blue * Color.MAX_VALUE),
135 )
136
137 @classmethod
138 def from_color(cls, color):
139 """Returns a new RGBA instance given a Color instance."""
140 return cls(color.red_float, color.green_float, color.blue_float)
141
142
143 RGBA = override(RGBA)
144 __all__.append("RGBA")
145
146
147 if GDK3:
148 # Newer GTK/gobject-introspection (3.17.x) include GdkRectangle in the
149 # typelib. See https://bugzilla.gnome.org/show_bug.cgi?id=748832 and
150 # https://bugzilla.gnome.org/show_bug.cgi?id=748833
151 if not hasattr(Gdk, "Rectangle"):
152 from gi.repository import cairo as _cairo
153
154 Rectangle = _cairo.RectangleInt
155
156 __all__.append("Rectangle")
157 else:
158 # https://bugzilla.gnome.org/show_bug.cgi?id=756364
159 # These methods used to be functions, keep aliases for backwards compat
160 rectangle_intersect = Gdk.Rectangle.intersect
161 rectangle_union = Gdk.Rectangle.union
162
163 __all__.append("rectangle_intersect")
164 __all__.append("rectangle_union")
165
166 if GDK3:
167
168 class Window(Gdk.Window):
169 def __new__(cls, parent, attributes, attributes_mask):
170 # Gdk.Window had to be made abstract,
171 # this override allows using the standard constructor
172 return Gdk.Window.new(parent, attributes, attributes_mask)
173
174 def __init__(self, parent, attributes, attributes_mask):
175 pass
176
177 def cairo_create(self):
178 return Gdk.cairo_create(self)
179
180 Window = override(Window)
181 __all__.append("Window")
182
183 if GDK3:
184 Gdk.EventType._2BUTTON_PRESS = getattr(Gdk.EventType, "2BUTTON_PRESS")
185 Gdk.EventType._3BUTTON_PRESS = getattr(Gdk.EventType, "3BUTTON_PRESS")
186
187 class Event(Gdk.Event):
188 _UNION_MEMBERS = {
189 Gdk.EventType.DELETE: "any",
190 Gdk.EventType.DESTROY: "any",
191 Gdk.EventType.MOTION_NOTIFY: "motion",
192 Gdk.EventType.BUTTON_PRESS: "button",
193 Gdk.EventType.BUTTON_RELEASE: "button",
194 Gdk.EventType.KEY_PRESS: "key",
195 Gdk.EventType.KEY_RELEASE: "key",
196 Gdk.EventType.ENTER_NOTIFY: "crossing",
197 Gdk.EventType.LEAVE_NOTIFY: "crossing",
198 Gdk.EventType.FOCUS_CHANGE: "focus_change",
199 Gdk.EventType.CONFIGURE: "configure",
200 Gdk.EventType.PROXIMITY_IN: "proximity",
201 Gdk.EventType.PROXIMITY_OUT: "proximity",
202 Gdk.EventType.DRAG_ENTER: "dnd",
203 Gdk.EventType.DRAG_LEAVE: "dnd",
204 Gdk.EventType.DRAG_MOTION: "dnd",
205 Gdk.EventType.DROP_START: "dnd",
206 Gdk.EventType._2BUTTON_PRESS: "button",
207 Gdk.EventType._3BUTTON_PRESS: "button",
208 Gdk.EventType.PROPERTY_NOTIFY: "property",
209 Gdk.EventType.SELECTION_CLEAR: "selection",
210 Gdk.EventType.SELECTION_REQUEST: "selection",
211 Gdk.EventType.SELECTION_NOTIFY: "selection",
212 Gdk.EventType.DRAG_STATUS: "dnd",
213 Gdk.EventType.DROP_FINISHED: "dnd",
214 Gdk.EventType.CLIENT_EVENT: "client",
215 Gdk.EventType.VISIBILITY_NOTIFY: "visibility",
216 Gdk.EventType.SCROLL: "scroll",
217 Gdk.EventType.EXPOSE: "expose",
218 Gdk.EventType.MAP: "any",
219 Gdk.EventType.UNMAP: "any",
220 }
221
222 if hasattr(Gdk.EventType, "TOUCH_BEGIN"):
223 _UNION_MEMBERS.update(
224 {
225 Gdk.EventType.TOUCH_BEGIN: "touch",
226 Gdk.EventType.TOUCH_UPDATE: "touch",
227 Gdk.EventType.TOUCH_END: "touch",
228 Gdk.EventType.TOUCH_CANCEL: "touch",
229 }
230 )
231
232 def __getattr__(self, name):
233 real_event = getattr(self, "_UNION_MEMBERS").get(self.type)
234 if real_event:
235 return getattr(getattr(self, real_event), name)
236 raise AttributeError(
237 f"'{self.__class__.__name__}' object has no attribute '{name}'"
238 )
239
240 def __setattr__(self, name, value):
241 real_event = getattr(self, "_UNION_MEMBERS").get(self.type)
242 if real_event:
243 setattr(getattr(self, real_event), name, value)
244 else:
245 Gdk.Event.__setattr__(self, name, value)
246
247 def __repr__(self):
248 base_repr = Gdk.Event.__repr__(self).strip("><")
249 return f"<{base_repr} type={self.type!r}>"
250
251 Event = override(Event)
252 __all__.append("Event")
253
254 # manually bind GdkEvent members to GdkEvent
255
256 modname = globals()["__name__"]
257 module = sys.modules[modname]
258
259 # right now we can't get the type_info from the
260 # field info so manually list the class names
261 event_member_classes = [
262 "EventAny",
263 "EventExpose",
264 "EventMotion",
265 "EventButton",
266 "EventScroll",
267 "EventKey",
268 "EventCrossing",
269 "EventFocus",
270 "EventConfigure",
271 "EventProximity",
272 "EventDND",
273 "EventSetting",
274 "EventGrabBroken",
275 "EventVisibility",
276 "EventProperty",
277 "EventSelection",
278 "EventOwnerChange",
279 "EventWindowState",
280 "EventVisibility",
281 ]
282
283 if hasattr(Gdk, "EventTouch"):
284 event_member_classes.append("EventTouch")
285
286 # whitelist all methods that have a success return we want to mask
287 gsuccess_mask_funcs = ["get_state", "get_axis", "get_coords", "get_root_coords"]
288
289 for event_class in event_member_classes:
290 override_class = type(event_class, (getattr(Gdk, event_class),), {})
291 # add the event methods
292 for method_info in Gdk.Event.__info__.get_methods():
293 name = method_info.get_name()
294 event_method = getattr(Gdk.Event, name)
295
296 # use the _gsuccess_mask decorator if this method is whitelisted
297 if name in gsuccess_mask_funcs:
298 event_method = strip_boolean_result(event_method)
299 setattr(override_class, name, event_method)
300
301 setattr(module, event_class, override_class)
302 __all__.append(event_class)
303
304 # end GdkEvent overrides
305
306 class DragContext(Gdk.DragContext):
307 def finish(self, success, del_, time):
308 Gtk = get_introspection_module("Gtk")
309 Gtk.drag_finish(self, success, del_, time)
310
311 DragContext = override(DragContext)
312 __all__.append("DragContext")
313
314 class Cursor(Gdk.Cursor):
315 def __new__(cls, *args, **kwds):
316 arg_len = len(args)
317 kwd_len = len(kwds)
318 total_len = arg_len + kwd_len
319
320 if total_len == 1:
321 # Since g_object_newv (super.__new__) does not seem valid for
322 # direct use with GdkCursor, we must assume usage of at least
323 # one of the C constructors to be valid.
324 return cls.new(*args, **kwds)
325
326 if total_len == 2:
327 warnings.warn(
328 'Calling "Gdk.Cursor(display, cursor_type)" has been deprecated. '
329 "Please use Gdk.Cursor.new_for_display(display, cursor_type). "
330 "See: https://pygobject.gnome.org/devguide/initializer_deprecations.html",
331 PyGIDeprecationWarning,
332 )
333 return cls.new_for_display(*args, **kwds)
334
335 if total_len == 4:
336 warnings.warn(
337 'Calling "Gdk.Cursor(display, pixbuf, x, y)" has been deprecated. '
338 "Please use Gdk.Cursor.new_from_pixbuf(display, pixbuf, x, y). "
339 "See: https://pygobject.gnome.org/devguide/initializer_deprecations.html",
340 PyGIDeprecationWarning,
341 )
342 return cls.new_from_pixbuf(*args, **kwds)
343
344 raise ValueError("Wrong number of parameters")
345
346 Cursor = override(Cursor)
347 __all__.append("Cursor")
348
349 # Gdk.Color was deprecated since 3.14 and dropped in Gtk-4.0
350 color_parse = strip_boolean_result(Gdk.color_parse)
351 __all__.append("color_parse")
352
353 # Note, we cannot override the entire class as Gdk.Atom has no gtype, so just
354 # hack some individual methods
355 def _gdk_atom_str(atom):
356 n = atom.name()
357 if n:
358 return n
359 # fall back to atom index
360 return f"Gdk.Atom<{hash(atom):d}>"
361
362 def _gdk_atom_repr(atom):
363 n = atom.name()
364 if n:
365 return f'Gdk.Atom.intern("{n}", False)'
366 # fall back to atom index
367 return f"<Gdk.Atom({hash(atom):d})>"
368
369 Gdk.Atom.__str__ = _gdk_atom_str
370 Gdk.Atom.__repr__ = _gdk_atom_repr
371
372
373 if GDK4:
374 from gi.repository import Gio
375
376 class FileList(Gdk.FileList):
377 if hasattr(Gdk.FileList, "new_from_list"):
378
379 def __new__(cls, files):
380 files_list = []
381 if isinstance(files, (tuple, list)):
382 for f in files:
383 if isinstance(f, Gio.File):
384 files_list.append(f)
385 else:
386 raise TypeError(
387 "Constructor requires a list or tuple of Gio.File instances"
388 )
389 else:
390 raise TypeError(
391 "Constructor requires a list or tuple of Gio.File instances"
392 )
393 return Gdk.FileList.new_from_list(files)
394
395 def __iter__(self):
396 return iter(self.get_files())
397
398 def __len__(self):
399 return len(self.get_files())
400
401 def __getitem__(self, index):
402 return self.get_files()[index]
403
404 FileList = override(FileList)
405 __all__.append("FileList")
406
407
408 # constants
409 if GDK3:
410 SELECTION_PRIMARY = Gdk.atom_intern("PRIMARY", True)
411 __all__.append("SELECTION_PRIMARY")
412
413 SELECTION_SECONDARY = Gdk.atom_intern("SECONDARY", True)
414 __all__.append("SELECTION_SECONDARY")
415
416 SELECTION_CLIPBOARD = Gdk.atom_intern("CLIPBOARD", True)
417 __all__.append("SELECTION_CLIPBOARD")
418
419 TARGET_BITMAP = Gdk.atom_intern("BITMAP", True)
420 __all__.append("TARGET_BITMAP")
421
422 TARGET_COLORMAP = Gdk.atom_intern("COLORMAP", True)
423 __all__.append("TARGET_COLORMAP")
424
425 TARGET_DRAWABLE = Gdk.atom_intern("DRAWABLE", True)
426 __all__.append("TARGET_DRAWABLE")
427
428 TARGET_PIXMAP = Gdk.atom_intern("PIXMAP", True)
429 __all__.append("TARGET_PIXMAP")
430
431 TARGET_STRING = Gdk.atom_intern("STRING", True)
432 __all__.append("TARGET_STRING")
433
434 SELECTION_TYPE_ATOM = Gdk.atom_intern("ATOM", True)
435 __all__.append("SELECTION_TYPE_ATOM")
436
437 SELECTION_TYPE_BITMAP = Gdk.atom_intern("BITMAP", True)
438 __all__.append("SELECTION_TYPE_BITMAP")
439
440 SELECTION_TYPE_COLORMAP = Gdk.atom_intern("COLORMAP", True)
441 __all__.append("SELECTION_TYPE_COLORMAP")
442
443 SELECTION_TYPE_DRAWABLE = Gdk.atom_intern("DRAWABLE", True)
444 __all__.append("SELECTION_TYPE_DRAWABLE")
445
446 SELECTION_TYPE_INTEGER = Gdk.atom_intern("INTEGER", True)
447 __all__.append("SELECTION_TYPE_INTEGER")
448
449 SELECTION_TYPE_PIXMAP = Gdk.atom_intern("PIXMAP", True)
450 __all__.append("SELECTION_TYPE_PIXMAP")
451
452 SELECTION_TYPE_WINDOW = Gdk.atom_intern("WINDOW", True)
453 __all__.append("SELECTION_TYPE_WINDOW")
454
455 SELECTION_TYPE_STRING = Gdk.atom_intern("STRING", True)
456 __all__.append("SELECTION_TYPE_STRING")
457
458
459 if GDK4 and not hasattr(Gdk.PaintableFlags, "SIZE"):
460 Gdk.PaintableFlags.SIZE = getattr(Gdk.PaintableFlags, "STATIC_SIZE")
461 Gdk.PaintableFlags.CONTENTS = getattr(Gdk.PaintableFlags, "STATIC_CONTENTS")
462
463
464 if GDK3 and get_option("legacy_autoinit"):
465 import sys
466
467 initialized, argv = Gdk.init_check(sys.argv)