Imported Upstream version 3.18.1
[platform/upstream/pygobject2.git] / gi / overrides / Gdk.py
1 # -*- Mode: Python; py-indent-offset: 4 -*-
2 # vim: tabstop=4 shiftwidth=4 expandtab
3 #
4 # Copyright (C) 2009 Johan Dahlin <johan@gnome.org>
5 #               2010 Simon van der Linden <svdlinden@src.gnome.org>
6 #
7 # This library is free software; you can redistribute it and/or
8 # modify it under the terms of the GNU Lesser General Public
9 # License as published by the Free Software Foundation; either
10 # version 2.1 of the License, or (at your option) any later version.
11 #
12 # This library is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
15 # Lesser General Public License for more details.
16 #
17 # You should have received a copy of the GNU Lesser General Public
18 # License along with this library; if not, write to the Free Software
19 # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301
20 # USA
21
22 import sys
23 import warnings
24
25 from ..overrides import override, strip_boolean_result
26 from ..module import get_introspection_module
27 from gi import PyGIDeprecationWarning
28
29 Gdk = get_introspection_module('Gdk')
30
31 __all__ = []
32
33
34 class Color(Gdk.Color):
35     MAX_VALUE = 65535
36
37     def __init__(self, red, green, blue):
38         Gdk.Color.__init__(self)
39         self.red = red
40         self.green = green
41         self.blue = blue
42
43     def __eq__(self, other):
44         return self.equal(other)
45
46     def __repr__(self):
47         return 'Gdk.Color(red=%d, green=%d, blue=%d)' % (self.red, self.green, self.blue)
48
49     red_float = property(fget=lambda self: self.red / float(self.MAX_VALUE),
50                          fset=lambda self, v: setattr(self, 'red', int(v * self.MAX_VALUE)))
51
52     green_float = property(fget=lambda self: self.green / float(self.MAX_VALUE),
53                            fset=lambda self, v: setattr(self, 'green', int(v * self.MAX_VALUE)))
54
55     blue_float = property(fget=lambda self: self.blue / float(self.MAX_VALUE),
56                           fset=lambda self, v: setattr(self, 'blue', int(v * self.MAX_VALUE)))
57
58     def to_floats(self):
59         """Return (red_float, green_float, blue_float) triple."""
60
61         return (self.red_float, self.green_float, self.blue_float)
62
63     @staticmethod
64     def from_floats(red, green, blue):
65         """Return a new Color object from red/green/blue values from 0.0 to 1.0."""
66
67         return Color(int(red * Color.MAX_VALUE),
68                      int(green * Color.MAX_VALUE),
69                      int(blue * Color.MAX_VALUE))
70
71 Color = override(Color)
72 __all__.append('Color')
73
74 if Gdk._version == '3.0':
75     class RGBA(Gdk.RGBA):
76         def __init__(self, red=1.0, green=1.0, blue=1.0, alpha=1.0):
77             Gdk.RGBA.__init__(self)
78             self.red = red
79             self.green = green
80             self.blue = blue
81             self.alpha = alpha
82
83         def __eq__(self, other):
84             return self.equal(other)
85
86         def __repr__(self):
87             return 'Gdk.RGBA(red=%f, green=%f, blue=%f, alpha=%f)' % (self.red, self.green, self.blue, self.alpha)
88
89         def __iter__(self):
90             """Iterator which allows easy conversion to tuple and list types."""
91
92             yield self.red
93             yield self.green
94             yield self.blue
95             yield self.alpha
96
97         def to_color(self):
98             """Converts this RGBA into a Color instance which excludes alpha."""
99
100             return Color(int(self.red * Color.MAX_VALUE),
101                          int(self.green * Color.MAX_VALUE),
102                          int(self.blue * Color.MAX_VALUE))
103
104         @classmethod
105         def from_color(cls, color):
106             """Returns a new RGBA instance given a Color instance."""
107
108             return cls(color.red_float, color.green_float, color.blue_float)
109
110     RGBA = override(RGBA)
111     __all__.append('RGBA')
112
113 if Gdk._version == '2.0':
114     class Rectangle(Gdk.Rectangle):
115
116         def __init__(self, x, y, width, height):
117             Gdk.Rectangle.__init__(self)
118             self.x = x
119             self.y = y
120             self.width = width
121             self.height = height
122
123         def __repr__(self):
124             return 'Gdk.Rectangle(x=%d, y=%d, width=%d, height=%d)' % (self.x, self.y, self.height, self.width)
125
126     Rectangle = override(Rectangle)
127     __all__.append('Rectangle')
128 else:
129     # Newer GTK+/gobject-introspection (3.17.x) include GdkRectangle in the
130     # typelib. See https://bugzilla.gnome.org/show_bug.cgi?id=748832 and
131     # https://bugzilla.gnome.org/show_bug.cgi?id=748833
132     if not hasattr(Gdk, 'Rectangle'):
133         from gi.repository import cairo as _cairo
134         Rectangle = _cairo.RectangleInt
135
136         __all__.append('Rectangle')
137     else:
138         # https://bugzilla.gnome.org/show_bug.cgi?id=756364
139         # These methods used to be functions, keep aliases for backwards compat
140         rectangle_intersect = Gdk.Rectangle.intersect
141         rectangle_union = Gdk.Rectangle.union
142
143         __all__.append('rectangle_intersect')
144         __all__.append('rectangle_union')
145
146 if Gdk._version == '2.0':
147     class Drawable(Gdk.Drawable):
148         def cairo_create(self):
149             return Gdk.cairo_create(self)
150
151     Drawable = override(Drawable)
152     __all__.append('Drawable')
153 else:
154     class Window(Gdk.Window):
155         def __new__(cls, parent, attributes, attributes_mask):
156             # Gdk.Window had to be made abstract,
157             # this override allows using the standard constructor
158             return Gdk.Window.new(parent, attributes, attributes_mask)
159
160         def __init__(self, parent, attributes, attributes_mask):
161             pass
162
163         def cairo_create(self):
164             return Gdk.cairo_create(self)
165
166     Window = override(Window)
167     __all__.append('Window')
168
169 Gdk.EventType._2BUTTON_PRESS = getattr(Gdk.EventType, "2BUTTON_PRESS")
170 Gdk.EventType._3BUTTON_PRESS = getattr(Gdk.EventType, "3BUTTON_PRESS")
171
172
173 class Event(Gdk.Event):
174     _UNION_MEMBERS = {
175         Gdk.EventType.DELETE: 'any',
176         Gdk.EventType.DESTROY: 'any',
177         Gdk.EventType.EXPOSE: 'expose',
178         Gdk.EventType.MOTION_NOTIFY: 'motion',
179         Gdk.EventType.BUTTON_PRESS: 'button',
180         Gdk.EventType._2BUTTON_PRESS: 'button',
181         Gdk.EventType._3BUTTON_PRESS: 'button',
182         Gdk.EventType.BUTTON_RELEASE: 'button',
183         Gdk.EventType.KEY_PRESS: 'key',
184         Gdk.EventType.KEY_RELEASE: 'key',
185         Gdk.EventType.ENTER_NOTIFY: 'crossing',
186         Gdk.EventType.LEAVE_NOTIFY: 'crossing',
187         Gdk.EventType.FOCUS_CHANGE: 'focus_change',
188         Gdk.EventType.CONFIGURE: 'configure',
189         Gdk.EventType.MAP: 'any',
190         Gdk.EventType.UNMAP: 'any',
191         Gdk.EventType.PROPERTY_NOTIFY: 'property',
192         Gdk.EventType.SELECTION_CLEAR: 'selection',
193         Gdk.EventType.SELECTION_REQUEST: 'selection',
194         Gdk.EventType.SELECTION_NOTIFY: 'selection',
195         Gdk.EventType.PROXIMITY_IN: 'proximity',
196         Gdk.EventType.PROXIMITY_OUT: 'proximity',
197         Gdk.EventType.DRAG_ENTER: 'dnd',
198         Gdk.EventType.DRAG_LEAVE: 'dnd',
199         Gdk.EventType.DRAG_MOTION: 'dnd',
200         Gdk.EventType.DRAG_STATUS: 'dnd',
201         Gdk.EventType.DROP_START: 'dnd',
202         Gdk.EventType.DROP_FINISHED: 'dnd',
203         Gdk.EventType.CLIENT_EVENT: 'client',
204         Gdk.EventType.VISIBILITY_NOTIFY: 'visibility',
205     }
206
207     if Gdk._version == '2.0':
208         _UNION_MEMBERS[Gdk.EventType.NO_EXPOSE] = 'no_expose'
209
210     if hasattr(Gdk.EventType, 'TOUCH_BEGIN'):
211         _UNION_MEMBERS.update(
212             {
213                 Gdk.EventType.TOUCH_BEGIN: 'touch',
214                 Gdk.EventType.TOUCH_UPDATE: 'touch',
215                 Gdk.EventType.TOUCH_END: 'touch',
216                 Gdk.EventType.TOUCH_CANCEL: 'touch',
217             })
218
219     def __getattr__(self, name):
220         real_event = getattr(self, '_UNION_MEMBERS').get(self.type)
221         if real_event:
222             return getattr(getattr(self, real_event), name)
223         else:
224             raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
225
226     def __setattr__(self, name, value):
227         real_event = getattr(self, '_UNION_MEMBERS').get(self.type)
228         if real_event:
229             setattr(getattr(self, real_event), name, value)
230         else:
231             Gdk.Event.__setattr__(self, name, value)
232
233     def __repr__(self):
234         base_repr = Gdk.Event.__repr__(self).strip("><")
235         return "<%s type=%r>" % (base_repr, self.type)
236
237 Event = override(Event)
238 __all__.append('Event')
239
240 # manually bind GdkEvent members to GdkEvent
241
242 modname = globals()['__name__']
243 module = sys.modules[modname]
244
245 # right now we can't get the type_info from the
246 # field info so manually list the class names
247 event_member_classes = ['EventAny',
248                         'EventExpose',
249                         'EventVisibility',
250                         'EventMotion',
251                         'EventButton',
252                         'EventScroll',
253                         'EventKey',
254                         'EventCrossing',
255                         'EventFocus',
256                         'EventConfigure',
257                         'EventProperty',
258                         'EventSelection',
259                         'EventOwnerChange',
260                         'EventProximity',
261                         'EventDND',
262                         'EventWindowState',
263                         'EventSetting',
264                         'EventGrabBroken']
265
266 if Gdk._version == '2.0':
267     event_member_classes.append('EventNoExpose')
268
269 if hasattr(Gdk, 'EventTouch'):
270     event_member_classes.append('EventTouch')
271
272
273 # whitelist all methods that have a success return we want to mask
274 gsuccess_mask_funcs = ['get_state',
275                        'get_axis',
276                        'get_coords',
277                        'get_root_coords']
278
279
280 for event_class in event_member_classes:
281     override_class = type(event_class, (getattr(Gdk, event_class),), {})
282     # add the event methods
283     for method_info in Gdk.Event.__info__.get_methods():
284         name = method_info.get_name()
285         event_method = getattr(Gdk.Event, name)
286         # python2 we need to use the __func__ attr to avoid internal
287         # instance checks
288         event_method = getattr(event_method, '__func__', event_method)
289
290         # use the _gsuccess_mask decorator if this method is whitelisted
291         if name in gsuccess_mask_funcs:
292             event_method = strip_boolean_result(event_method)
293         setattr(override_class, name, event_method)
294
295     setattr(module, event_class, override_class)
296     __all__.append(event_class)
297
298 # end GdkEvent overrides
299
300
301 class DragContext(Gdk.DragContext):
302     def finish(self, success, del_, time):
303         Gtk = get_introspection_module('Gtk')
304         Gtk.drag_finish(self, success, del_, time)
305
306 DragContext = override(DragContext)
307 __all__.append('DragContext')
308
309
310 class Cursor(Gdk.Cursor):
311     def __new__(cls, *args, **kwds):
312         arg_len = len(args)
313         kwd_len = len(kwds)
314         total_len = arg_len + kwd_len
315
316         if total_len == 1:
317             # Since g_object_newv (super.__new__) does not seem valid for
318             # direct use with GdkCursor, we must assume usage of at least
319             # one of the C constructors to be valid.
320             return cls.new(*args, **kwds)
321
322         elif total_len == 2:
323             warnings.warn('Calling "Gdk.Cursor(display, cursor_type)" has been deprecated. '
324                           'Please use Gdk.Cursor.new_for_display(display, cursor_type). '
325                           'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
326                           PyGIDeprecationWarning)
327             return cls.new_for_display(*args, **kwds)
328
329         elif total_len == 4:
330             warnings.warn('Calling "Gdk.Cursor(display, pixbuf, x, y)" has been deprecated. '
331                           'Please use Gdk.Cursor.new_from_pixbuf(display, pixbuf, x, y). '
332                           'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
333                           PyGIDeprecationWarning)
334             return cls.new_from_pixbuf(*args, **kwds)
335
336         elif total_len == 6:
337             if Gdk._version != '2.0':
338                 # pixmaps don't exist in Gdk 3.0
339                 raise ValueError("Wrong number of parameters")
340
341             warnings.warn('Calling "Gdk.Cursor(source, mask, fg, bg, x, y)" has been deprecated. '
342                           'Please use Gdk.Cursor.new_from_pixmap(source, mask, fg, bg, x, y). '
343                           'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
344                           PyGIDeprecationWarning)
345             return cls.new_from_pixmap(*args, **kwds)
346
347         else:
348             raise ValueError("Wrong number of parameters")
349
350
351 Cursor = override(Cursor)
352 __all__.append('Cursor')
353
354 color_parse = strip_boolean_result(Gdk.color_parse)
355 __all__.append('color_parse')
356
357
358 # Note, we cannot override the entire class as Gdk.Atom has no gtype, so just
359 # hack some individual methods
360 def _gdk_atom_str(atom):
361     n = atom.name()
362     if n:
363         return n
364     # fall back to atom index
365     return 'Gdk.Atom<%i>' % hash(atom)
366
367
368 def _gdk_atom_repr(atom):
369     n = atom.name()
370     if n:
371         return 'Gdk.Atom.intern("%s", False)' % n
372     # fall back to atom index
373     return '<Gdk.Atom(%i)>' % hash(atom)
374
375
376 Gdk.Atom.__str__ = _gdk_atom_str
377 Gdk.Atom.__repr__ = _gdk_atom_repr
378
379
380 # constants
381 if Gdk._version >= '3.0':
382     SELECTION_PRIMARY = Gdk.atom_intern('PRIMARY', True)
383     __all__.append('SELECTION_PRIMARY')
384
385     SELECTION_SECONDARY = Gdk.atom_intern('SECONDARY', True)
386     __all__.append('SELECTION_SECONDARY')
387
388     SELECTION_CLIPBOARD = Gdk.atom_intern('CLIPBOARD', True)
389     __all__.append('SELECTION_CLIPBOARD')
390
391     TARGET_BITMAP = Gdk.atom_intern('BITMAP', True)
392     __all__.append('TARGET_BITMAP')
393
394     TARGET_COLORMAP = Gdk.atom_intern('COLORMAP', True)
395     __all__.append('TARGET_COLORMAP')
396
397     TARGET_DRAWABLE = Gdk.atom_intern('DRAWABLE', True)
398     __all__.append('TARGET_DRAWABLE')
399
400     TARGET_PIXMAP = Gdk.atom_intern('PIXMAP', True)
401     __all__.append('TARGET_PIXMAP')
402
403     TARGET_STRING = Gdk.atom_intern('STRING', True)
404     __all__.append('TARGET_STRING')
405
406     SELECTION_TYPE_ATOM = Gdk.atom_intern('ATOM', True)
407     __all__.append('SELECTION_TYPE_ATOM')
408
409     SELECTION_TYPE_BITMAP = Gdk.atom_intern('BITMAP', True)
410     __all__.append('SELECTION_TYPE_BITMAP')
411
412     SELECTION_TYPE_COLORMAP = Gdk.atom_intern('COLORMAP', True)
413     __all__.append('SELECTION_TYPE_COLORMAP')
414
415     SELECTION_TYPE_DRAWABLE = Gdk.atom_intern('DRAWABLE', True)
416     __all__.append('SELECTION_TYPE_DRAWABLE')
417
418     SELECTION_TYPE_INTEGER = Gdk.atom_intern('INTEGER', True)
419     __all__.append('SELECTION_TYPE_INTEGER')
420
421     SELECTION_TYPE_PIXMAP = Gdk.atom_intern('PIXMAP', True)
422     __all__.append('SELECTION_TYPE_PIXMAP')
423
424     SELECTION_TYPE_WINDOW = Gdk.atom_intern('WINDOW', True)
425     __all__.append('SELECTION_TYPE_WINDOW')
426
427     SELECTION_TYPE_STRING = Gdk.atom_intern('STRING', True)
428     __all__.append('SELECTION_TYPE_STRING')
429
430 import sys
431
432 initialized, argv = Gdk.init_check(sys.argv)