d9797465b4234e1f09a963d13b6c5374241dc8d8
[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.Color(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     from gi.repository import cairo as _cairo
130     Rectangle = _cairo.RectangleInt
131
132     __all__.append('Rectangle')
133
134 if Gdk._version == '2.0':
135     class Drawable(Gdk.Drawable):
136         def cairo_create(self):
137             return Gdk.cairo_create(self)
138
139     Drawable = override(Drawable)
140     __all__.append('Drawable')
141 else:
142     class Window(Gdk.Window):
143         def __new__(cls, parent, attributes, attributes_mask):
144             # Gdk.Window had to be made abstract,
145             # this override allows using the standard constructor
146             return Gdk.Window.new(parent, attributes, attributes_mask)
147
148         def __init__(self, parent, attributes, attributes_mask):
149             pass
150
151         def cairo_create(self):
152             return Gdk.cairo_create(self)
153
154     Window = override(Window)
155     __all__.append('Window')
156
157 Gdk.EventType._2BUTTON_PRESS = getattr(Gdk.EventType, "2BUTTON_PRESS")
158 Gdk.EventType._3BUTTON_PRESS = getattr(Gdk.EventType, "3BUTTON_PRESS")
159
160
161 class Event(Gdk.Event):
162     _UNION_MEMBERS = {
163         Gdk.EventType.DELETE: 'any',
164         Gdk.EventType.DESTROY: 'any',
165         Gdk.EventType.EXPOSE: 'expose',
166         Gdk.EventType.MOTION_NOTIFY: 'motion',
167         Gdk.EventType.BUTTON_PRESS: 'button',
168         Gdk.EventType._2BUTTON_PRESS: 'button',
169         Gdk.EventType._3BUTTON_PRESS: 'button',
170         Gdk.EventType.BUTTON_RELEASE: 'button',
171         Gdk.EventType.KEY_PRESS: 'key',
172         Gdk.EventType.KEY_RELEASE: 'key',
173         Gdk.EventType.ENTER_NOTIFY: 'crossing',
174         Gdk.EventType.LEAVE_NOTIFY: 'crossing',
175         Gdk.EventType.FOCUS_CHANGE: 'focus_change',
176         Gdk.EventType.CONFIGURE: 'configure',
177         Gdk.EventType.MAP: 'any',
178         Gdk.EventType.UNMAP: 'any',
179         Gdk.EventType.PROPERTY_NOTIFY: 'property',
180         Gdk.EventType.SELECTION_CLEAR: 'selection',
181         Gdk.EventType.SELECTION_REQUEST: 'selection',
182         Gdk.EventType.SELECTION_NOTIFY: 'selection',
183         Gdk.EventType.PROXIMITY_IN: 'proximity',
184         Gdk.EventType.PROXIMITY_OUT: 'proximity',
185         Gdk.EventType.DRAG_ENTER: 'dnd',
186         Gdk.EventType.DRAG_LEAVE: 'dnd',
187         Gdk.EventType.DRAG_MOTION: 'dnd',
188         Gdk.EventType.DRAG_STATUS: 'dnd',
189         Gdk.EventType.DROP_START: 'dnd',
190         Gdk.EventType.DROP_FINISHED: 'dnd',
191         Gdk.EventType.CLIENT_EVENT: 'client',
192         Gdk.EventType.VISIBILITY_NOTIFY: 'visibility',
193     }
194
195     if Gdk._version == '2.0':
196         _UNION_MEMBERS[Gdk.EventType.NO_EXPOSE] = 'no_expose'
197
198     def __getattr__(self, name):
199         real_event = getattr(self, '_UNION_MEMBERS').get(self.type)
200         if real_event:
201             return getattr(getattr(self, real_event), name)
202         else:
203             raise AttributeError("'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
204
205 Event = override(Event)
206 __all__.append('Event')
207
208 # manually bind GdkEvent members to GdkEvent
209
210 modname = globals()['__name__']
211 module = sys.modules[modname]
212
213 # right now we can't get the type_info from the
214 # field info so manually list the class names
215 event_member_classes = ['EventAny',
216                         'EventExpose',
217                         'EventVisibility',
218                         'EventMotion',
219                         'EventButton',
220                         'EventScroll',
221                         'EventKey',
222                         'EventCrossing',
223                         'EventFocus',
224                         'EventConfigure',
225                         'EventProperty',
226                         'EventSelection',
227                         'EventOwnerChange',
228                         'EventProximity',
229                         'EventDND',
230                         'EventWindowState',
231                         'EventSetting',
232                         'EventGrabBroken']
233
234 if Gdk._version == '2.0':
235     event_member_classes.append('EventNoExpose')
236
237 # whitelist all methods that have a success return we want to mask
238 gsuccess_mask_funcs = ['get_state',
239                        'get_axis',
240                        'get_coords',
241                        'get_root_coords']
242
243
244 for event_class in event_member_classes:
245     override_class = type(event_class, (getattr(Gdk, event_class),), {})
246     # add the event methods
247     for method_info in Gdk.Event.__info__.get_methods():
248         name = method_info.get_name()
249         event_method = getattr(Gdk.Event, name)
250         # python2 we need to use the __func__ attr to avoid internal
251         # instance checks
252         event_method = getattr(event_method, '__func__', event_method)
253
254         # use the _gsuccess_mask decorator if this method is whitelisted
255         if name in gsuccess_mask_funcs:
256             event_method = strip_boolean_result(event_method)
257         setattr(override_class, name, event_method)
258
259     setattr(module, event_class, override_class)
260     __all__.append(event_class)
261
262 # end GdkEvent overrides
263
264
265 class DragContext(Gdk.DragContext):
266     def finish(self, success, del_, time):
267         Gtk = get_introspection_module('Gtk')
268         Gtk.drag_finish(self, success, del_, time)
269
270 DragContext = override(DragContext)
271 __all__.append('DragContext')
272
273
274 class Cursor(Gdk.Cursor):
275     def __new__(cls, *args, **kwds):
276         arg_len = len(args)
277         kwd_len = len(kwds)
278         total_len = arg_len + kwd_len
279
280         if total_len == 1:
281             # Since g_object_newv (super.__new__) does not seem valid for
282             # direct use with GdkCursor, we must assume usage of at least
283             # one of the C constructors to be valid.
284             return cls.new(*args, **kwds)
285
286         elif total_len == 2:
287             warnings.warn('Calling "Gdk.Cursor(display, cursor_type)" has been deprecated. '
288                           'Please use Gdk.Cursor.new_for_display(display, cursor_type). '
289                           'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
290                           PyGIDeprecationWarning)
291             return cls.new_for_display(*args, **kwds)
292
293         elif total_len == 4:
294             warnings.warn('Calling "Gdk.Cursor(display, pixbuf, x, y)" has been deprecated. '
295                           'Please use Gdk.Cursor.new_from_pixbuf(display, pixbuf, x, y). '
296                           'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
297                           PyGIDeprecationWarning)
298             return cls.new_from_pixbuf(*args, **kwds)
299
300         elif total_len == 6:
301             if Gdk._version != '2.0':
302                 # pixmaps don't exist in Gdk 3.0
303                 raise ValueError("Wrong number of parameters")
304
305             warnings.warn('Calling "Gdk.Cursor(source, mask, fg, bg, x, y)" has been deprecated. '
306                           'Please use Gdk.Cursor.new_from_pixmap(source, mask, fg, bg, x, y). '
307                           'See: https://wiki.gnome.org/PyGObject/InitializerDeprecations',
308                           PyGIDeprecationWarning)
309             return cls.new_from_pixmap(*args, **kwds)
310
311         else:
312             raise ValueError("Wrong number of parameters")
313
314
315 Cursor = override(Cursor)
316 __all__.append('Cursor')
317
318 color_parse = strip_boolean_result(Gdk.color_parse)
319 __all__.append('color_parse')
320
321
322 # Note, we cannot override the entire class as Gdk.Atom has no gtype, so just
323 # hack some individual methods
324 def _gdk_atom_str(atom):
325     n = atom.name()
326     if n:
327         return n
328     # fall back to atom index
329     return 'Gdk.Atom<%i>' % hash(atom)
330
331
332 def _gdk_atom_repr(atom):
333     n = atom.name()
334     if n:
335         return 'Gdk.Atom<%s>' % n
336     # fall back to atom index
337     return 'Gdk.Atom<%i>' % hash(atom)
338
339
340 Gdk.Atom.__str__ = _gdk_atom_str
341 Gdk.Atom.__repr__ = _gdk_atom_repr
342
343
344 # constants
345 if Gdk._version >= '3.0':
346     SELECTION_PRIMARY = Gdk.atom_intern('PRIMARY', True)
347     __all__.append('SELECTION_PRIMARY')
348
349     SELECTION_SECONDARY = Gdk.atom_intern('SECONDARY', True)
350     __all__.append('SELECTION_SECONDARY')
351
352     SELECTION_CLIPBOARD = Gdk.atom_intern('CLIPBOARD', True)
353     __all__.append('SELECTION_CLIPBOARD')
354
355     TARGET_BITMAP = Gdk.atom_intern('BITMAP', True)
356     __all__.append('TARGET_BITMAP')
357
358     TARGET_COLORMAP = Gdk.atom_intern('COLORMAP', True)
359     __all__.append('TARGET_COLORMAP')
360
361     TARGET_DRAWABLE = Gdk.atom_intern('DRAWABLE', True)
362     __all__.append('TARGET_DRAWABLE')
363
364     TARGET_PIXMAP = Gdk.atom_intern('PIXMAP', True)
365     __all__.append('TARGET_PIXMAP')
366
367     TARGET_STRING = Gdk.atom_intern('STRING', True)
368     __all__.append('TARGET_STRING')
369
370     SELECTION_TYPE_ATOM = Gdk.atom_intern('ATOM', True)
371     __all__.append('SELECTION_TYPE_ATOM')
372
373     SELECTION_TYPE_BITMAP = Gdk.atom_intern('BITMAP', True)
374     __all__.append('SELECTION_TYPE_BITMAP')
375
376     SELECTION_TYPE_COLORMAP = Gdk.atom_intern('COLORMAP', True)
377     __all__.append('SELECTION_TYPE_COLORMAP')
378
379     SELECTION_TYPE_DRAWABLE = Gdk.atom_intern('DRAWABLE', True)
380     __all__.append('SELECTION_TYPE_DRAWABLE')
381
382     SELECTION_TYPE_INTEGER = Gdk.atom_intern('INTEGER', True)
383     __all__.append('SELECTION_TYPE_INTEGER')
384
385     SELECTION_TYPE_PIXMAP = Gdk.atom_intern('PIXMAP', True)
386     __all__.append('SELECTION_TYPE_PIXMAP')
387
388     SELECTION_TYPE_WINDOW = Gdk.atom_intern('WINDOW', True)
389     __all__.append('SELECTION_TYPE_WINDOW')
390
391     SELECTION_TYPE_STRING = Gdk.atom_intern('STRING', True)
392     __all__.append('SELECTION_TYPE_STRING')
393
394 import sys
395
396 initialized, argv = Gdk.init_check(sys.argv)