]> Pileus Git - ~andy/gtk/blob - gdk/gdkwindow.c
wayland: set the "transient inactive" flag on tooltip surfaces
[~andy/gtk] / gdk / gdkwindow.c
1 /* GDK - The GIMP Drawing Kit
2  * Copyright (C) 1995-2007 Peter Mattis, Spencer Kimball,
3  * Josh MacDonald, Ryan Lortie
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Lesser General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Lesser General Public License for more details.
14  *
15  * You should have received a copy of the GNU Lesser General Public
16  * License along with this library. If not, see <http://www.gnu.org/licenses/>.
17  */
18
19 /*
20  * Modified by the GTK+ Team and others 1997-2000.  See the AUTHORS
21  * file for a list of people on the GTK+ Team.  See the ChangeLog
22  * files for a list of changes.  These files are distributed with
23  * GTK+ at ftp://ftp.gtk.org/pub/gtk/.
24  */
25
26 #include "config.h"
27
28 #include <cairo-gobject.h>
29
30 #include "gdkwindow.h"
31
32 #include "gdkrectangle.h"
33 #include "gdkinternals.h"
34 #include "gdkintl.h"
35 #include "gdkscreenprivate.h"
36 #include "gdkdisplayprivate.h"
37 #include "gdkdeviceprivate.h"
38 #include "gdkvisualprivate.h"
39 #include "gdkmarshalers.h"
40 #include "gdkwindowimpl.h"
41
42 #include <math.h>
43
44 #undef DEBUG_WINDOW_PRINTING
45
46
47 /**
48  * SECTION:windows
49  * @Short_description: Onscreen display areas in the target window system
50  * @Title: Windows
51  *
52  * A #GdkWindow is a (usually) rectangular region on the screen.
53  * It's a low-level object, used to implement high-level objects such as
54  * #GtkWidget and #GtkWindow on the GTK+ level. A #GtkWindow is a toplevel
55  * window, the thing a user might think of as a "window" with a titlebar and
56  * so on; a #GtkWindow may contain many #GdkWindows. For example, each
57  * #GtkButton has a #GdkWindow associated with it.
58  *
59  * <refsect2 id="COMPOSITED-WINDOWS">
60  * <title>Composited Windows</title>
61  * <para>
62  * Normally, the windowing system takes care of rendering the contents of a
63  * child window onto its parent window. This mechanism can be intercepted by
64  * calling gdk_window_set_composited() on the child window. For a
65  * <firstterm>composited</firstterm> window it is the responsibility of the
66  * application to render the window contents at the right spot.
67  * </para>
68  * </refsect2>
69  * <refsect2 id="OFFSCREEN-WINDOWS">
70  * <title>Offscreen Windows</title>
71  * <para>
72  * Offscreen windows are more general than composited windows, since they allow
73  * not only to modify the rendering of the child window onto its parent, but
74  * also to apply coordinate transformations.
75  *
76  * To integrate an offscreen window into a window hierarchy, one has to call
77  * gdk_offscreen_window_set_embedder() and handle a number of signals. The
78  * #GdkWindow::pick-embedded-child signal on the embedder window is used to
79  * select an offscreen child at given coordinates, and the
80  * #GdkWindow::to-embedder and #GdkWindow::from-embedder signals on the
81  * offscreen window are used to translate coordinates between the embedder and
82  * the offscreen window.
83  *
84  * For rendering an offscreen window onto its embedder, the contents of the
85  * offscreen window are available as a surface, via
86  * gdk_offscreen_window_get_surface().
87  * </para>
88  * </refsect2>
89  */
90
91
92 /* Historically a GdkWindow always matches a platform native window,
93  * be it a toplevel window or a child window. In this setup the
94  * GdkWindow (and other GdkDrawables) were platform independent classes,
95  * and the actual platform specific implementation was in a delegate
96  * object available as "impl" in the window object.
97  *
98  * With the addition of client side windows and offscreen windows this
99  * changes a bit. The application-visible GdkWindow object behaves as
100  * it did before, but not all such windows now have a corresponding native
101  * window. Instead windows that are "client side" are emulated by the gdk
102  * code such that clipping, drawing, moving, events etc work as expected.
103  *
104  * For GdkWindows that have a native window the "impl" object is the
105  * same as before. However, for all client side windows the impl object
106  * is shared with its parent (i.e. all client windows descendants of one
107  * native window has the same impl.
108  *
109  * Additionally there is a new type of platform independent impl object,
110  * GdkOffscreenWindow. All windows of type GDK_WINDOW_OFFSCREEN get an impl
111  * of this type (while their children are generally GDK_WINDOW_CHILD virtual
112  * windows). Such windows work by allocating a #cairo_surface_t as the backing
113  * store for drawing operations, which is resized with the window.
114  *
115  * GdkWindows have a pointer to the "impl window" they are in, i.e.
116  * the topmost GdkWindow which have the same "impl" value. This is stored
117  * in impl_window, which is different from the window itself only for client
118  * side windows.
119  * All GdkWindows (native or not) track the position of the window in the parent
120  * (x, y), the size of the window (width, height), the position of the window
121  * with respect to the impl window (abs_x, abs_y). We also track the clip
122  * region of the window wrt parent windows and siblings, in window-relative
123  * coordinates with and without child windows included (clip_region,
124  * clip_region_with_children).
125  *
126  * All toplevel windows are native windows, but also child windows can be
127  * native (although not children of offscreens). We always listen to
128  * a basic set of events (see get_native_event_mask) for these windows
129  * so that we can emulate events for any client side children.
130  *
131  * For native windows we apply the calculated clip region as a window shape
132  * so that eg. client side siblings that overlap the native child properly
133  * draws over the native child window.
134  *
135  * In order to minimize flicker and for performance we use a couple of cacheing
136  * tricks. First of all, every time we do a window to window copy area, for instance
137  * when moving a client side window or when scrolling/moving a region in a window
138  * we store this in outstanding_moves instead of applying immediately. We then
139  * delay this move until we really need it (because something depends on being
140  * able to read it), or until we're handing a redraw from an expose/invalidation
141  * (actually we delay it past redraw, but before blitting the double buffer
142  * to the window). This gives us two advantages. First of all it minimizes the time
143  * from the window is moved to the exposes related to that move, secondly it allows
144  * us to be smart about how to do the copy. We combine multiple moves into one (when
145  * possible) and we don't actually do copies to anything that is or will be
146  * invalidated and exposed anyway.
147  *
148  * Secondly, we use something called a "implicit paint" during repaint handling.
149  * An implicit paint is similar to a regular paint for the paint stack, but it is
150  * not put on the stack. Instead, it is set on the impl window, and later when
151  * regular gdk_window_begin_paint_region()  happen on a window of this impl window
152  * we reuse the surface from the implicit paint. During repaint we create and at the
153  * end flush an implicit paint, which means we can collect all the paints on
154  * multiple client side windows in the same backing store.
155  */
156
157 #define USE_BACKING_STORE       /* Appears to work on Win32, too, now. */
158
159 /* This adds a local value to the GdkVisibilityState enum */
160 #define GDK_VISIBILITY_NOT_VIEWABLE 3
161
162 enum {
163   PICK_EMBEDDED_CHILD, /* only called if children are embedded */
164   TO_EMBEDDER,
165   FROM_EMBEDDER,
166   CREATE_SURFACE,
167   LAST_SIGNAL
168 };
169
170 enum {
171   PROP_0,
172   PROP_CURSOR
173 };
174
175 typedef enum {
176   CLEAR_BG_NONE,
177   CLEAR_BG_WINCLEARED, /* Clear backgrounds except those that the window system clears */
178   CLEAR_BG_ALL
179 } ClearBg;
180
181 struct _GdkWindowPaint
182 {
183   cairo_region_t *region;
184   cairo_surface_t *surface;
185   cairo_region_t *flushed;
186   guint8 alpha;
187   guint uses_implicit : 1;
188 };
189
190 typedef struct {
191   cairo_region_t *dest_region; /* The destination region */
192   int dx, dy; /* The amount that the source was moved to reach dest_region */
193 } GdkWindowRegionMove;
194
195 /* Global info */
196
197 static void             gdk_window_drop_cairo_surface (GdkWindow *private);
198
199 static void gdk_window_free_paint_stack (GdkWindow *window);
200
201 static void gdk_window_finalize   (GObject              *object);
202
203 static void gdk_window_set_property (GObject      *object,
204                                      guint         prop_id,
205                                      const GValue *value,
206                                      GParamSpec   *pspec);
207 static void gdk_window_get_property (GObject      *object,
208                                      guint         prop_id,
209                                      GValue       *value,
210                                      GParamSpec   *pspec);
211
212 static void gdk_window_clear_backing_region (GdkWindow *window,
213                                              cairo_region_t *region);
214
215 static void recompute_visible_regions   (GdkWindow *private,
216                                          gboolean recalculate_siblings,
217                                          gboolean recalculate_children);
218 static void gdk_window_flush_outstanding_moves (GdkWindow *window);
219 static void gdk_window_flush_recursive  (GdkWindow *window);
220 static void do_move_region_bits_on_impl (GdkWindow *window,
221                                          cairo_region_t *region, /* In impl window coords */
222                                          int dx, int dy);
223 static void gdk_window_invalidate_in_parent (GdkWindow *private);
224 static void move_native_children        (GdkWindow *private);
225 static void update_cursor               (GdkDisplay *display,
226                                          GdkDevice  *device);
227 static void impl_window_add_update_area (GdkWindow *impl_window,
228                                          cairo_region_t *region);
229 static void gdk_window_region_move_free (GdkWindowRegionMove *move);
230 static void gdk_window_invalidate_region_full (GdkWindow       *window,
231                                                const cairo_region_t *region,
232                                                gboolean         invalidate_children,
233                                                ClearBg          clear_bg);
234 static void gdk_window_invalidate_rect_full (GdkWindow          *window,
235                                              const GdkRectangle *rect,
236                                              gboolean            invalidate_children,
237                                              ClearBg             clear_bg);
238 static void _gdk_window_propagate_has_alpha_background (GdkWindow *window);
239 static cairo_surface_t *gdk_window_ref_impl_surface (GdkWindow *window);
240
241 static guint signals[LAST_SIGNAL] = { 0 };
242
243 static gpointer parent_class = NULL;
244
245 static const cairo_user_data_key_t gdk_window_cairo_key;
246
247 G_DEFINE_ABSTRACT_TYPE (GdkWindow, gdk_window, G_TYPE_OBJECT)
248
249 #ifdef DEBUG_WINDOW_PRINTING
250 char *
251 print_region (cairo_region_t *region)
252 {
253   GString *s = g_string_new ("{");
254   if (cairo_region_is_empty (region))
255     {
256       g_string_append (s, "empty");
257     }
258   else
259     {
260       int num = cairo_region_num_rectangles (region);
261       cairo_rectangle_int_t r;
262
263       if (num == 1)
264         {
265           cairo_region_get_rectangle (region, 0, &r);
266           g_string_append_printf (s, "%dx%d @%d,%d", r.width, r.height, r.x, r.y);
267         }
268       else
269         {
270           cairo_region_get_extents (region, &r);
271           g_string_append_printf (s, "extent: %dx%d @%d,%d, details: ", r.width, r.height, r.x, r.y);
272           for (int i = 0; i < num; i++)
273             {
274               g_string_append_printf (s, "[%dx%d @%d,%d]", r.width, r.height, r.x, r.y);
275               if (i != num -1)
276                 g_string_append (s, ", ");
277             }
278         }
279     }
280   g_string_append (s, "}");
281   return g_string_free (s, FALSE);
282 }
283 #endif
284
285 GType
286 _gdk_paintable_get_type (void)
287 {
288   static GType paintable_type = 0;
289
290   if (!paintable_type)
291     {
292       const GTypeInfo paintable_info =
293       {
294         sizeof (GdkPaintableIface),  /* class_size */
295         NULL,                        /* base_init */
296         NULL,                        /* base_finalize */
297       };
298
299       paintable_type = g_type_register_static (G_TYPE_INTERFACE,
300                                                g_intern_static_string ("GdkPaintable"),
301                                                &paintable_info, 0);
302
303       g_type_interface_add_prerequisite (paintable_type, G_TYPE_OBJECT);
304     }
305
306   return paintable_type;
307 }
308
309 static void
310 gdk_window_init (GdkWindow *window)
311 {
312   /* 0-initialization is good for all other fields. */
313
314   window->window_type = GDK_WINDOW_CHILD;
315
316   window->state = GDK_WINDOW_STATE_WITHDRAWN;
317   window->fullscreen_mode = GDK_FULLSCREEN_ON_CURRENT_MONITOR;
318   window->width = 1;
319   window->height = 1;
320   window->toplevel_window_type = -1;
321   /* starts hidden */
322   window->effective_visibility = GDK_VISIBILITY_NOT_VIEWABLE;
323   window->visibility = GDK_VISIBILITY_FULLY_OBSCURED;
324   /* Default to unobscured since some backends don't send visibility events */
325   window->native_visibility = GDK_VISIBILITY_UNOBSCURED;
326
327   window->device_cursor = g_hash_table_new_full (NULL, NULL,
328                                                  NULL, g_object_unref);
329 }
330
331 /* Stop and return on the first non-NULL parent */
332 static gboolean
333 accumulate_get_window (GSignalInvocationHint *ihint,
334                        GValue                  *return_accu,
335                        const GValue            *handler_return,
336                        gpointer               data)
337 {
338   g_value_copy (handler_return, return_accu);
339   /* Continue while returning NULL */
340   return g_value_get_object (handler_return) == NULL;
341 }
342
343 static gboolean
344 create_surface_accumulator (GSignalInvocationHint *ihint,
345                             GValue                *return_accu,
346                             const GValue          *handler_return,
347                             gpointer               data)
348 {
349   g_value_copy (handler_return, return_accu);
350
351   /* Stop on the first non-NULL return value */
352   return g_value_get_boxed (handler_return) == NULL;
353 }
354
355 static GQuark quark_pointer_window = 0;
356
357 static void
358 gdk_window_class_init (GdkWindowClass *klass)
359 {
360   GObjectClass *object_class = G_OBJECT_CLASS (klass);
361
362   parent_class = g_type_class_peek_parent (klass);
363
364   object_class->finalize = gdk_window_finalize;
365   object_class->set_property = gdk_window_set_property;
366   object_class->get_property = gdk_window_get_property;
367
368   klass->create_surface = _gdk_offscreen_window_create_surface;
369
370   quark_pointer_window = g_quark_from_static_string ("gtk-pointer-window");
371
372
373   /* Properties */
374
375   /**
376    * GdkWindow:cursor:
377    *
378    * The mouse pointer for a #GdkWindow. See gdk_window_set_cursor() and
379    * gdk_window_get_cursor() for details.
380    *
381    * Since: 2.18
382    */
383   g_object_class_install_property (object_class,
384                                    PROP_CURSOR,
385                                    g_param_spec_object ("cursor",
386                                                         P_("Cursor"),
387                                                         P_("Cursor"),
388                                                         GDK_TYPE_CURSOR,
389                                                         G_PARAM_READWRITE));
390
391   /**
392    * GdkWindow::pick-embedded-child:
393    * @window: the window on which the signal is emitted
394    * @x: x coordinate in the window
395    * @y: y coordinate in the window
396    *
397    * The ::pick-embedded-child signal is emitted to find an embedded
398    * child at the given position.
399    *
400    * Returns: (transfer none): the #GdkWindow of the embedded child at
401    *     @x, @y, or %NULL
402    *
403    * Since: 2.18
404    */
405   signals[PICK_EMBEDDED_CHILD] =
406     g_signal_new (g_intern_static_string ("pick-embedded-child"),
407                   G_OBJECT_CLASS_TYPE (object_class),
408                   G_SIGNAL_RUN_LAST,
409                   G_STRUCT_OFFSET (GdkWindowClass, pick_embedded_child),
410                   accumulate_get_window, NULL,
411                   _gdk_marshal_OBJECT__DOUBLE_DOUBLE,
412                   GDK_TYPE_WINDOW,
413                   2,
414                   G_TYPE_DOUBLE,
415                   G_TYPE_DOUBLE);
416
417   /**
418    * GdkWindow::to-embedder:
419    * @window: the offscreen window on which the signal is emitted
420    * @offscreen_x: x coordinate in the offscreen window
421    * @offscreen_y: y coordinate in the offscreen window
422    * @embedder_x: (out) (type double): return location for the x
423    *     coordinate in the embedder window
424    * @embedder_y: (out) (type double): return location for the y
425    *     coordinate in the embedder window
426    *
427    * The ::to-embedder signal is emitted to translate coordinates
428    * in an offscreen window to its embedder.
429    *
430    * See also #GtkWindow::from-embedder.
431    *
432    * Since: 2.18
433    */
434   signals[TO_EMBEDDER] =
435     g_signal_new (g_intern_static_string ("to-embedder"),
436                   G_OBJECT_CLASS_TYPE (object_class),
437                   G_SIGNAL_RUN_LAST,
438                   G_STRUCT_OFFSET (GdkWindowClass, to_embedder),
439                   NULL, NULL,
440                   _gdk_marshal_VOID__DOUBLE_DOUBLE_POINTER_POINTER,
441                   G_TYPE_NONE,
442                   4,
443                   G_TYPE_DOUBLE,
444                   G_TYPE_DOUBLE,
445                   G_TYPE_POINTER,
446                   G_TYPE_POINTER);
447
448   /**
449    * GdkWindow::from-embedder:
450    * @window: the offscreen window on which the signal is emitted
451    * @embedder_x: x coordinate in the embedder window
452    * @embedder_y: y coordinate in the embedder window
453    * @offscreen_x: (out) (type double): return location for the x
454    *     coordinate in the offscreen window
455    * @offscreen_y: (out) (type double): return location for the y
456    *     coordinate in the offscreen window
457    *
458    * The ::from-embedder signal is emitted to translate coordinates
459    * in the embedder of an offscreen window to the offscreen window.
460    *
461    * See also #GtkWindow::to-embedder.
462    *
463    * Since: 2.18
464    */
465   signals[FROM_EMBEDDER] =
466     g_signal_new (g_intern_static_string ("from-embedder"),
467                   G_OBJECT_CLASS_TYPE (object_class),
468                   G_SIGNAL_RUN_LAST,
469                   G_STRUCT_OFFSET (GdkWindowClass, from_embedder),
470                   NULL, NULL,
471                   _gdk_marshal_VOID__DOUBLE_DOUBLE_POINTER_POINTER,
472                   G_TYPE_NONE,
473                   4,
474                   G_TYPE_DOUBLE,
475                   G_TYPE_DOUBLE,
476                   G_TYPE_POINTER,
477                   G_TYPE_POINTER);
478
479   /**
480    * GdkWindow::create-surface:
481    * @window: the offscreen window on which the signal is emitted
482    * @width: the width of the offscreen surface to create
483    * @height: the height of the offscreen surface to create
484    *
485    * The ::create-surface signal is emitted when an offscreen window
486    * needs its surface (re)created, which happens either when the the
487    * window is first drawn to, or when the window is being
488    * resized. The first signal handler that returns a non-%NULL
489    * surface will stop any further signal emission, and its surface
490    * will be used.
491    *
492    * Note that it is not possible to access the window's previous
493    * surface from within any callback of this signal. Calling
494    * gdk_offscreen_window_get_surface() will lead to a crash.
495    *
496    * Returns: the newly created #cairo_surface_t for the offscreen window
497    *
498    * Since: 3.0
499    */
500   signals[CREATE_SURFACE] =
501     g_signal_new (g_intern_static_string ("create-surface"),
502                   G_OBJECT_CLASS_TYPE (object_class),
503                   G_SIGNAL_RUN_LAST,
504                   G_STRUCT_OFFSET (GdkWindowClass, create_surface),
505                   create_surface_accumulator, NULL,
506                   _gdk_marshal_BOXED__INT_INT,
507                   CAIRO_GOBJECT_TYPE_SURFACE,
508                   2,
509                   G_TYPE_INT,
510                   G_TYPE_INT);
511 }
512
513 static void
514 device_removed_cb (GdkDeviceManager *device_manager,
515                    GdkDevice        *device,
516                    GdkWindow        *window)
517 {
518   window->devices_inside = g_list_remove (window->devices_inside, device);
519   g_hash_table_remove (window->device_cursor, device);
520
521   if (window->device_events)
522     g_hash_table_remove (window->device_events, device);
523 }
524
525 static void
526 gdk_window_finalize (GObject *object)
527 {
528   GdkWindow *window = GDK_WINDOW (object);
529   GdkDeviceManager *device_manager;
530
531   device_manager = gdk_display_get_device_manager (gdk_window_get_display (window));
532   g_signal_handlers_disconnect_by_func (device_manager, device_removed_cb, window);
533
534   if (!GDK_WINDOW_DESTROYED (window))
535     {
536       if (GDK_WINDOW_TYPE (window) != GDK_WINDOW_FOREIGN)
537         {
538           g_warning ("losing last reference to undestroyed window\n");
539           _gdk_window_destroy (window, FALSE);
540         }
541       else
542         /* We use TRUE here, to keep us from actually calling
543          * XDestroyWindow() on the window
544          */
545         _gdk_window_destroy (window, TRUE);
546     }
547
548   gdk_window_drop_cairo_surface (window);
549
550   if (window->impl)
551     {
552       g_object_unref (window->impl);
553       window->impl = NULL;
554     }
555
556   if (window->impl_window != window)
557     {
558       g_object_unref (window->impl_window);
559       window->impl_window = NULL;
560     }
561
562   if (window->shape)
563     cairo_region_destroy (window->shape);
564
565   if (window->input_shape)
566     cairo_region_destroy (window->input_shape);
567
568   if (window->cursor)
569     g_object_unref (window->cursor);
570
571   if (window->device_cursor)
572     g_hash_table_destroy (window->device_cursor);
573
574   if (window->device_events)
575     g_hash_table_destroy (window->device_events);
576
577   if (window->source_event_masks)
578     g_hash_table_destroy (window->source_event_masks);
579
580   if (window->devices_inside)
581     g_list_free (window->devices_inside);
582
583   if (window->layered_region)
584       cairo_region_destroy (window->layered_region);
585
586   G_OBJECT_CLASS (parent_class)->finalize (object);
587 }
588
589 static void
590 gdk_window_set_property (GObject      *object,
591                          guint         prop_id,
592                          const GValue *value,
593                          GParamSpec   *pspec)
594 {
595   GdkWindow *window = (GdkWindow *)object;
596
597   switch (prop_id)
598     {
599     case PROP_CURSOR:
600       gdk_window_set_cursor (window, g_value_get_object (value));
601       break;
602
603     default:
604       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
605       break;
606     }
607 }
608
609 static void
610 gdk_window_get_property (GObject    *object,
611                          guint       prop_id,
612                          GValue     *value,
613                          GParamSpec *pspec)
614 {
615   GdkWindow *window = (GdkWindow *) object;
616
617   switch (prop_id)
618     {
619     case PROP_CURSOR:
620       g_value_set_object (value, gdk_window_get_cursor (window));
621       break;
622
623     default:
624       G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
625       break;
626     }
627 }
628
629 static gboolean
630 gdk_window_is_offscreen (GdkWindow *window)
631 {
632   return window->window_type == GDK_WINDOW_OFFSCREEN;
633 }
634
635 static GdkWindow *
636 gdk_window_get_impl_window (GdkWindow *window)
637 {
638   return window->impl_window;
639 }
640
641 GdkWindow *
642 _gdk_window_get_impl_window (GdkWindow *window)
643 {
644   return gdk_window_get_impl_window (window);
645 }
646
647 static gboolean
648 gdk_window_has_impl (GdkWindow *window)
649 {
650   return window->impl_window == window;
651 }
652
653 static gboolean
654 gdk_window_is_toplevel (GdkWindow *window)
655 {
656   return
657     window->parent == NULL ||
658     window->parent->window_type == GDK_WINDOW_ROOT;
659 }
660
661 gboolean
662 _gdk_window_has_impl (GdkWindow *window)
663 {
664   return gdk_window_has_impl (window);
665 }
666
667 static gboolean
668 gdk_window_has_no_impl (GdkWindow *window)
669 {
670   return window->impl_window != window;
671 }
672
673 static gboolean
674 gdk_window_has_alpha (GdkWindow *window)
675 {
676   return !gdk_window_has_impl (window) &&
677     (window->has_alpha_background || window->alpha != 255);
678 }
679
680 static void
681 remove_layered_child_area (GdkWindow *window,
682                            cairo_region_t *region)
683 {
684   GdkWindow *child;
685   cairo_region_t *child_region;
686   GdkRectangle r;
687   GList *l;
688
689   for (l = window->children; l; l = l->next)
690     {
691       child = l->data;
692
693       /* If region is empty already, no need to do
694          anything potentially costly */
695       if (cairo_region_is_empty (region))
696         break;
697
698       if (!GDK_WINDOW_IS_MAPPED (child) || child->input_only || child->composited)
699         continue;
700
701       /* Ignore offscreen children, as they don't draw in their parent and
702        * don't take part in the clipping */
703       if (gdk_window_is_offscreen (child))
704         continue;
705
706       /* Only non-impl children with alpha add to the layered region */
707       if (!gdk_window_has_alpha (child))
708         continue;
709
710       r.x = child->x;
711       r.y = child->y;
712       r.width = child->width;
713       r.height = child->height;
714
715       /* Bail early if child totally outside region */
716       if (cairo_region_contains_rectangle (region, &r) == CAIRO_REGION_OVERLAP_OUT)
717         continue;
718
719       child_region = cairo_region_create_rectangle (&r);
720       if (child->shape)
721         {
722           /* Adjust shape region to parent window coords */
723           cairo_region_translate (child->shape, child->x, child->y);
724           cairo_region_intersect (child_region, child->shape);
725           cairo_region_translate (child->shape, -child->x, -child->y);
726         }
727
728       cairo_region_subtract (region, child_region);
729       cairo_region_destroy (child_region);
730     }
731 }
732
733 static void
734 remove_child_area (GdkWindow *window,
735                    GdkWindow *until,
736                    gboolean for_input,
737                    cairo_region_t *region,
738                    cairo_region_t *layered_region)
739 {
740   GdkWindow *child;
741   cairo_region_t *child_region;
742   GdkRectangle r;
743   GList *l;
744   cairo_region_t *shape;
745
746   for (l = window->children; l; l = l->next)
747     {
748       child = l->data;
749
750       if (child == until)
751         break;
752
753       /* If region is empty already, no need to do
754          anything potentially costly */
755       if (cairo_region_is_empty (region))
756         break;
757
758       if (!GDK_WINDOW_IS_MAPPED (child) || child->input_only || child->composited)
759         continue;
760
761       /* Ignore offscreen children, as they don't draw in their parent and
762        * don't take part in the clipping */
763       if (gdk_window_is_offscreen (child))
764         continue;
765
766       r.x = child->x;
767       r.y = child->y;
768       r.width = child->width;
769       r.height = child->height;
770
771       /* Bail early if child totally outside region */
772       if (cairo_region_contains_rectangle (region, &r) == CAIRO_REGION_OVERLAP_OUT)
773         continue;
774
775       child_region = cairo_region_create_rectangle (&r);
776
777       if (child->shape)
778         {
779           /* Adjust shape region to parent window coords */
780           cairo_region_translate (child->shape, child->x, child->y);
781           cairo_region_intersect (child_region, child->shape);
782           cairo_region_translate (child->shape, -child->x, -child->y);
783         }
784       else if (window->window_type == GDK_WINDOW_FOREIGN)
785         {
786           shape = GDK_WINDOW_IMPL_GET_CLASS (child)->get_shape (child);
787           if (shape)
788             {
789               cairo_region_intersect (child_region, shape);
790               cairo_region_destroy (shape);
791             }
792         }
793
794       if (for_input)
795         {
796           if (child->input_shape)
797             cairo_region_intersect (child_region, child->input_shape);
798           else if (window->window_type == GDK_WINDOW_FOREIGN)
799             {
800               shape = GDK_WINDOW_IMPL_GET_CLASS (child)->get_input_shape (child);
801               if (shape)
802                 {
803                   cairo_region_intersect (child_region, shape);
804                   cairo_region_destroy (shape);
805                 }
806             }
807         }
808
809       if (gdk_window_has_alpha (child))
810         {
811           if (layered_region != NULL)
812             cairo_region_union (layered_region, child_region);
813         }
814       else
815         cairo_region_subtract (region, child_region);
816       cairo_region_destroy (child_region);
817     }
818 }
819
820 static GdkVisibilityState
821 effective_visibility (GdkWindow *window)
822 {
823   GdkVisibilityState native;
824
825   if (!gdk_window_is_viewable (window))
826     return GDK_VISIBILITY_NOT_VIEWABLE;
827
828   native = window->impl_window->native_visibility;
829
830   if (native == GDK_VISIBILITY_FULLY_OBSCURED ||
831       window->visibility == GDK_VISIBILITY_FULLY_OBSCURED)
832     return GDK_VISIBILITY_FULLY_OBSCURED;
833   else if (native == GDK_VISIBILITY_UNOBSCURED)
834     return window->visibility;
835   else /* native PARTIAL, private partial or unobscured  */
836     return GDK_VISIBILITY_PARTIAL;
837 }
838
839 static void
840 gdk_window_update_visibility (GdkWindow *window)
841 {
842   GdkVisibilityState new_visibility;
843   GdkEvent *event;
844
845   new_visibility = effective_visibility (window);
846
847   if (new_visibility != window->effective_visibility)
848     {
849       window->effective_visibility = new_visibility;
850
851       if (new_visibility != GDK_VISIBILITY_NOT_VIEWABLE &&
852           window->event_mask & GDK_VISIBILITY_NOTIFY_MASK)
853         {
854           event = _gdk_make_event (window, GDK_VISIBILITY_NOTIFY,
855                                    NULL, FALSE);
856           event->visibility.state = new_visibility;
857         }
858     }
859 }
860
861 static void
862 gdk_window_update_visibility_recursively (GdkWindow *window,
863                                           GdkWindow *only_for_impl)
864 {
865   GdkWindow *child;
866   GList *l;
867
868   gdk_window_update_visibility (window);
869   for (l = window->children; l != NULL; l = l->next)
870     {
871       child = l->data;
872       if ((only_for_impl == NULL) ||
873           (only_for_impl == child->impl_window))
874         gdk_window_update_visibility_recursively (child, only_for_impl);
875     }
876 }
877
878 static gboolean
879 should_apply_clip_as_shape (GdkWindow *window)
880 {
881   return
882     gdk_window_has_impl (window) &&
883     /* Not for offscreens */
884     !gdk_window_is_offscreen (window) &&
885     /* or for toplevels */
886     !gdk_window_is_toplevel (window) &&
887     /* or for foreign windows */
888     window->window_type != GDK_WINDOW_FOREIGN &&
889     /* or for the root window */
890     window->window_type != GDK_WINDOW_ROOT;
891 }
892
893 static void
894 apply_shape (GdkWindow *window,
895              cairo_region_t *region)
896 {
897   GdkWindowImplClass *impl_class;
898
899   /* We trash whether we applied a shape so that
900      we can avoid unsetting it many times, which
901      could happen in e.g. apply_clip_as_shape as
902      windows get resized */
903   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
904   if (region)
905     impl_class->shape_combine_region (window,
906                                       region, 0, 0);
907   else if (window->applied_shape)
908     impl_class->shape_combine_region (window,
909                                       NULL, 0, 0);
910
911   window->applied_shape = region != NULL;
912 }
913
914 static gboolean
915 region_rect_equal (const cairo_region_t *region,
916                    const GdkRectangle *rect)
917 {
918     GdkRectangle extents;
919
920     if (cairo_region_num_rectangles (region) != 1)
921         return FALSE;
922
923     cairo_region_get_extents (region, &extents);
924
925     return extents.x == rect->x &&
926         extents.y == rect->y &&
927         extents.width == rect->width &&
928         extents.height == rect->height;
929 }
930
931 static void
932 apply_clip_as_shape (GdkWindow *window)
933 {
934   GdkRectangle r;
935
936   r.x = r.y = 0;
937   r.width = window->width;
938   r.height = window->height;
939
940   /* We only apply the clip region if would differ
941      from the actual clip region implied by the size
942      of the window. This is to avoid unneccessarily
943      adding meaningless shapes to all native subwindows */
944   if (!region_rect_equal (window->clip_region, &r))
945     apply_shape (window, window->clip_region);
946   else
947     apply_shape (window, NULL);
948 }
949
950 static void
951 recompute_visible_regions_internal (GdkWindow *private,
952                                     gboolean   recalculate_clip,
953                                     gboolean   recalculate_siblings,
954                                     gboolean   recalculate_children)
955 {
956   GdkRectangle r;
957   GList *l;
958   GdkWindow *child;
959   cairo_region_t *new_clip, *new_layered;
960   gboolean clip_region_changed;
961   gboolean abs_pos_changed;
962   int old_abs_x, old_abs_y;
963
964   old_abs_x = private->abs_x;
965   old_abs_y = private->abs_y;
966
967   /* Update absolute position */
968   if (gdk_window_has_impl (private))
969     {
970       /* Native window starts here */
971       private->abs_x = 0;
972       private->abs_y = 0;
973     }
974   else
975     {
976       private->abs_x = private->parent->abs_x + private->x;
977       private->abs_y = private->parent->abs_y + private->y;
978     }
979
980   abs_pos_changed =
981     private->abs_x != old_abs_x ||
982     private->abs_y != old_abs_y;
983
984   /* Update clip region based on:
985    * parent clip
986    * window size
987    * siblings in parents above window
988    */
989   clip_region_changed = FALSE;
990   if (recalculate_clip)
991     {
992       new_layered = cairo_region_create ();
993       if (private->viewable)
994         {
995           /* Calculate visible region (sans children) in parent window coords */
996           r.x = private->x;
997           r.y = private->y;
998           r.width = private->width;
999           r.height = private->height;
1000           new_clip = cairo_region_create_rectangle (&r);
1001
1002           if (!gdk_window_is_toplevel (private))
1003             {
1004               cairo_region_intersect (new_clip, private->parent->clip_region);
1005               cairo_region_union (new_layered, private->parent->layered_region);
1006
1007               /* Remove all overlapping children from parent. */
1008               remove_child_area (private->parent, private, FALSE, new_clip, new_layered);
1009             }
1010
1011           /* Convert from parent coords to window coords */
1012           cairo_region_translate (new_clip, -private->x, -private->y);
1013           cairo_region_translate (new_layered, -private->x, -private->y);
1014
1015           if (private->shape)
1016             cairo_region_intersect (new_clip, private->shape);
1017         }
1018       else
1019           new_clip = cairo_region_create ();
1020
1021       cairo_region_intersect (new_layered, new_clip);
1022       
1023       if (private->clip_region == NULL ||
1024           !cairo_region_equal (private->clip_region, new_clip))
1025         clip_region_changed = TRUE;
1026
1027       if (private->layered_region == NULL ||
1028           !cairo_region_equal (private->layered_region, new_layered))
1029         clip_region_changed = TRUE;
1030       
1031       if (private->clip_region)
1032         cairo_region_destroy (private->clip_region);
1033       private->clip_region = new_clip;
1034
1035       if (private->layered_region != NULL)
1036         cairo_region_destroy (private->layered_region);
1037       private->layered_region = new_layered;
1038
1039       if (private->clip_region_with_children)
1040         cairo_region_destroy (private->clip_region_with_children);
1041       private->clip_region_with_children = cairo_region_copy (private->clip_region);
1042       if (private->window_type != GDK_WINDOW_ROOT)
1043         remove_child_area (private, NULL, FALSE, private->clip_region_with_children, NULL);
1044     }
1045
1046   if (clip_region_changed)
1047     {
1048       GdkVisibilityState visibility;
1049       gboolean fully_visible;
1050
1051       if (cairo_region_is_empty (private->clip_region))
1052         visibility = GDK_VISIBILITY_FULLY_OBSCURED;
1053       else
1054         {
1055           if (private->shape)
1056             {
1057               fully_visible = cairo_region_equal (private->clip_region,
1058                                                 private->shape);
1059             }
1060           else
1061             {
1062               r.x = 0;
1063               r.y = 0;
1064               r.width = private->width;
1065               r.height = private->height;
1066               fully_visible = region_rect_equal (private->clip_region, &r);
1067             }
1068
1069           if (fully_visible)
1070             visibility = GDK_VISIBILITY_UNOBSCURED;
1071           else
1072             visibility = GDK_VISIBILITY_PARTIAL;
1073         }
1074
1075       if (private->visibility != visibility)
1076         {
1077           private->visibility = visibility;
1078           gdk_window_update_visibility (private);
1079         }
1080     }
1081
1082   /* Update all children, recursively (except for root, where children are not exact). */
1083   if ((abs_pos_changed || clip_region_changed || recalculate_children) &&
1084       private->window_type != GDK_WINDOW_ROOT)
1085     {
1086       for (l = private->children; l; l = l->next)
1087         {
1088           child = l->data;
1089           /* Only recalculate clip if the the clip region changed, otherwise
1090            * there is no way the child clip region could change (its has not e.g. moved)
1091            * Except if recalculate_children is set to force child updates
1092            */
1093           recompute_visible_regions_internal (child,
1094                                               recalculate_clip && (clip_region_changed || recalculate_children),
1095                                               FALSE, FALSE);
1096         }
1097     }
1098
1099   if (clip_region_changed &&
1100       should_apply_clip_as_shape (private))
1101     apply_clip_as_shape (private);
1102
1103   if (recalculate_siblings &&
1104       !gdk_window_is_toplevel (private))
1105     {
1106       /* If we moved a child window in parent or changed the stacking order, then we
1107        * need to recompute the visible area of all the other children in the parent
1108        */
1109       for (l = private->parent->children; l; l = l->next)
1110         {
1111           child = l->data;
1112
1113           if (child != private)
1114             recompute_visible_regions_internal (child, TRUE, FALSE, FALSE);
1115         }
1116
1117       /* We also need to recompute the _with_children clip for the parent */
1118       recompute_visible_regions_internal (private->parent, TRUE, FALSE, FALSE);
1119     }
1120
1121   if (private->cairo_surface && gdk_window_has_impl (private))
1122     {
1123       GdkWindowImplClass *iface = GDK_WINDOW_IMPL_GET_CLASS (private->impl);
1124
1125       private->cairo_surface = iface->resize_cairo_surface (private,
1126                                                             private->cairo_surface,
1127                                                             private->width,
1128                                                             private->height);
1129     }
1130   else if (private->cairo_surface)
1131     gdk_window_drop_cairo_surface (private);
1132 }
1133
1134 /* Call this when private has changed in one or more of these ways:
1135  *  size changed
1136  *  window moved
1137  *  new window added
1138  *  stacking order of window changed
1139  *  child deleted
1140  *
1141  * It will recalculate abs_x/y and the clip regions
1142  *
1143  * Unless the window didn't change stacking order or size/pos, pass in TRUE
1144  * for recalculate_siblings. (Mostly used internally for the recursion)
1145  *
1146  * If a child window was removed (and you can't use that child for
1147  * recompute_visible_regions), pass in TRUE for recalculate_children on the parent
1148  */
1149 static void
1150 recompute_visible_regions (GdkWindow *private,
1151                            gboolean recalculate_siblings,
1152                            gboolean recalculate_children)
1153 {
1154   recompute_visible_regions_internal (private,
1155                                       TRUE,
1156                                       recalculate_siblings,
1157                                       recalculate_children);
1158 }
1159
1160 void
1161 _gdk_window_update_size (GdkWindow *window)
1162 {
1163   recompute_visible_regions (window, TRUE, FALSE);
1164 }
1165
1166 /* Find the native window that would be just above "child"
1167  * in the native stacking order if "child" was a native window
1168  * (it doesn't have to be native). If there is no such native
1169  * window inside this native parent then NULL is returned.
1170  * If child is NULL, find lowest native window in parent.
1171  */
1172 static GdkWindow *
1173 find_native_sibling_above_helper (GdkWindow *parent,
1174                                   GdkWindow *child)
1175 {
1176   GdkWindow *w;
1177   GList *l;
1178
1179   if (child)
1180     {
1181       l = g_list_find (parent->children, child);
1182       g_assert (l != NULL); /* Better be a child of its parent... */
1183       l = l->prev; /* Start looking at the one above the child */
1184     }
1185   else
1186     l = g_list_last (parent->children);
1187
1188   for (; l != NULL; l = l->prev)
1189     {
1190       w = l->data;
1191
1192       if (gdk_window_has_impl (w))
1193         return w;
1194
1195       g_assert (parent != w);
1196       w = find_native_sibling_above_helper (w, NULL);
1197       if (w)
1198         return w;
1199     }
1200
1201   return NULL;
1202 }
1203
1204
1205 static GdkWindow *
1206 find_native_sibling_above (GdkWindow *parent,
1207                            GdkWindow *child)
1208 {
1209   GdkWindow *w;
1210
1211   w = find_native_sibling_above_helper (parent, child);
1212   if (w)
1213     return w;
1214
1215   if (gdk_window_has_impl (parent))
1216     return NULL;
1217   else
1218     return find_native_sibling_above (parent->parent, parent);
1219 }
1220
1221 static GdkEventMask
1222 get_native_device_event_mask (GdkWindow *private,
1223                               GdkDevice *device)
1224 {
1225   GdkEventMask event_mask;
1226
1227   if (device)
1228     event_mask = GPOINTER_TO_INT (g_hash_table_lookup (private->device_events, device));
1229   else
1230     event_mask = private->event_mask;
1231
1232   if (private->window_type == GDK_WINDOW_ROOT ||
1233       private->window_type == GDK_WINDOW_FOREIGN)
1234     return event_mask;
1235   else
1236     {
1237       GdkEventMask mask;
1238
1239       /* Do whatever the app asks to, since the app
1240        * may be asking for weird things for native windows,
1241        * but don't use motion hints as that may affect non-native
1242        * child windows that don't want it. Also, we need to
1243        * set all the app-specified masks since they will be picked
1244        * up by any implicit grabs (i.e. if they were not set as
1245        * native we would not get the events we need). */
1246       mask = private->event_mask & ~GDK_POINTER_MOTION_HINT_MASK;
1247
1248       /* We need thse for all native windows so we can
1249          emulate events on children: */
1250       mask |=
1251         GDK_EXPOSURE_MASK |
1252         GDK_VISIBILITY_NOTIFY_MASK |
1253         GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK;
1254
1255       /* Additionally we select for pointer and button events
1256        * for toplevels as we need to get these to emulate
1257        * them for non-native subwindows. Even though we don't
1258        * select on them for all native windows we will get them
1259        * as the events are propagated out to the first window
1260        * that select for them.
1261        * Not selecting for button press on all windows is an
1262        * important thing, because in X only one client can do
1263        * so, and we don't want to unexpectedly prevent another
1264        * client from doing it.
1265        *
1266        * We also need to do the same if the app selects for button presses
1267        * because then we will get implicit grabs for this window, and the
1268        * event mask used for that grab is based on the rest of the mask
1269        * for the window, but we might need more events than this window
1270        * lists due to some non-native child window.
1271        */
1272       if (gdk_window_is_toplevel (private) ||
1273           mask & GDK_BUTTON_PRESS_MASK)
1274         mask |=
1275           GDK_TOUCH_MASK |
1276           GDK_POINTER_MOTION_MASK |
1277           GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
1278           GDK_SCROLL_MASK;
1279
1280       return mask;
1281     }
1282 }
1283
1284 static GdkEventMask
1285 get_native_grab_event_mask (GdkEventMask grab_mask)
1286 {
1287   /* Similar to the above but for pointer events only */
1288   return
1289     GDK_POINTER_MOTION_MASK |
1290     GDK_BUTTON_PRESS_MASK | GDK_BUTTON_RELEASE_MASK |
1291     GDK_ENTER_NOTIFY_MASK | GDK_LEAVE_NOTIFY_MASK |
1292     GDK_SCROLL_MASK |
1293     (grab_mask &
1294      ~GDK_POINTER_MOTION_HINT_MASK);
1295 }
1296
1297 static GdkEventMask
1298 get_native_event_mask (GdkWindow *private)
1299 {
1300   return get_native_device_event_mask (private, NULL);
1301 }
1302
1303 /* Puts the native window in the right order wrt the other native windows
1304  * in the hierarchy, given the position it has in the client side data.
1305  * This is useful if some operation changed the stacking order.
1306  * This calls assumes the native window is now topmost in its native parent.
1307  */
1308 static void
1309 sync_native_window_stack_position (GdkWindow *window)
1310 {
1311   GdkWindow *above;
1312   GdkWindowImplClass *impl_class;
1313   GList listhead = {0};
1314
1315   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
1316
1317   above = find_native_sibling_above (window->parent, window);
1318   if (above)
1319     {
1320       listhead.data = window;
1321       impl_class->restack_under (above, &listhead);
1322     }
1323 }
1324
1325 /**
1326  * gdk_window_new: (constructor)
1327  * @parent: (allow-none): a #GdkWindow, or %NULL to create the window as a child of
1328  *   the default root window for the default display.
1329  * @attributes: attributes of the new window
1330  * @attributes_mask: (type GdkWindowAttributesType): mask indicating which
1331  *   fields in @attributes are valid
1332  *
1333  * Creates a new #GdkWindow using the attributes from
1334  * @attributes. See #GdkWindowAttr and #GdkWindowAttributesType for
1335  * more details.  Note: to use this on displays other than the default
1336  * display, @parent must be specified.
1337  *
1338  * Return value: (transfer full): the new #GdkWindow
1339  **/
1340 GdkWindow*
1341 gdk_window_new (GdkWindow     *parent,
1342                 GdkWindowAttr *attributes,
1343                 gint           attributes_mask)
1344 {
1345   GdkWindow *window;
1346   GdkScreen *screen;
1347   GdkDisplay *display;
1348   int x, y;
1349   gboolean native;
1350   GdkEventMask event_mask;
1351   GdkWindow *real_parent;
1352   GdkDeviceManager *device_manager;
1353
1354   g_return_val_if_fail (attributes != NULL, NULL);
1355
1356   if (!parent)
1357     {
1358       GDK_NOTE (MULTIHEAD,
1359                 g_warning ("gdk_window_new(): no parent specified reverting to parent = default root window"));
1360
1361       screen = gdk_screen_get_default ();
1362       parent = gdk_screen_get_root_window (screen);
1363     }
1364   else
1365     screen = gdk_window_get_screen (parent);
1366
1367   g_return_val_if_fail (GDK_IS_WINDOW (parent), NULL);
1368
1369   if (GDK_WINDOW_DESTROYED (parent))
1370     {
1371       g_warning ("gdk_window_new(): parent is destroyed\n");
1372       return NULL;
1373     }
1374
1375   if (attributes_mask & GDK_WA_VISUAL)
1376     {
1377       g_return_val_if_fail (gdk_visual_get_screen (attributes->visual) == screen, NULL);
1378     }
1379
1380   display = gdk_screen_get_display (screen);
1381
1382   window = _gdk_display_create_window (display);
1383
1384   /* Windows with a foreign parent are treated as if they are children
1385    * of the root window, except for actual creation.
1386    */
1387   real_parent = parent;
1388   if (GDK_WINDOW_TYPE (parent) == GDK_WINDOW_FOREIGN)
1389     parent = gdk_screen_get_root_window (screen);
1390
1391   window->parent = parent;
1392
1393   window->accept_focus = TRUE;
1394   window->focus_on_map = TRUE;
1395
1396   if (attributes_mask & GDK_WA_X)
1397     x = attributes->x;
1398   else
1399     x = 0;
1400
1401   if (attributes_mask & GDK_WA_Y)
1402     y = attributes->y;
1403   else
1404     y = 0;
1405
1406   window->x = x;
1407   window->y = y;
1408   window->width = (attributes->width > 1) ? (attributes->width) : (1);
1409   window->height = (attributes->height > 1) ? (attributes->height) : (1);
1410   window->alpha = 255;
1411
1412   if (attributes->wclass == GDK_INPUT_ONLY)
1413     {
1414       /* Backwards compatiblity - we've always ignored
1415        * attributes->window_type for input-only windows
1416        * before
1417        */
1418       if (GDK_WINDOW_TYPE (parent) == GDK_WINDOW_ROOT)
1419         window->window_type = GDK_WINDOW_TEMP;
1420       else
1421         window->window_type = GDK_WINDOW_CHILD;
1422     }
1423   else
1424     window->window_type = attributes->window_type;
1425
1426   /* Sanity checks */
1427   switch (window->window_type)
1428     {
1429     case GDK_WINDOW_TOPLEVEL:
1430     case GDK_WINDOW_TEMP:
1431     case GDK_WINDOW_OFFSCREEN:
1432       if (GDK_WINDOW_TYPE (parent) != GDK_WINDOW_ROOT)
1433         g_warning (G_STRLOC "Toplevel windows must be created as children of\n"
1434                    "of a window of type GDK_WINDOW_ROOT or GDK_WINDOW_FOREIGN");
1435     case GDK_WINDOW_CHILD:
1436       break;
1437       break;
1438     default:
1439       g_warning (G_STRLOC "cannot make windows of type %d", window->window_type);
1440       return NULL;
1441     }
1442
1443   if (attributes_mask & GDK_WA_VISUAL)
1444     window->visual = attributes->visual;
1445   else
1446     window->visual = gdk_screen_get_system_visual (screen);
1447
1448   window->event_mask = attributes->event_mask;
1449
1450   if (attributes->wclass == GDK_INPUT_OUTPUT)
1451     {
1452       window->input_only = FALSE;
1453       window->depth = window->visual->depth;
1454
1455       /* XXX: Cache this somehow? */
1456       window->background = cairo_pattern_create_rgba (0, 0, 0, 0);
1457       window->has_alpha_background = TRUE;
1458     }
1459   else
1460     {
1461       window->depth = 0;
1462       window->input_only = TRUE;
1463     }
1464
1465   if (window->parent)
1466     window->parent->children = g_list_prepend (window->parent->children, window);
1467
1468   native = FALSE;
1469   if (window->parent->window_type == GDK_WINDOW_ROOT)
1470     native = TRUE; /* Always use native windows for toplevels */
1471   else if (!window->input_only &&
1472            (attributes_mask & GDK_WA_VISUAL &&
1473             attributes->visual != gdk_window_get_visual (window->parent)))
1474     native = TRUE; /* InputOutput window with different visual than parent, needs native window */
1475
1476   if (gdk_window_is_offscreen (window))
1477     {
1478       _gdk_offscreen_window_new (window, attributes, attributes_mask);
1479       window->impl_window = window;
1480     }
1481   else if (native)
1482     {
1483       event_mask = get_native_event_mask (window);
1484
1485       /* Create the impl */
1486       _gdk_display_create_window_impl (display, window, real_parent, screen, event_mask, attributes, attributes_mask);
1487       window->impl_window = window;
1488
1489       /* This will put the native window topmost in the native parent, which may
1490        * be wrong wrt other native windows in the non-native hierarchy, so restack */
1491       if (!_gdk_window_has_impl (real_parent))
1492         sync_native_window_stack_position (window);
1493     }
1494   else
1495     {
1496       window->impl_window = g_object_ref (window->parent->impl_window);
1497       window->impl = g_object_ref (window->impl_window->impl);
1498     }
1499
1500   recompute_visible_regions (window, TRUE, FALSE);
1501
1502   gdk_window_set_cursor (window, ((attributes_mask & GDK_WA_CURSOR) ?
1503                                   (attributes->cursor) :
1504                                   NULL));
1505
1506   device_manager = gdk_display_get_device_manager (gdk_window_get_display (parent));
1507   g_signal_connect (device_manager, "device-removed",
1508                     G_CALLBACK (device_removed_cb), window);
1509
1510   return window;
1511 }
1512
1513 static gboolean
1514 is_parent_of (GdkWindow *parent,
1515               GdkWindow *child)
1516 {
1517   GdkWindow *w;
1518
1519   w = child;
1520   while (w != NULL)
1521     {
1522       if (w == parent)
1523         return TRUE;
1524
1525       w = gdk_window_get_parent (w);
1526     }
1527
1528   return FALSE;
1529 }
1530
1531 static void
1532 change_impl (GdkWindow *private,
1533              GdkWindow *impl_window,
1534              GdkWindowImpl *new)
1535 {
1536   GList *l;
1537   GdkWindow *child;
1538   GdkWindowImpl *old_impl;
1539   GdkWindow *old_impl_window;
1540
1541   old_impl = private->impl;
1542   old_impl_window = private->impl_window;
1543   if (private != impl_window)
1544     private->impl_window = g_object_ref (impl_window);
1545   else
1546     private->impl_window = private;
1547   private->impl = g_object_ref (new);
1548   if (old_impl_window != private)
1549     g_object_unref (old_impl_window);
1550   g_object_unref (old_impl);
1551
1552   for (l = private->children; l != NULL; l = l->next)
1553     {
1554       child = l->data;
1555
1556       if (child->impl == old_impl)
1557         change_impl (child, impl_window, new);
1558     }
1559 }
1560
1561 static void
1562 reparent_to_impl (GdkWindow *private)
1563 {
1564   GList *l;
1565   GdkWindow *child;
1566   gboolean show;
1567   GdkWindowImplClass *impl_class;
1568
1569   impl_class = GDK_WINDOW_IMPL_GET_CLASS (private->impl);
1570
1571   /* Enumerate in reverse order so we get the right order for the native
1572      windows (first in childrens list is topmost, and reparent places on top) */
1573   for (l = g_list_last (private->children); l != NULL; l = l->prev)
1574     {
1575       child = l->data;
1576
1577       if (child->impl == private->impl)
1578         reparent_to_impl (child);
1579       else
1580         {
1581           show = impl_class->reparent ((GdkWindow *)child,
1582                                        (GdkWindow *)private,
1583                                        child->x, child->y);
1584           if (show)
1585             gdk_window_show_unraised ((GdkWindow *)child);
1586         }
1587     }
1588 }
1589
1590
1591 /**
1592  * gdk_window_reparent:
1593  * @window: a #GdkWindow
1594  * @new_parent: new parent to move @window into
1595  * @x: X location inside the new parent
1596  * @y: Y location inside the new parent
1597  *
1598  * Reparents @window into the given @new_parent. The window being
1599  * reparented will be unmapped as a side effect.
1600  *
1601  **/
1602 void
1603 gdk_window_reparent (GdkWindow *window,
1604                      GdkWindow *new_parent,
1605                      gint       x,
1606                      gint       y)
1607 {
1608   GdkWindow *old_parent;
1609   GdkScreen *screen;
1610   gboolean show, was_mapped, applied_clip_as_shape;
1611   gboolean do_reparent_to_impl;
1612   GdkEventMask old_native_event_mask;
1613   GdkWindowImplClass *impl_class;
1614
1615   g_return_if_fail (GDK_IS_WINDOW (window));
1616   g_return_if_fail (new_parent == NULL || GDK_IS_WINDOW (new_parent));
1617   g_return_if_fail (GDK_WINDOW_TYPE (window) != GDK_WINDOW_ROOT);
1618
1619   if (GDK_WINDOW_DESTROYED (window) ||
1620       (new_parent && GDK_WINDOW_DESTROYED (new_parent)))
1621     return;
1622
1623   screen = gdk_window_get_screen (window);
1624   if (!new_parent)
1625     new_parent = gdk_screen_get_root_window (screen);
1626
1627   /* No input-output children of input-only windows */
1628   if (new_parent->input_only && !window->input_only)
1629     return;
1630
1631   /* Don't create loops in hierarchy */
1632   if (is_parent_of (window, new_parent))
1633     return;
1634
1635   /* This might be wrong in the new parent, e.g. for non-native surfaces.
1636      To make sure we're ok, just wipe it. */
1637   gdk_window_drop_cairo_surface (window);
1638
1639   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
1640   old_parent = window->parent;
1641
1642   was_mapped = GDK_WINDOW_IS_MAPPED (window);
1643   show = FALSE;
1644
1645   /* Reparenting to toplevel. Ensure we have a native window so this can work */
1646   if (new_parent->window_type == GDK_WINDOW_ROOT ||
1647       new_parent->window_type == GDK_WINDOW_FOREIGN)
1648     gdk_window_ensure_native (window);
1649
1650   applied_clip_as_shape = should_apply_clip_as_shape (window);
1651
1652   old_native_event_mask = 0;
1653   do_reparent_to_impl = FALSE;
1654   if (gdk_window_has_impl (window))
1655     {
1656       old_native_event_mask = get_native_event_mask (window);
1657       /* Native window */
1658       show = impl_class->reparent (window, new_parent, x, y);
1659     }
1660   else
1661     {
1662       /* This shouldn't happen, as we created a native in this case, check anyway to see if that ever fails */
1663       g_assert (new_parent->window_type != GDK_WINDOW_ROOT &&
1664                 new_parent->window_type != GDK_WINDOW_FOREIGN);
1665
1666       show = was_mapped;
1667       gdk_window_hide (window);
1668
1669       do_reparent_to_impl = TRUE;
1670       change_impl (window,
1671                    new_parent->impl_window,
1672                    new_parent->impl);
1673     }
1674
1675   /* From here on, we treat parents of type GDK_WINDOW_FOREIGN like
1676    * the root window
1677    */
1678   if (GDK_WINDOW_TYPE (new_parent) == GDK_WINDOW_FOREIGN)
1679     {
1680       new_parent = gdk_screen_get_root_window (screen);
1681     }
1682
1683   if (old_parent)
1684     old_parent->children = g_list_remove (old_parent->children, window);
1685
1686   window->parent = new_parent;
1687   window->x = x;
1688   window->y = y;
1689
1690   new_parent->children = g_list_prepend (new_parent->children, window);
1691
1692   /* Switch the window type as appropriate */
1693
1694   switch (GDK_WINDOW_TYPE (new_parent))
1695     {
1696     case GDK_WINDOW_ROOT:
1697     case GDK_WINDOW_FOREIGN:
1698       if (window->toplevel_window_type != -1)
1699         GDK_WINDOW_TYPE (window) = window->toplevel_window_type;
1700       else if (GDK_WINDOW_TYPE (window) == GDK_WINDOW_CHILD)
1701         GDK_WINDOW_TYPE (window) = GDK_WINDOW_TOPLEVEL;
1702       break;
1703     case GDK_WINDOW_OFFSCREEN:
1704     case GDK_WINDOW_TOPLEVEL:
1705     case GDK_WINDOW_CHILD:
1706     case GDK_WINDOW_TEMP:
1707       if (GDK_WINDOW_TYPE (window) != GDK_WINDOW_CHILD && \
1708           GDK_WINDOW_TYPE (window) != GDK_WINDOW_FOREIGN)
1709         {
1710           /* Save the original window type so we can restore it if the
1711            * window is reparented back to be a toplevel
1712            */
1713           window->toplevel_window_type = GDK_WINDOW_TYPE (window);
1714           GDK_WINDOW_TYPE (window) = GDK_WINDOW_CHILD;
1715         }
1716     }
1717
1718   /* We might have changed window type for a native windows, so we
1719      need to change the event mask too. */
1720   if (gdk_window_has_impl (window))
1721     {
1722       GdkEventMask native_event_mask = get_native_event_mask (window);
1723
1724       if (native_event_mask != old_native_event_mask)
1725         impl_class->set_events (window, native_event_mask);
1726     }
1727
1728   _gdk_window_update_viewable (window);
1729
1730   if (window->background == NULL)
1731     {
1732       /* parent relative background, update has_alpha_background */
1733       if (window->parent == NULL ||
1734           window->parent->window_type == GDK_WINDOW_ROOT)
1735         window->has_alpha_background = FALSE;
1736       else
1737         window->has_alpha_background = window->parent->has_alpha_background;
1738     }
1739
1740   recompute_visible_regions (window, TRUE, FALSE);
1741   if (old_parent && GDK_WINDOW_TYPE (old_parent) != GDK_WINDOW_ROOT)
1742     recompute_visible_regions (old_parent, FALSE, TRUE);
1743
1744   _gdk_window_propagate_has_alpha_background (window);
1745
1746   /* We used to apply the clip as the shape, but no more.
1747      Reset this to the real shape */
1748   if (gdk_window_has_impl (window) &&
1749       applied_clip_as_shape &&
1750       !should_apply_clip_as_shape (window))
1751     apply_shape (window, window->shape);
1752
1753   if (do_reparent_to_impl)
1754     reparent_to_impl (window);
1755   else
1756     {
1757       /* The reparent will have put the native window topmost in the native parent,
1758        * which may be wrong wrt other native windows in the non-native hierarchy,
1759        * so restack */
1760       if (!gdk_window_has_impl (new_parent))
1761         sync_native_window_stack_position (window);
1762     }
1763
1764   if (show)
1765     gdk_window_show_unraised (window);
1766   else
1767     _gdk_synthesize_crossing_events_for_geometry_change (window);
1768 }
1769
1770 /**
1771  * gdk_window_ensure_native:
1772  * @window: a #GdkWindow
1773  *
1774  * Tries to ensure that there is a window-system native window for this
1775  * GdkWindow. This may fail in some situations, returning %FALSE.
1776  *
1777  * Offscreen window and children of them can never have native windows.
1778  *
1779  * Some backends may not support native child windows.
1780  *
1781  * Returns: %TRUE if the window has a native window, %FALSE otherwise
1782  *
1783  * Since: 2.18
1784  */
1785 gboolean
1786 gdk_window_ensure_native (GdkWindow *window)
1787 {
1788   GdkWindow *impl_window;
1789   GdkWindowImpl *new_impl, *old_impl;
1790   GdkDisplay *display;
1791   GdkScreen *screen;
1792   GdkWindow *above;
1793   GList listhead;
1794   GdkWindowImplClass *impl_class;
1795
1796   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
1797
1798   if (GDK_WINDOW_TYPE (window) == GDK_WINDOW_ROOT ||
1799       GDK_WINDOW_DESTROYED (window))
1800     return FALSE;
1801
1802   impl_window = gdk_window_get_impl_window (window);
1803
1804   if (gdk_window_is_offscreen (impl_window))
1805     return FALSE; /* native in offscreens not supported */
1806
1807   if (impl_window == window)
1808     /* Already has an impl, and its not offscreen . */
1809     return TRUE;
1810
1811   /* Need to create a native window */
1812
1813   gdk_window_drop_cairo_surface (window);
1814
1815   screen = gdk_window_get_screen (window);
1816   display = gdk_screen_get_display (screen);
1817
1818   old_impl = window->impl;
1819   _gdk_display_create_window_impl (display,
1820                                    window, window->parent,
1821                                    screen,
1822                                    get_native_event_mask (window),
1823                                    NULL, 0);
1824   new_impl = window->impl;
1825
1826   window->impl = old_impl;
1827   change_impl (window, window, new_impl);
1828
1829   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
1830
1831   /* Native window creation will put the native window topmost in the
1832    * native parent, which may be wrong wrt the position of the previous
1833    * non-native window wrt to the other non-native children, so correct this.
1834    */
1835   above = find_native_sibling_above (window->parent, window);
1836   if (above)
1837     {
1838       listhead.data = window;
1839       listhead.prev = NULL;
1840       listhead.next = NULL;
1841       impl_class->restack_under ((GdkWindow *)above, &listhead);
1842     }
1843
1844   recompute_visible_regions (window, FALSE, FALSE);
1845
1846   /* The shape may not have been set, as the clip region doesn't actually
1847      change, so do it here manually */
1848   if (should_apply_clip_as_shape (window))
1849     apply_clip_as_shape (window);
1850
1851   reparent_to_impl (window);
1852
1853   if (!window->input_only)
1854     impl_class->set_background (window, window->background);
1855
1856   impl_class->input_shape_combine_region (window,
1857                                           window->input_shape,
1858                                           0, 0);
1859
1860   if (gdk_window_is_viewable (window))
1861     impl_class->show (window, FALSE);
1862
1863   return TRUE;
1864 }
1865
1866 /**
1867  * _gdk_event_filter_unref:
1868  * @window: (allow-none): A #GdkWindow, or %NULL to be the global window
1869  * @filter: A window filter
1870  *
1871  * Release a reference to @filter.  Note this function may
1872  * mutate the list storage, so you need to handle this
1873  * if iterating over a list of filters.
1874  */
1875 void
1876 _gdk_event_filter_unref (GdkWindow       *window,
1877                          GdkEventFilter  *filter)
1878 {
1879   GList **filters;
1880   GList *tmp_list;
1881
1882   if (window == NULL)
1883     filters = &_gdk_default_filters;
1884   else
1885     filters = &window->filters;
1886
1887   tmp_list = *filters;
1888   while (tmp_list)
1889     {
1890       GdkEventFilter *iter_filter = tmp_list->data;
1891       GList *node;
1892
1893       node = tmp_list;
1894       tmp_list = tmp_list->next;
1895
1896       if (iter_filter != filter)
1897         continue;
1898
1899       g_assert (iter_filter->ref_count > 0);
1900
1901       filter->ref_count--;
1902       if (filter->ref_count != 0)
1903         continue;
1904
1905       *filters = g_list_remove_link (*filters, node);
1906       g_free (filter);
1907       g_list_free_1 (node);
1908     }
1909 }
1910
1911 static void
1912 window_remove_filters (GdkWindow *window)
1913 {
1914   while (window->filters)
1915     _gdk_event_filter_unref (window, window->filters->data);
1916 }
1917
1918 static void
1919 update_pointer_info_foreach (GdkDisplay           *display,
1920                              GdkDevice            *device,
1921                              GdkPointerWindowInfo *pointer_info,
1922                              gpointer              user_data)
1923 {
1924   GdkWindow *window = user_data;
1925
1926   if (pointer_info->toplevel_under_pointer == window)
1927     {
1928       g_object_unref (pointer_info->toplevel_under_pointer);
1929       pointer_info->toplevel_under_pointer = NULL;
1930     }
1931 }
1932
1933 static void
1934 window_remove_from_pointer_info (GdkWindow  *window,
1935                                  GdkDisplay *display)
1936 {
1937   _gdk_display_pointer_info_foreach (display,
1938                                      update_pointer_info_foreach,
1939                                      window);
1940 }
1941
1942 /**
1943  * _gdk_window_destroy_hierarchy:
1944  * @window: a #GdkWindow
1945  * @recursing: If TRUE, then this is being called because a parent
1946  *            was destroyed.
1947  * @recursing_native: If TRUE, then this is being called because a native parent
1948  *            was destroyed. This generally means that the call to the
1949  *            windowing system to destroy the window can be omitted, since
1950  *            it will be destroyed as a result of the parent being destroyed.
1951  *            Unless @foreign_destroy.
1952  * @foreign_destroy: If TRUE, the window or a parent was destroyed by some
1953  *            external agency. The window has already been destroyed and no
1954  *            windowing system calls should be made. (This may never happen
1955  *            for some windowing systems.)
1956  *
1957  * Internal function to destroy a window. Like gdk_window_destroy(),
1958  * but does not drop the reference count created by gdk_window_new().
1959  **/
1960 static void
1961 _gdk_window_destroy_hierarchy (GdkWindow *window,
1962                                gboolean   recursing,
1963                                gboolean   recursing_native,
1964                                gboolean   foreign_destroy)
1965 {
1966   GdkWindowImplClass *impl_class;
1967   GdkWindow *temp_window;
1968   GdkScreen *screen;
1969   GdkDisplay *display;
1970   GList *children;
1971   GList *tmp;
1972
1973   g_return_if_fail (GDK_IS_WINDOW (window));
1974
1975   if (GDK_WINDOW_DESTROYED (window))
1976     return;
1977
1978   display = gdk_window_get_display (window);
1979   screen = gdk_window_get_screen (window);
1980   temp_window = g_object_get_qdata (G_OBJECT (screen), quark_pointer_window);
1981   if (temp_window == window)
1982     g_object_set_qdata (G_OBJECT (screen), quark_pointer_window, NULL);
1983
1984
1985   switch (window->window_type)
1986     {
1987     case GDK_WINDOW_ROOT:
1988       if (!screen->closed)
1989         {
1990           g_error ("attempted to destroy root window");
1991           break;
1992         }
1993       /* else fall thru */
1994     case GDK_WINDOW_TOPLEVEL:
1995     case GDK_WINDOW_CHILD:
1996     case GDK_WINDOW_TEMP:
1997     case GDK_WINDOW_FOREIGN:
1998     case GDK_WINDOW_OFFSCREEN:
1999       if (window->window_type == GDK_WINDOW_FOREIGN && !foreign_destroy)
2000         {
2001           /* Logically, it probably makes more sense to send
2002            * a "destroy yourself" message to the foreign window
2003            * whether or not it's in our hierarchy; but for historical
2004            * reasons, we only send "destroy yourself" messages to
2005            * foreign windows in our hierarchy.
2006            */
2007           if (window->parent)
2008             {
2009               impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
2010
2011               if (gdk_window_has_impl (window))
2012                 impl_class->destroy_foreign (window);
2013             }
2014
2015           /* Also for historical reasons, we remove any filters
2016            * on a foreign window when it or a parent is destroyed;
2017            * this likely causes problems if two separate portions
2018            * of code are maintaining filter lists on a foreign window.
2019            */
2020           window_remove_filters (window);
2021         }
2022       else
2023         {
2024           if (window->parent)
2025             {
2026               if (window->parent->children)
2027                 window->parent->children = g_list_remove (window->parent->children, window);
2028
2029               if (!recursing &&
2030                   GDK_WINDOW_IS_MAPPED (window))
2031                 {
2032                   recompute_visible_regions (window, TRUE, FALSE);
2033                   gdk_window_invalidate_in_parent (window);
2034                 }
2035             }
2036
2037           gdk_window_free_paint_stack (window);
2038
2039           if (window->background)
2040             {
2041               cairo_pattern_destroy (window->background);
2042               window->background = NULL;
2043             }
2044
2045           if (window->window_type == GDK_WINDOW_FOREIGN)
2046             g_assert (window->children == NULL);
2047           else
2048             {
2049               children = tmp = window->children;
2050               window->children = NULL;
2051
2052               while (tmp)
2053                 {
2054                   temp_window = tmp->data;
2055                   tmp = tmp->next;
2056
2057                   if (temp_window)
2058                     _gdk_window_destroy_hierarchy (temp_window,
2059                                                    TRUE,
2060                                                    recursing_native || gdk_window_has_impl (window),
2061                                                    foreign_destroy);
2062                 }
2063
2064               g_list_free (children);
2065             }
2066
2067           _gdk_window_clear_update_area (window);
2068
2069           gdk_window_drop_cairo_surface (window);
2070
2071           impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
2072
2073           if (gdk_window_has_impl (window))
2074             impl_class->destroy (window, recursing_native,
2075                                  foreign_destroy);
2076           else
2077             {
2078               /* hide to make sure we repaint and break grabs */
2079               gdk_window_hide (window);
2080             }
2081
2082           window->state |= GDK_WINDOW_STATE_WITHDRAWN;
2083           window->parent = NULL;
2084           window->destroyed = TRUE;
2085
2086           window_remove_filters (window);
2087
2088           window_remove_from_pointer_info (window, display);
2089
2090           if (window->clip_region)
2091             {
2092               cairo_region_destroy (window->clip_region);
2093               window->clip_region = NULL;
2094             }
2095
2096           if (window->clip_region_with_children)
2097             {
2098               cairo_region_destroy (window->clip_region_with_children);
2099               window->clip_region_with_children = NULL;
2100             }
2101
2102           g_list_free_full (window->outstanding_moves, (GDestroyNotify) gdk_window_region_move_free);
2103           window->outstanding_moves = NULL;
2104         }
2105       break;
2106     }
2107 }
2108
2109 /**
2110  * _gdk_window_destroy:
2111  * @window: a #GdkWindow
2112  * @foreign_destroy: If TRUE, the window or a parent was destroyed by some
2113  *            external agency. The window has already been destroyed and no
2114  *            windowing system calls should be made. (This may never happen
2115  *            for some windowing systems.)
2116  *
2117  * Internal function to destroy a window. Like gdk_window_destroy(),
2118  * but does not drop the reference count created by gdk_window_new().
2119  **/
2120 void
2121 _gdk_window_destroy (GdkWindow *window,
2122                      gboolean   foreign_destroy)
2123 {
2124   _gdk_window_destroy_hierarchy (window, FALSE, FALSE, foreign_destroy);
2125 }
2126
2127 /**
2128  * gdk_window_destroy:
2129  * @window: a #GdkWindow
2130  *
2131  * Destroys the window system resources associated with @window and decrements @window's
2132  * reference count. The window system resources for all children of @window are also
2133  * destroyed, but the children's reference counts are not decremented.
2134  *
2135  * Note that a window will not be destroyed automatically when its reference count
2136  * reaches zero. You must call this function yourself before that happens.
2137  *
2138  **/
2139 void
2140 gdk_window_destroy (GdkWindow *window)
2141 {
2142   _gdk_window_destroy_hierarchy (window, FALSE, FALSE, FALSE);
2143   g_object_unref (window);
2144 }
2145
2146 /**
2147  * gdk_window_set_user_data:
2148  * @window: a #GdkWindow
2149  * @user_data: (allow-none) (type GObject.Object): user data
2150  *
2151  * For most purposes this function is deprecated in favor of
2152  * g_object_set_data(). However, for historical reasons GTK+ stores
2153  * the #GtkWidget that owns a #GdkWindow as user data on the
2154  * #GdkWindow. So, custom widget implementations should use
2155  * this function for that. If GTK+ receives an event for a #GdkWindow,
2156  * and the user data for the window is non-%NULL, GTK+ will assume the
2157  * user data is a #GtkWidget, and forward the event to that widget.
2158  *
2159  **/
2160 void
2161 gdk_window_set_user_data (GdkWindow *window,
2162                           gpointer   user_data)
2163 {
2164   g_return_if_fail (GDK_IS_WINDOW (window));
2165
2166   window->user_data = user_data;
2167 }
2168
2169 /**
2170  * gdk_window_get_user_data:
2171  * @window: a #GdkWindow
2172  * @data: (out): return location for user data
2173  *
2174  * Retrieves the user data for @window, which is normally the widget
2175  * that @window belongs to. See gdk_window_set_user_data().
2176  *
2177  **/
2178 void
2179 gdk_window_get_user_data (GdkWindow *window,
2180                           gpointer  *data)
2181 {
2182   g_return_if_fail (GDK_IS_WINDOW (window));
2183
2184   *data = window->user_data;
2185 }
2186
2187 /**
2188  * gdk_window_get_window_type:
2189  * @window: a #GdkWindow
2190  *
2191  * Gets the type of the window. See #GdkWindowType.
2192  *
2193  * Return value: type of window
2194  **/
2195 GdkWindowType
2196 gdk_window_get_window_type (GdkWindow *window)
2197 {
2198   g_return_val_if_fail (GDK_IS_WINDOW (window), (GdkWindowType) -1);
2199
2200   return GDK_WINDOW_TYPE (window);
2201 }
2202
2203 /**
2204  * gdk_window_get_visual:
2205  * @window: a #GdkWindow
2206  * 
2207  * Gets the #GdkVisual describing the pixel format of @window.
2208  * 
2209  * Return value: (transfer none): a #GdkVisual
2210  *
2211  * Since: 2.24
2212  **/
2213 GdkVisual*
2214 gdk_window_get_visual (GdkWindow *window)
2215 {
2216   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2217   
2218   return window->visual;
2219 }
2220
2221 /**
2222  * gdk_window_get_screen:
2223  * @window: a #GdkWindow
2224  * 
2225  * Gets the #GdkScreen associated with a #GdkWindow.
2226  * 
2227  * Return value: (transfer none): the #GdkScreen associated with @window
2228  *
2229  * Since: 2.24
2230  **/
2231 GdkScreen*
2232 gdk_window_get_screen (GdkWindow *window)
2233 {
2234   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2235
2236   return gdk_visual_get_screen (window->visual);
2237 }
2238
2239 /**
2240  * gdk_window_get_display:
2241  * @window: a #GdkWindow
2242  * 
2243  * Gets the #GdkDisplay associated with a #GdkWindow.
2244  * 
2245  * Return value: (transfer none): the #GdkDisplay associated with @window
2246  *
2247  * Since: 2.24
2248  **/
2249 GdkDisplay *
2250 gdk_window_get_display (GdkWindow *window)
2251 {
2252   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2253
2254   return gdk_screen_get_display (gdk_visual_get_screen (window->visual));
2255 }
2256 /**
2257  * gdk_window_is_destroyed:
2258  * @window: a #GdkWindow
2259  *
2260  * Check to see if a window is destroyed..
2261  *
2262  * Return value: %TRUE if the window is destroyed
2263  *
2264  * Since: 2.18
2265  **/
2266 gboolean
2267 gdk_window_is_destroyed (GdkWindow *window)
2268 {
2269   return GDK_WINDOW_DESTROYED (window);
2270 }
2271
2272 static void
2273 to_embedder (GdkWindow *window,
2274              gdouble    offscreen_x,
2275              gdouble    offscreen_y,
2276              gdouble   *embedder_x,
2277              gdouble   *embedder_y)
2278 {
2279   g_signal_emit (window, signals[TO_EMBEDDER], 0,
2280                  offscreen_x, offscreen_y,
2281                  embedder_x, embedder_y);
2282 }
2283
2284 static void
2285 from_embedder (GdkWindow *window,
2286                gdouble    embedder_x,
2287                gdouble    embedder_y,
2288                gdouble   *offscreen_x,
2289                gdouble   *offscreen_y)
2290 {
2291   g_signal_emit (window, signals[FROM_EMBEDDER], 0,
2292                  embedder_x, embedder_y,
2293                  offscreen_x, offscreen_y);
2294 }
2295
2296 /**
2297  * gdk_window_has_native:
2298  * @window: a #GdkWindow
2299  *
2300  * Checks whether the window has a native window or not. Note that
2301  * you can use gdk_window_ensure_native() if a native window is needed.
2302  *
2303  * Returns: %TRUE if the %window has a native window, %FALSE otherwise.
2304  *
2305  * Since: 2.22
2306  */
2307 gboolean
2308 gdk_window_has_native (GdkWindow *window)
2309 {
2310   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
2311
2312   return window->parent == NULL || window->parent->impl != window->impl;
2313 }
2314
2315 /**
2316  * gdk_window_get_position:
2317  * @window: a #GdkWindow
2318  * @x: (out) (allow-none): X coordinate of window
2319  * @y: (out) (allow-none): Y coordinate of window
2320  *
2321  * Obtains the position of the window as reported in the
2322  * most-recently-processed #GdkEventConfigure. Contrast with
2323  * gdk_window_get_geometry() which queries the X server for the
2324  * current window position, regardless of which events have been
2325  * received or processed.
2326  *
2327  * The position coordinates are relative to the window's parent window.
2328  *
2329  **/
2330 void
2331 gdk_window_get_position (GdkWindow *window,
2332                          gint      *x,
2333                          gint      *y)
2334 {
2335   g_return_if_fail (GDK_IS_WINDOW (window));
2336
2337   if (x)
2338     *x = window->x;
2339   if (y)
2340     *y = window->y;
2341 }
2342
2343 /**
2344  * gdk_window_get_parent:
2345  * @window: a #GdkWindow
2346  *
2347  * Obtains the parent of @window, as known to GDK. Does not query the
2348  * X server; thus this returns the parent as passed to gdk_window_new(),
2349  * not the actual parent. This should never matter unless you're using
2350  * Xlib calls mixed with GDK calls on the X11 platform. It may also
2351  * matter for toplevel windows, because the window manager may choose
2352  * to reparent them.
2353  *
2354  * Note that you should use gdk_window_get_effective_parent() when
2355  * writing generic code that walks up a window hierarchy, because
2356  * gdk_window_get_parent() will most likely not do what you expect if
2357  * there are offscreen windows in the hierarchy.
2358  *
2359  * Return value: (transfer none): parent of @window
2360  **/
2361 GdkWindow*
2362 gdk_window_get_parent (GdkWindow *window)
2363 {
2364   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2365
2366   return window->parent;
2367 }
2368
2369 /**
2370  * gdk_window_get_effective_parent:
2371  * @window: a #GdkWindow
2372  *
2373  * Obtains the parent of @window, as known to GDK. Works like
2374  * gdk_window_get_parent() for normal windows, but returns the
2375  * window's embedder for offscreen windows.
2376  *
2377  * See also: gdk_offscreen_window_get_embedder()
2378  *
2379  * Return value: (transfer none): effective parent of @window
2380  *
2381  * Since: 2.22
2382  **/
2383 GdkWindow *
2384 gdk_window_get_effective_parent (GdkWindow *window)
2385 {
2386   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2387
2388   if (gdk_window_is_offscreen (window))
2389     return gdk_offscreen_window_get_embedder (window);
2390   else
2391     return window->parent;
2392 }
2393
2394 /**
2395  * gdk_window_get_toplevel:
2396  * @window: a #GdkWindow
2397  *
2398  * Gets the toplevel window that's an ancestor of @window.
2399  *
2400  * Any window type but %GDK_WINDOW_CHILD is considered a
2401  * toplevel window, as is a %GDK_WINDOW_CHILD window that
2402  * has a root window as parent.
2403  *
2404  * Note that you should use gdk_window_get_effective_toplevel() when
2405  * you want to get to a window's toplevel as seen on screen, because
2406  * gdk_window_get_toplevel() will most likely not do what you expect
2407  * if there are offscreen windows in the hierarchy.
2408  *
2409  * Return value: (transfer none): the toplevel window containing @window
2410  **/
2411 GdkWindow *
2412 gdk_window_get_toplevel (GdkWindow *window)
2413 {
2414   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2415
2416   while (window->window_type == GDK_WINDOW_CHILD)
2417     {
2418       if (gdk_window_is_toplevel (window))
2419         break;
2420       window = window->parent;
2421     }
2422
2423   return window;
2424 }
2425
2426 /**
2427  * gdk_window_get_effective_toplevel:
2428  * @window: a #GdkWindow
2429  *
2430  * Gets the toplevel window that's an ancestor of @window.
2431  *
2432  * Works like gdk_window_get_toplevel(), but treats an offscreen window's
2433  * embedder as its parent, using gdk_window_get_effective_parent().
2434  *
2435  * See also: gdk_offscreen_window_get_embedder()
2436  *
2437  * Return value: (transfer none): the effective toplevel window containing @window
2438  *
2439  * Since: 2.22
2440  **/
2441 GdkWindow *
2442 gdk_window_get_effective_toplevel (GdkWindow *window)
2443 {
2444   GdkWindow *parent;
2445
2446   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2447
2448   while ((parent = gdk_window_get_effective_parent (window)) != NULL &&
2449          (gdk_window_get_window_type (parent) != GDK_WINDOW_ROOT))
2450     window = parent;
2451
2452   return window;
2453 }
2454
2455 /**
2456  * gdk_window_get_children:
2457  * @window: a #GdkWindow
2458  *
2459  * Gets the list of children of @window known to GDK.
2460  * This function only returns children created via GDK,
2461  * so for example it's useless when used with the root window;
2462  * it only returns windows an application created itself.
2463  *
2464  * The returned list must be freed, but the elements in the
2465  * list need not be.
2466  *
2467  * Return value: (transfer container) (element-type GdkWindow):
2468  *     list of child windows inside @window
2469  **/
2470 GList*
2471 gdk_window_get_children (GdkWindow *window)
2472 {
2473   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2474
2475   if (GDK_WINDOW_DESTROYED (window))
2476     return NULL;
2477
2478   return g_list_copy (window->children);
2479 }
2480
2481 /**
2482  * gdk_window_peek_children:
2483  * @window: a #GdkWindow
2484  *
2485  * Like gdk_window_get_children(), but does not copy the list of
2486  * children, so the list does not need to be freed.
2487  *
2488  * Return value: (transfer none) (element-type GdkWindow):
2489  *     a reference to the list of child windows in @window
2490  **/
2491 GList *
2492 gdk_window_peek_children (GdkWindow *window)
2493 {
2494   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
2495
2496   if (GDK_WINDOW_DESTROYED (window))
2497     return NULL;
2498
2499   return window->children;
2500 }
2501
2502 /**
2503  * gdk_window_add_filter: (skip)
2504  * @window: (allow-none): a #GdkWindow
2505  * @function: filter callback
2506  * @data: data to pass to filter callback
2507  *
2508  * Adds an event filter to @window, allowing you to intercept events
2509  * before they reach GDK. This is a low-level operation and makes it
2510  * easy to break GDK and/or GTK+, so you have to know what you're
2511  * doing. Pass %NULL for @window to get all events for all windows,
2512  * instead of events for a specific window.
2513  *
2514  * If you are interested in X GenericEvents, bear in mind that
2515  * XGetEventData() has been already called on the event, and
2516  * XFreeEventData() must not be called within @function.
2517  **/
2518 void
2519 gdk_window_add_filter (GdkWindow     *window,
2520                        GdkFilterFunc  function,
2521                        gpointer       data)
2522 {
2523   GList *tmp_list;
2524   GdkEventFilter *filter;
2525
2526   g_return_if_fail (window == NULL || GDK_IS_WINDOW (window));
2527
2528   if (window && GDK_WINDOW_DESTROYED (window))
2529     return;
2530
2531   /* Filters are for the native events on the native window, so
2532      ensure there is a native window. */
2533   if (window)
2534     gdk_window_ensure_native (window);
2535
2536   if (window)
2537     tmp_list = window->filters;
2538   else
2539     tmp_list = _gdk_default_filters;
2540
2541   while (tmp_list)
2542     {
2543       filter = (GdkEventFilter *)tmp_list->data;
2544       if ((filter->function == function) && (filter->data == data))
2545         {
2546           filter->ref_count++;
2547           return;
2548         }
2549       tmp_list = tmp_list->next;
2550     }
2551
2552   filter = g_new (GdkEventFilter, 1);
2553   filter->function = function;
2554   filter->data = data;
2555   filter->ref_count = 1;
2556   filter->flags = 0;
2557
2558   if (window)
2559     window->filters = g_list_append (window->filters, filter);
2560   else
2561     _gdk_default_filters = g_list_append (_gdk_default_filters, filter);
2562 }
2563
2564 /**
2565  * gdk_window_remove_filter: (skip)
2566  * @window: a #GdkWindow
2567  * @function: previously-added filter function
2568  * @data: user data for previously-added filter function
2569  *
2570  * Remove a filter previously added with gdk_window_add_filter().
2571  */
2572 void
2573 gdk_window_remove_filter (GdkWindow     *window,
2574                           GdkFilterFunc  function,
2575                           gpointer       data)
2576 {
2577   GList *tmp_list;
2578   GdkEventFilter *filter;
2579
2580   g_return_if_fail (window == NULL || GDK_IS_WINDOW (window));
2581
2582   if (window)
2583     tmp_list = window->filters;
2584   else
2585     tmp_list = _gdk_default_filters;
2586
2587   while (tmp_list)
2588     {
2589       filter = (GdkEventFilter *)tmp_list->data;
2590       tmp_list = tmp_list->next;
2591
2592       if ((filter->function == function) && (filter->data == data))
2593         {
2594           filter->flags |= GDK_EVENT_FILTER_REMOVED;
2595
2596           _gdk_event_filter_unref (window, filter);
2597
2598           return;
2599         }
2600     }
2601 }
2602
2603 /**
2604  * gdk_screen_get_toplevel_windows:
2605  * @screen: The #GdkScreen where the toplevels are located.
2606  *
2607  * Obtains a list of all toplevel windows known to GDK on the screen @screen.
2608  * A toplevel window is a child of the root window (see
2609  * gdk_get_default_root_window()).
2610  *
2611  * The returned list should be freed with g_list_free(), but
2612  * its elements need not be freed.
2613  *
2614  * Return value: (transfer container) (element-type GdkWindow):
2615  *     list of toplevel windows, free with g_list_free()
2616  *
2617  * Since: 2.2
2618  **/
2619 GList *
2620 gdk_screen_get_toplevel_windows (GdkScreen *screen)
2621 {
2622   GdkWindow * root_window;
2623   GList *new_list = NULL;
2624   GList *tmp_list;
2625
2626   g_return_val_if_fail (GDK_IS_SCREEN (screen), NULL);
2627
2628   root_window = gdk_screen_get_root_window (screen);
2629
2630   tmp_list = root_window->children;
2631   while (tmp_list)
2632     {
2633       GdkWindow *w = tmp_list->data;
2634
2635       if (w->window_type != GDK_WINDOW_FOREIGN)
2636         new_list = g_list_prepend (new_list, w);
2637       tmp_list = tmp_list->next;
2638     }
2639
2640   return new_list;
2641 }
2642
2643 /**
2644  * gdk_window_is_visible:
2645  * @window: a #GdkWindow
2646  *
2647  * Checks whether the window has been mapped (with gdk_window_show() or
2648  * gdk_window_show_unraised()).
2649  *
2650  * Return value: %TRUE if the window is mapped
2651  **/
2652 gboolean
2653 gdk_window_is_visible (GdkWindow *window)
2654 {
2655   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
2656
2657   return GDK_WINDOW_IS_MAPPED (window);
2658 }
2659
2660 /**
2661  * gdk_window_is_viewable:
2662  * @window: a #GdkWindow
2663  *
2664  * Check if the window and all ancestors of the window are
2665  * mapped. (This is not necessarily "viewable" in the X sense, since
2666  * we only check as far as we have GDK window parents, not to the root
2667  * window.)
2668  *
2669  * Return value: %TRUE if the window is viewable
2670  **/
2671 gboolean
2672 gdk_window_is_viewable (GdkWindow *window)
2673 {
2674   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
2675
2676   if (window->destroyed)
2677     return FALSE;
2678
2679   return window->viewable;
2680 }
2681
2682 /**
2683  * gdk_window_get_state:
2684  * @window: a #GdkWindow
2685  *
2686  * Gets the bitwise OR of the currently active window state flags,
2687  * from the #GdkWindowState enumeration.
2688  *
2689  * Return value: window state bitfield
2690  **/
2691 GdkWindowState
2692 gdk_window_get_state (GdkWindow *window)
2693 {
2694   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
2695
2696   return window->state;
2697 }
2698
2699 static cairo_content_t
2700 gdk_window_get_content (GdkWindow *window)
2701 {
2702   cairo_surface_t *surface;
2703   cairo_content_t content;
2704
2705   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
2706
2707   surface = gdk_window_ref_impl_surface (window);
2708   content = cairo_surface_get_content (surface);
2709   cairo_surface_destroy (surface);
2710
2711   return content;
2712 }
2713
2714 /* This creates an empty "implicit" paint region for the impl window.
2715  * By itself this does nothing, but real paints to this window
2716  * or children of it can use this surface as backing to avoid allocating
2717  * multiple surfaces for subwindow rendering. When doing so they
2718  * add to the region of the implicit paint region, which will be
2719  * pushed to the window when the implicit paint region is ended.
2720  * Such paints should not copy anything to the window on paint end, but
2721  * should rely on the implicit paint end.
2722  * The implicit paint will be automatically ended if someone draws
2723  * directly to the window or a child window.
2724  */
2725 static gboolean
2726 gdk_window_begin_implicit_paint (GdkWindow *window, GdkRectangle *rect,
2727                                  gboolean with_alpha, guint8 alpha)
2728 {
2729   GdkWindowPaint *paint;
2730
2731   g_assert (gdk_window_has_impl (window));
2732
2733   if (GDK_IS_PAINTABLE (window->impl))
2734     return FALSE; /* Implementation does double buffering */
2735
2736   if (window->paint_stack != NULL)
2737     return FALSE; /* Don't stack implicit paints */
2738
2739   /* Never do implicit paints for foreign windows, they don't need
2740    * double buffer combination since they have no client side children,
2741    * and creating surfaces for them is risky since they could disappear
2742    * at any time
2743    */
2744   if (window->window_type == GDK_WINDOW_FOREIGN)
2745     return FALSE;
2746
2747   paint = g_new (GdkWindowPaint, 1);
2748   paint->region = cairo_region_create (); /* Empty */
2749   paint->uses_implicit = FALSE;
2750   paint->flushed = NULL;
2751   paint->alpha = alpha;
2752   paint->surface = gdk_window_create_similar_surface (window,
2753                                                       with_alpha ? CAIRO_CONTENT_COLOR_ALPHA : gdk_window_get_content (window),
2754                                                       MAX (rect->width, 1),
2755                                                       MAX (rect->height, 1));
2756   cairo_surface_set_device_offset (paint->surface, -rect->x, -rect->y);
2757
2758   window->implicit_paint = g_slist_prepend (window->implicit_paint, paint);
2759
2760   return TRUE;
2761 }
2762
2763 static cairo_surface_t *
2764 gdk_window_ref_impl_surface (GdkWindow *window)
2765 {
2766   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)->ref_cairo_surface (gdk_window_get_impl_window (window));
2767 }
2768
2769 static cairo_t *
2770 gdk_cairo_create_for_impl (GdkWindow *window)
2771 {
2772   cairo_surface_t *surface;
2773   cairo_t *cr;
2774
2775   surface = gdk_window_ref_impl_surface (window);
2776   cr = cairo_create (surface);
2777
2778   cairo_surface_destroy (surface);
2779
2780   return cr;
2781 }
2782
2783 /* This is called whenever something is drawing directly to the
2784  * window, bypassing the double buffering. When this happens we
2785  * need to mark any the currently drawn data in the double buffer
2786  * as invalid to avoid later drawing it back over the directly
2787  * rendered pixels. We also need to mark this region as "flushed"
2788  * so that if we later try to paint on it double-buffered we need
2789  * to read back the on-window pixels rather than relying on what
2790  * is in the current double-buffer pixmap.
2791  *
2792  * Note that this doesn't correctly handle the case where the
2793  * non-double buffered drawing uses transparency and relies on
2794  * what the windows below it draws. A fix for that would require
2795  * drawing the existing double-buffered background to the window,
2796  * but that causes ugly flashes. Non-double buffered drawing is
2797  * typically only used in old code or when the drawed widget
2798  * already has a double-buffering layer, and in these cases the
2799  * pixels are opaque anyway. If you need transparency, don't
2800  * disable double buffering.
2801  */
2802 static void
2803 gdk_window_flush_implicit_paint (GdkWindow *window)
2804 {
2805   GdkWindow *impl_window;
2806   GdkWindowPaint *paint;
2807   cairo_region_t *region;
2808   GSList *l;
2809
2810   impl_window = gdk_window_get_impl_window (window);
2811   if (impl_window->implicit_paint == NULL)
2812     return;
2813
2814   /* There is no proper way to flush any non-toplevel implicit
2815      paint, because direct rendering is not compatible with
2816      opacity rendering, as it requires an opacity group.
2817
2818      We warn and flush just the outermost paint in this case.
2819   */
2820   l = g_slist_last (impl_window->implicit_paint);
2821   if (l != impl_window->implicit_paint)
2822     g_warning ("Non double buffered drawing not supported inside transparent windows");
2823
2824   paint = l->data;
2825
2826   region = cairo_region_copy (window->clip_region_with_children);
2827   cairo_region_translate (region, window->abs_x, window->abs_y);
2828
2829   /* Anything in the whole flushed window that was drawn is now
2830      considered unpainted, so that we don't push it back at the
2831      end of the implicit paint overwriting the directly rendered
2832      pixels. */
2833   cairo_region_subtract (paint->region, region);
2834
2835   /* Save flushed area so we can read it back if we draw over it later */
2836   if (paint->flushed == NULL)
2837     paint->flushed = region;
2838   else
2839     {
2840       cairo_region_union (paint->flushed, region);
2841       cairo_region_destroy (region);
2842     }
2843 }
2844
2845 /* Ends an implicit paint, paired with gdk_window_begin_implicit_paint returning TRUE */
2846 static void
2847 gdk_window_end_implicit_paint (GdkWindow *window)
2848 {
2849   GdkWindowPaint *paint;
2850
2851   g_assert (gdk_window_has_impl (window));
2852
2853   g_assert (window->implicit_paint != NULL);
2854
2855   paint = window->implicit_paint->data;
2856
2857   window->implicit_paint = g_slist_delete_link (window->implicit_paint,
2858                                                 window->implicit_paint);
2859
2860   if (!GDK_WINDOW_DESTROYED (window) && !cairo_region_is_empty (paint->region) && paint->alpha > 0)
2861     {
2862       GdkWindowPaint *parent_paint = NULL;
2863       cairo_t *cr;
2864
2865       /* Some regions are valid, push these to window now */
2866       if (window->implicit_paint)
2867         {
2868           parent_paint = window->implicit_paint->data;
2869
2870           /* If the toplevel implicit paint was flushed, restore it now
2871              before we blend over it. */
2872           if (parent_paint->flushed != NULL &&
2873               !cairo_region_is_empty (parent_paint->flushed))
2874             {
2875               cairo_surface_t *source_surface = gdk_window_ref_impl_surface (window);
2876               cairo_region_t *flushed = cairo_region_copy (parent_paint->flushed);
2877
2878               cr = cairo_create (parent_paint->surface);
2879               cairo_set_source_surface (cr, source_surface, 0, 0);
2880               cairo_surface_destroy (source_surface);
2881
2882               cairo_region_intersect (flushed, paint->region);
2883               gdk_cairo_region (cr, flushed);
2884               cairo_clip (cr);
2885
2886               cairo_region_subtract (parent_paint->flushed, flushed);
2887               cairo_region_destroy (flushed);
2888
2889               cairo_paint (cr);
2890               cairo_destroy (cr);
2891             }
2892
2893           cr = cairo_create (parent_paint->surface);
2894         }
2895       else
2896         cr = gdk_cairo_create_for_impl (window);
2897
2898       gdk_cairo_region (cr, paint->region);
2899       cairo_clip (cr);
2900       cairo_set_source_surface (cr, paint->surface, 0, 0);
2901       if (paint->alpha == 255)
2902         {
2903           cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
2904           cairo_paint (cr);
2905         }
2906       else
2907         {
2908           cairo_set_operator (cr, CAIRO_OPERATOR_OVER);
2909           cairo_paint_with_alpha (cr, paint->alpha / 255.0);
2910         }
2911
2912       cairo_destroy (cr);
2913
2914       if (parent_paint)
2915         cairo_region_union (parent_paint->region, paint->region);
2916     }
2917
2918   cairo_region_destroy (paint->region);
2919   if (paint->flushed)
2920     cairo_region_destroy (paint->flushed);
2921   cairo_surface_destroy (paint->surface);
2922   g_free (paint);
2923 }
2924
2925 /**
2926  * gdk_window_begin_paint_rect:
2927  * @window: a #GdkWindow
2928  * @rectangle: rectangle you intend to draw to
2929  *
2930  * A convenience wrapper around gdk_window_begin_paint_region() which
2931  * creates a rectangular region for you. See
2932  * gdk_window_begin_paint_region() for details.
2933  *
2934  **/
2935 void
2936 gdk_window_begin_paint_rect (GdkWindow          *window,
2937                              const GdkRectangle *rectangle)
2938 {
2939   cairo_region_t *region;
2940
2941   g_return_if_fail (GDK_IS_WINDOW (window));
2942
2943   region = cairo_region_create_rectangle (rectangle);
2944   gdk_window_begin_paint_region (window, region);
2945   cairo_region_destroy (region);
2946 }
2947
2948 /**
2949  * gdk_window_begin_paint_region:
2950  * @window: a #GdkWindow
2951  * @region: region you intend to draw to
2952  *
2953  * Indicates that you are beginning the process of redrawing @region.
2954  * A backing store (offscreen buffer) large enough to contain @region
2955  * will be created. The backing store will be initialized with the
2956  * background color or background surface for @window. Then, all
2957  * drawing operations performed on @window will be diverted to the
2958  * backing store.  When you call gdk_window_end_paint(), the backing
2959  * store will be copied to @window, making it visible onscreen. Only
2960  * the part of @window contained in @region will be modified; that is,
2961  * drawing operations are clipped to @region.
2962  *
2963  * The net result of all this is to remove flicker, because the user
2964  * sees the finished product appear all at once when you call
2965  * gdk_window_end_paint(). If you draw to @window directly without
2966  * calling gdk_window_begin_paint_region(), the user may see flicker
2967  * as individual drawing operations are performed in sequence.  The
2968  * clipping and background-initializing features of
2969  * gdk_window_begin_paint_region() are conveniences for the
2970  * programmer, so you can avoid doing that work yourself.
2971  *
2972  * When using GTK+, the widget system automatically places calls to
2973  * gdk_window_begin_paint_region() and gdk_window_end_paint() around
2974  * emissions of the expose_event signal. That is, if you're writing an
2975  * expose event handler, you can assume that the exposed area in
2976  * #GdkEventExpose has already been cleared to the window background,
2977  * is already set as the clip region, and already has a backing store.
2978  * Therefore in most cases, application code need not call
2979  * gdk_window_begin_paint_region(). (You can disable the automatic
2980  * calls around expose events on a widget-by-widget basis by calling
2981  * gtk_widget_set_double_buffered().)
2982  *
2983  * If you call this function multiple times before calling the
2984  * matching gdk_window_end_paint(), the backing stores are pushed onto
2985  * a stack. gdk_window_end_paint() copies the topmost backing store
2986  * onscreen, subtracts the topmost region from all other regions in
2987  * the stack, and pops the stack. All drawing operations affect only
2988  * the topmost backing store in the stack. One matching call to
2989  * gdk_window_end_paint() is required for each call to
2990  * gdk_window_begin_paint_region().
2991  *
2992  **/
2993 void
2994 gdk_window_begin_paint_region (GdkWindow       *window,
2995                                const cairo_region_t *region)
2996 {
2997 #ifdef USE_BACKING_STORE
2998   GdkRectangle clip_box;
2999   GdkWindowPaint *paint, *implicit_paint;
3000   GdkWindow *impl_window;
3001   GSList *list;
3002
3003   g_return_if_fail (GDK_IS_WINDOW (window));
3004
3005   if (GDK_WINDOW_DESTROYED (window))
3006     return;
3007
3008   if (GDK_IS_PAINTABLE (window->impl))
3009     {
3010       GdkPaintableIface *iface = GDK_PAINTABLE_GET_IFACE (window->impl);
3011
3012       if (iface->begin_paint_region)
3013         iface->begin_paint_region ((GdkPaintable*)window->impl, window, region);
3014
3015       return;
3016     }
3017
3018   impl_window = gdk_window_get_impl_window (window);
3019   implicit_paint = impl_window->implicit_paint != NULL ? impl_window->implicit_paint->data : NULL;
3020
3021   paint = g_new (GdkWindowPaint, 1);
3022   paint->region = cairo_region_copy (region);
3023
3024   cairo_region_intersect (paint->region, window->clip_region_with_children);
3025   cairo_region_get_extents (paint->region, &clip_box);
3026
3027   cairo_region_translate (paint->region, window->abs_x, window->abs_y);
3028
3029   /* Mark the region as valid on the implicit paint */
3030
3031   if (implicit_paint)
3032     cairo_region_union (implicit_paint->region, paint->region);
3033
3034   /* Convert back to normal coords */
3035   cairo_region_translate (paint->region, -window->abs_x, -window->abs_y);
3036
3037   if (implicit_paint)
3038     {
3039       paint->uses_implicit = TRUE;
3040       paint->surface = cairo_surface_create_for_rectangle (implicit_paint->surface,
3041                                                            window->abs_x + clip_box.x,
3042                                                            window->abs_y + clip_box.y,
3043                                                            MAX (clip_box.width, 1),
3044                                                            MAX (clip_box.height, 1));
3045     }
3046   else
3047     {
3048       paint->uses_implicit = FALSE;
3049       paint->surface = gdk_window_create_similar_surface (window,
3050                                                           gdk_window_get_content (window),
3051                                                           MAX (clip_box.width, 1),
3052                                                           MAX (clip_box.height, 1));
3053     }
3054
3055   /* Normally alpha backgrounded client side windows are composited on the implicit paint
3056      by being drawn in back to front order. However, if implicit paints are not used, for
3057      instance if it was flushed due to a non-double-buffered paint in the middle of the
3058      expose we need to copy in the existing data here. */
3059   if (gdk_window_has_alpha (window) &&
3060       (!implicit_paint ||
3061        (implicit_paint && implicit_paint->flushed != NULL && !cairo_region_is_empty (implicit_paint->flushed))))
3062     {
3063       cairo_t *cr = cairo_create (paint->surface);
3064       /* We can't use gdk_cairo_set_source_window here, as that might
3065          flush the implicit paint at an unfortunate time, since this
3066          would be detected as a draw during non-expose time */
3067       cairo_surface_t *source_surface  = gdk_window_ref_impl_surface (impl_window);
3068       cairo_set_source_surface (cr, source_surface,
3069                                 - (window->abs_x + clip_box.x),
3070                                 - (window->abs_y + clip_box.y));
3071       cairo_surface_destroy (source_surface);
3072
3073       /* Only read back the flushed area if any */
3074       if (implicit_paint)
3075         {
3076           cairo_region_t *flushed = cairo_region_copy (implicit_paint->flushed);
3077           /* Convert from impl coords */
3078           cairo_region_translate (flushed, -window->abs_x, -window->abs_y);
3079           cairo_region_intersect (flushed, paint->region);
3080           gdk_cairo_region (cr, flushed);
3081           cairo_clip (cr);
3082
3083           /* Convert to impl coords */
3084           cairo_region_translate (flushed, window->abs_x, window->abs_y);
3085           cairo_region_subtract (implicit_paint->flushed, flushed);
3086           cairo_region_destroy (flushed);
3087         }
3088       cairo_paint (cr);
3089       cairo_destroy (cr);
3090     }
3091
3092   cairo_surface_set_device_offset (paint->surface, -clip_box.x, -clip_box.y);
3093
3094   for (list = window->paint_stack; list != NULL; list = list->next)
3095     {
3096       GdkWindowPaint *tmp_paint = list->data;
3097
3098       cairo_region_subtract (tmp_paint->region, paint->region);
3099     }
3100
3101   window->paint_stack = g_slist_prepend (window->paint_stack, paint);
3102
3103   if (!cairo_region_is_empty (paint->region))
3104     {
3105       gdk_window_clear_backing_region (window,
3106                                        paint->region);
3107     }
3108
3109 #endif /* USE_BACKING_STORE */
3110 }
3111
3112 /**
3113  * gdk_window_end_paint:
3114  * @window: a #GdkWindow
3115  *
3116  * Indicates that the backing store created by the most recent call to
3117  * gdk_window_begin_paint_region() should be copied onscreen and
3118  * deleted, leaving the next-most-recent backing store or no backing
3119  * store at all as the active paint region. See
3120  * gdk_window_begin_paint_region() for full details. It is an error to
3121  * call this function without a matching
3122  * gdk_window_begin_paint_region() first.
3123  *
3124  **/
3125 void
3126 gdk_window_end_paint (GdkWindow *window)
3127 {
3128 #ifdef USE_BACKING_STORE
3129   GdkWindow *composited;
3130   GdkWindowPaint *paint;
3131   GdkRectangle clip_box;
3132   cairo_region_t *full_clip;
3133
3134   g_return_if_fail (GDK_IS_WINDOW (window));
3135
3136   if (GDK_WINDOW_DESTROYED (window))
3137     return;
3138
3139   if (GDK_IS_PAINTABLE (window->impl))
3140     {
3141       GdkPaintableIface *iface = GDK_PAINTABLE_GET_IFACE (window->impl);
3142
3143       if (iface->end_paint)
3144         iface->end_paint ((GdkPaintable*)window->impl);
3145       return;
3146     }
3147
3148   if (window->paint_stack == NULL)
3149     {
3150       g_warning (G_STRLOC": no preceding call to gdk_window_begin_paint_region(), see documentation");
3151       return;
3152     }
3153
3154   paint = window->paint_stack->data;
3155
3156   window->paint_stack = g_slist_delete_link (window->paint_stack,
3157                                              window->paint_stack);
3158
3159   cairo_region_get_extents (paint->region, &clip_box);
3160
3161   if (!paint->uses_implicit)
3162     {
3163       cairo_t *cr;
3164
3165       gdk_window_flush_outstanding_moves (window);
3166
3167       full_clip = cairo_region_copy (window->clip_region_with_children);
3168       cairo_region_intersect (full_clip, paint->region);
3169
3170       cr = gdk_cairo_create (window);
3171       cairo_set_operator (cr, CAIRO_OPERATOR_SOURCE);
3172       cairo_set_source_surface (cr, paint->surface, 0, 0);
3173       gdk_cairo_region (cr, full_clip);
3174       cairo_fill (cr);
3175
3176       cairo_destroy (cr);
3177       cairo_region_destroy (full_clip);
3178     }
3179
3180   cairo_surface_destroy (paint->surface);
3181   cairo_region_destroy (paint->region);
3182   g_free (paint);
3183
3184   /* find a composited window in our hierarchy to signal its
3185    * parent to redraw, calculating the clip box as we go...
3186    *
3187    * stop if parent becomes NULL since then we'd have nowhere
3188    * to draw (ie: 'composited' will always be non-NULL here).
3189    */
3190   for (composited = window;
3191        composited->parent;
3192        composited = composited->parent)
3193     {
3194       clip_box.x += composited->x;
3195       clip_box.y += composited->y;
3196       clip_box.width = MIN (clip_box.width, composited->parent->width - clip_box.x);
3197       clip_box.height = MIN (clip_box.height, composited->parent->height - clip_box.y);
3198
3199       if (composited->composited)
3200         {
3201           gdk_window_invalidate_rect (GDK_WINDOW (composited->parent),
3202                                       &clip_box, FALSE);
3203           break;
3204         }
3205     }
3206 #endif /* USE_BACKING_STORE */
3207 }
3208
3209 static void
3210 gdk_window_free_paint_stack (GdkWindow *window)
3211 {
3212   if (window->paint_stack)
3213     {
3214       GSList *tmp_list = window->paint_stack;
3215
3216       while (tmp_list)
3217         {
3218           GdkWindowPaint *paint = tmp_list->data;
3219
3220           if (tmp_list == window->paint_stack)
3221             cairo_surface_destroy (paint->surface);
3222
3223           cairo_region_destroy (paint->region);
3224           g_free (paint);
3225
3226           tmp_list = tmp_list->next;
3227         }
3228
3229       g_slist_free (window->paint_stack);
3230       window->paint_stack = NULL;
3231     }
3232 }
3233
3234 static void
3235 do_move_region_bits_on_impl (GdkWindow *impl_window,
3236                              cairo_region_t *dest_region, /* In impl window coords */
3237                              int dx, int dy)
3238 {
3239   GdkWindowImplClass *impl_class;
3240
3241   impl_class = GDK_WINDOW_IMPL_GET_CLASS (impl_window->impl);
3242
3243   impl_class->translate (impl_window, dest_region, dx, dy);
3244 }
3245
3246 static GdkWindowRegionMove *
3247 gdk_window_region_move_new (cairo_region_t *region,
3248                             int dx, int dy)
3249 {
3250   GdkWindowRegionMove *move;
3251
3252   move = g_slice_new (GdkWindowRegionMove);
3253   move->dest_region = cairo_region_copy (region);
3254   move->dx = dx;
3255   move->dy = dy;
3256
3257   return move;
3258 }
3259
3260 static void
3261 gdk_window_region_move_free (GdkWindowRegionMove *move)
3262 {
3263   cairo_region_destroy (move->dest_region);
3264   g_slice_free (GdkWindowRegionMove, move);
3265 }
3266
3267 static void
3268 append_move_region (GdkWindow *impl_window,
3269                     cairo_region_t *new_dest_region,
3270                     int dx, int dy)
3271 {
3272   GdkWindowRegionMove *move, *old_move;
3273   cairo_region_t *new_total_region, *old_total_region;
3274   cairo_region_t *source_overlaps_destination;
3275   cairo_region_t *non_overwritten;
3276   gboolean added_move;
3277   GList *l, *prev;
3278
3279   if (cairo_region_is_empty (new_dest_region))
3280     return;
3281
3282   /* In principle this could just append the move to the list of outstanding
3283      moves that will be replayed before drawing anything when we're handling
3284      exposes. However, we'd like to do a bit better since its commonly the case
3285      that we get multiple copies where A is copied to B and then B is copied
3286      to C, and we'd like to express this as a simple copy A to C operation. */
3287
3288   /* We approach this by taking the new move and pushing it ahead of moves
3289      starting at the end of the list and stopping when its not safe to do so.
3290      It's not safe to push past a move if either the source of the new move
3291      is in the destination of the old move, or if the destination of the new
3292      move is in the source of the new move, or if the destination of the new
3293      move overlaps the destination of the old move. We simplify this by
3294      just comparing the total regions (src + dest) */
3295   new_total_region = cairo_region_copy (new_dest_region);
3296   cairo_region_translate (new_total_region, -dx, -dy);
3297   cairo_region_union (new_total_region, new_dest_region);
3298
3299   added_move = FALSE;
3300   for (l = g_list_last (impl_window->outstanding_moves); l != NULL; l = prev)
3301     {
3302       prev = l->prev;
3303       old_move = l->data;
3304
3305       old_total_region = cairo_region_copy (old_move->dest_region);
3306       cairo_region_translate (old_total_region, -old_move->dx, -old_move->dy);
3307       cairo_region_union (old_total_region, old_move->dest_region);
3308
3309       cairo_region_intersect (old_total_region, new_total_region);
3310       /* If these regions intersect then its not safe to push the
3311          new region before the old one */
3312       if (!cairo_region_is_empty (old_total_region))
3313         {
3314           /* The area where the new moves source overlaps the old ones
3315              destination */
3316           source_overlaps_destination = cairo_region_copy (new_dest_region);
3317           cairo_region_translate (source_overlaps_destination, -dx, -dy);
3318           cairo_region_intersect (source_overlaps_destination, old_move->dest_region);
3319           cairo_region_translate (source_overlaps_destination, dx, dy);
3320
3321           /* We can do all sort of optimizations here, but to do things safely it becomes
3322              quite complicated. However, a very common case is that you copy something first,
3323              then copy all that or a subset of it to a new location (i.e. if you scroll twice
3324              in the same direction). We'd like to detect this case and optimize it to one
3325              copy. */
3326           if (cairo_region_equal (source_overlaps_destination, new_dest_region))
3327             {
3328               /* This means we might be able to replace the old move and the new one
3329                  with the new one read from the old ones source, and a second copy of
3330                  the non-overwritten parts of the old move. However, such a split
3331                  is only valid if the source in the old move isn't overwritten
3332                  by the destination of the new one */
3333
3334               /* the new destination of old move if split is ok: */
3335               non_overwritten = cairo_region_copy (old_move->dest_region);
3336               cairo_region_subtract (non_overwritten, new_dest_region);
3337               /* move to source region */
3338               cairo_region_translate (non_overwritten, -old_move->dx, -old_move->dy);
3339
3340               cairo_region_intersect (non_overwritten, new_dest_region);
3341               if (cairo_region_is_empty (non_overwritten))
3342                 {
3343                   added_move = TRUE;
3344                   move = gdk_window_region_move_new (new_dest_region,
3345                                                      dx + old_move->dx,
3346                                                      dy + old_move->dy);
3347
3348                   impl_window->outstanding_moves =
3349                     g_list_insert_before (impl_window->outstanding_moves,
3350                                           l, move);
3351                   cairo_region_subtract (old_move->dest_region, new_dest_region);
3352                 }
3353               cairo_region_destroy (non_overwritten);
3354             }
3355
3356           cairo_region_destroy (source_overlaps_destination);
3357           cairo_region_destroy (old_total_region);
3358           break;
3359         }
3360       cairo_region_destroy (old_total_region);
3361     }
3362
3363   cairo_region_destroy (new_total_region);
3364
3365   if (!added_move)
3366     {
3367       move = gdk_window_region_move_new (new_dest_region, dx, dy);
3368
3369       if (l == NULL)
3370         impl_window->outstanding_moves =
3371           g_list_prepend (impl_window->outstanding_moves,
3372                           move);
3373       else
3374         impl_window->outstanding_moves =
3375           g_list_insert_before (impl_window->outstanding_moves,
3376                                 l->next, move);
3377     }
3378 }
3379
3380 /* Moves bits and update area by dx/dy in impl window.
3381    Takes ownership of region to avoid copy (because we may change it) */
3382 static void
3383 move_region_on_impl (GdkWindow *impl_window,
3384                      cairo_region_t *region, /* In impl window coords */
3385                      int dx, int dy)
3386 {
3387   GSList *l;
3388
3389   if ((dx == 0 && dy == 0) ||
3390       cairo_region_is_empty (region))
3391     {
3392       cairo_region_destroy (region);
3393       return;
3394     }
3395
3396   g_assert (impl_window == gdk_window_get_impl_window (impl_window));
3397
3398   /* Move any old invalid regions in the copy source area by dx/dy */
3399   if (impl_window->update_area)
3400     {
3401       cairo_region_t *update_area;
3402
3403       update_area = cairo_region_copy (region);
3404
3405       /* Convert from target to source */
3406       cairo_region_translate (update_area, -dx, -dy);
3407       cairo_region_intersect (update_area, impl_window->update_area);
3408       /* We only copy the area, so keep the old update area invalid.
3409          It would be safe to remove it too, as code that uses
3410          move_region_on_impl generally also invalidate the source
3411          area. However, it would just use waste cycles. */
3412
3413       /* Convert back */
3414       cairo_region_translate (update_area, dx, dy);
3415       cairo_region_union (impl_window->update_area, update_area);
3416
3417       /* This area of the destination is now invalid,
3418          so no need to copy to it.  */
3419       cairo_region_subtract (region, update_area);
3420
3421       cairo_region_destroy (update_area);
3422     }
3423
3424   /* If we're currently exposing this window, don't copy to this
3425      destination, as it will be overdrawn when the expose is done,
3426      instead invalidate it and repaint later. */
3427   for (l = impl_window->implicit_paint; l != NULL; l = l->next)
3428     {
3429       GdkWindowPaint *implicit_paint = l->data;
3430       cairo_region_t *exposing;
3431
3432       exposing = cairo_region_copy (implicit_paint->region);
3433       cairo_region_intersect (exposing, region);
3434       cairo_region_subtract (region, exposing);
3435
3436       impl_window_add_update_area (impl_window, exposing);
3437       cairo_region_destroy (exposing);
3438     }
3439
3440   append_move_region (impl_window, region, dx, dy);
3441
3442   cairo_region_destroy (region);
3443 }
3444
3445 /* Flushes all outstanding changes to the window, call this
3446  * before drawing directly to the window (i.e. outside a begin/end_paint pair).
3447  */
3448 static void
3449 gdk_window_flush_outstanding_moves (GdkWindow *window)
3450 {
3451   GdkWindow *impl_window;
3452   GList *l, *outstanding;
3453   GdkWindowRegionMove *move;
3454
3455   impl_window = gdk_window_get_impl_window (window);
3456   outstanding = impl_window->outstanding_moves;
3457   impl_window->outstanding_moves = NULL;
3458
3459   for (l = outstanding; l != NULL; l = l->next)
3460     {
3461       move = l->data;
3462
3463       do_move_region_bits_on_impl (impl_window,
3464                                    move->dest_region, move->dx, move->dy);
3465
3466       gdk_window_region_move_free (move);
3467     }
3468
3469   g_list_free (outstanding);
3470 }
3471
3472 /**
3473  * gdk_window_flush:
3474  * @window: a #GdkWindow
3475  *
3476  * Flush all outstanding cached operations on a window, leaving the
3477  * window in a state which reflects all that has been drawn before.
3478  *
3479  * Gdk uses multiple kinds of caching to get better performance and
3480  * nicer drawing. For instance, during exposes all paints to a window
3481  * using double buffered rendering are keep on a surface until the last
3482  * window has been exposed. It also delays window moves/scrolls until
3483  * as long as possible until next update to avoid tearing when moving
3484  * windows.
3485  *
3486  * Normally this should be completely invisible to applications, as
3487  * we automatically flush the windows when required, but this might
3488  * be needed if you for instance mix direct native drawing with
3489  * gdk drawing. For Gtk widgets that don't use double buffering this
3490  * will be called automatically before sending the expose event.
3491  *
3492  * Since: 2.18
3493  **/
3494 void
3495 gdk_window_flush (GdkWindow *window)
3496 {
3497   gdk_window_flush_outstanding_moves (window);
3498   gdk_window_flush_implicit_paint (window);
3499 }
3500
3501 static void
3502 gdk_window_flush_recursive_helper (GdkWindow *window,
3503                                    GdkWindowImpl *impl)
3504 {
3505   GdkWindow *child;
3506   GList *l;
3507
3508   for (l = window->children; l != NULL; l = l->next)
3509     {
3510       child = l->data;
3511
3512       if (child->impl == impl)
3513         /* Same impl, ignore */
3514         gdk_window_flush_recursive_helper (child, impl);
3515       else
3516         gdk_window_flush_recursive (child);
3517     }
3518 }
3519
3520 static void
3521 gdk_window_flush_recursive (GdkWindow *window)
3522 {
3523   gdk_window_flush (window);
3524   gdk_window_flush_recursive_helper (window, window->impl);
3525 }
3526
3527 /**
3528  * gdk_window_get_clip_region:
3529  * @window: a #GdkWindow
3530  * 
3531  * Computes the region of a window that potentially can be written
3532  * to by drawing primitives. This region may not take into account
3533  * other factors such as if the window is obscured by other windows,
3534  * but no area outside of this region will be affected by drawing
3535  * primitives.
3536  * 
3537  * Returns: a #cairo_region_t. This must be freed with cairo_region_destroy()
3538  *          when you are done.
3539  **/
3540 cairo_region_t*
3541 gdk_window_get_clip_region (GdkWindow *window)
3542 {
3543   cairo_region_t *result;
3544
3545   g_return_val_if_fail (GDK_WINDOW (window), NULL);
3546
3547   result = cairo_region_copy (window->clip_region);
3548
3549   if (window->paint_stack)
3550     {
3551       cairo_region_t *paint_region = cairo_region_create ();
3552       GSList *tmp_list = window->paint_stack;
3553
3554       while (tmp_list)
3555         {
3556           GdkWindowPaint *paint = tmp_list->data;
3557
3558           cairo_region_union (paint_region, paint->region);
3559
3560           tmp_list = tmp_list->next;
3561         }
3562
3563       cairo_region_intersect (result, paint_region);
3564       cairo_region_destroy (paint_region);
3565     }
3566
3567   return result;
3568 }
3569
3570 /**
3571  * gdk_window_get_visible_region:
3572  * @window: a #GdkWindow
3573  * 
3574  * Computes the region of the @window that is potentially visible.
3575  * This does not necessarily take into account if the window is
3576  * obscured by other windows, but no area outside of this region
3577  * is visible.
3578  * 
3579  * Returns: a #cairo_region_t. This must be freed with cairo_region_destroy()
3580  *          when you are done.
3581  **/
3582 cairo_region_t *
3583 gdk_window_get_visible_region (GdkWindow *window)
3584 {
3585   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
3586
3587   return cairo_region_copy (window->clip_region);
3588 }
3589
3590 static cairo_t *
3591 setup_backing_rect (GdkWindow *window, GdkWindowPaint *paint)
3592 {
3593   GdkWindow *bg_window;
3594   cairo_pattern_t *pattern = NULL;
3595   int x_offset = 0, y_offset = 0;
3596   cairo_t *cr;
3597
3598   cr = cairo_create (paint->surface);
3599
3600   for (bg_window = window; bg_window; bg_window = bg_window->parent)
3601     {
3602       pattern = gdk_window_get_background_pattern (bg_window);
3603       if (pattern)
3604         break;
3605
3606       x_offset += bg_window->x;
3607       y_offset += bg_window->y;
3608     }
3609
3610   if (pattern)
3611     {
3612       cairo_translate (cr, -x_offset, -y_offset);
3613       cairo_set_source (cr, pattern);
3614       cairo_translate (cr, x_offset, y_offset);
3615     }
3616   else
3617     cairo_set_source_rgb (cr, 0, 0, 0);
3618
3619   return cr;
3620 }
3621
3622 static void
3623 gdk_window_clear_backing_region (GdkWindow *window,
3624                                  cairo_region_t *region)
3625 {
3626   GdkWindowPaint *paint = window->paint_stack->data;
3627   cairo_region_t *clip;
3628   cairo_t *cr;
3629
3630   if (GDK_WINDOW_DESTROYED (window))
3631     return;
3632
3633   cr = setup_backing_rect (window, paint);
3634
3635   clip = cairo_region_copy (paint->region);
3636   cairo_region_intersect (clip, region);
3637
3638   gdk_cairo_region (cr, clip);
3639   cairo_fill (cr);
3640
3641   cairo_destroy (cr);
3642
3643   cairo_region_destroy (clip);
3644 }
3645
3646 static void
3647 gdk_window_drop_cairo_surface (GdkWindow *window)
3648 {
3649   if (window->cairo_surface)
3650     {
3651       cairo_surface_finish (window->cairo_surface);
3652       cairo_surface_set_user_data (window->cairo_surface, &gdk_window_cairo_key,
3653                                    NULL, NULL);
3654       window->cairo_surface = NULL;
3655     }
3656 }
3657
3658 static void
3659 gdk_window_cairo_surface_destroy (void *data)
3660 {
3661   GdkWindow *window = data;
3662
3663   window->cairo_surface = NULL;
3664 }
3665
3666 static cairo_surface_t *
3667 gdk_window_create_cairo_surface (GdkWindow *window,
3668                                  int width,
3669                                  int height)
3670 {
3671   cairo_surface_t *surface, *subsurface;
3672   
3673   surface = gdk_window_ref_impl_surface (window);
3674   if (gdk_window_has_impl (window))
3675     return surface;
3676
3677   subsurface = cairo_surface_create_for_rectangle (surface,
3678                                                    window->abs_x,
3679                                                    window->abs_y,
3680                                                    width,
3681                                                    height);
3682   cairo_surface_destroy (surface);
3683   return subsurface;
3684 }
3685
3686
3687 cairo_surface_t *
3688 _gdk_window_ref_cairo_surface (GdkWindow *window)
3689 {
3690   cairo_surface_t *surface;
3691
3692   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
3693
3694   if (window->paint_stack)
3695     {
3696       GdkWindowPaint *paint = window->paint_stack->data;
3697
3698       surface = paint->surface;
3699       cairo_surface_reference (surface);
3700     }
3701   else
3702     {
3703
3704       /* This will be drawing directly to the window, so flush implicit paint */
3705       gdk_window_flush (window);
3706
3707       if (!window->cairo_surface)
3708         {
3709           window->cairo_surface = gdk_window_create_cairo_surface (window,
3710                                                                    window->width,
3711                                                                    window->height);
3712
3713           if (window->cairo_surface)
3714             {
3715               cairo_surface_set_user_data (window->cairo_surface, &gdk_window_cairo_key,
3716                                            window, gdk_window_cairo_surface_destroy);
3717             }
3718         }
3719       else
3720         cairo_surface_reference (window->cairo_surface);
3721
3722       surface = window->cairo_surface;
3723     }
3724
3725   return surface;
3726 }
3727
3728 /**
3729  * gdk_cairo_create:
3730  * @window: a #GdkWindow
3731  * 
3732  * Creates a Cairo context for drawing to @window.
3733  *
3734  * <note><warning>
3735  * Note that calling cairo_reset_clip() on the resulting #cairo_t will
3736  * produce undefined results, so avoid it at all costs.
3737  * </warning></note>
3738  *
3739  * Return value: A newly created Cairo context. Free with
3740  *  cairo_destroy() when you are done drawing.
3741  * 
3742  * Since: 2.8
3743  **/
3744 cairo_t *
3745 gdk_cairo_create (GdkWindow *window)
3746 {
3747   cairo_surface_t *surface;
3748   cairo_t *cr;
3749     
3750   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
3751
3752   surface = _gdk_window_ref_cairo_surface (window);
3753   cr = cairo_create (surface);
3754
3755   if (!window->paint_stack)
3756     {
3757       gdk_cairo_region (cr, window->clip_region_with_children);
3758       cairo_clip (cr);
3759     }
3760   else
3761     {
3762       GdkWindowPaint *paint = window->paint_stack->data;
3763
3764       /* Only needs to clip to region if piggybacking
3765          on an implicit paint */
3766       if (paint->uses_implicit)
3767         {
3768           gdk_cairo_region (cr, paint->region);
3769           cairo_clip (cr);
3770         }
3771     }
3772     
3773   cairo_surface_destroy (surface);
3774
3775   return cr;
3776 }
3777
3778 /* Code for dirty-region queueing
3779  */
3780 static GSList *update_windows = NULL;
3781 static guint update_idle = 0;
3782 static gboolean debug_updates = FALSE;
3783
3784 static inline gboolean
3785 gdk_window_is_ancestor (GdkWindow *window,
3786                         GdkWindow *ancestor)
3787 {
3788   while (window)
3789     {
3790       GdkWindow *parent = window->parent;
3791
3792       if (parent == ancestor)
3793         return TRUE;
3794
3795       window = parent;
3796     }
3797
3798   return FALSE;
3799 }
3800
3801 static void
3802 gdk_window_add_update_window (GdkWindow *window)
3803 {
3804   GSList *tmp;
3805   GSList *prev = NULL;
3806   gboolean has_ancestor_in_list = FALSE;
3807
3808   for (tmp = update_windows; tmp; tmp = tmp->next)
3809     {
3810       GdkWindow *parent = window->parent;
3811
3812       /*  check if tmp is an ancestor of "window"; if it is, set a
3813        *  flag indicating that all following windows are either
3814        *  children of "window" or from a differen hierarchy
3815        */
3816       if (!has_ancestor_in_list && gdk_window_is_ancestor (window, tmp->data))
3817         has_ancestor_in_list = TRUE;
3818
3819       /* insert in reverse stacking order when adding around siblings,
3820        * so processing updates properly paints over lower stacked windows
3821        */
3822       if (parent == GDK_WINDOW (tmp->data)->parent)
3823         {
3824           gint index = g_list_index (parent->children, window);
3825           for (; tmp && parent == GDK_WINDOW (tmp->data)->parent; tmp = tmp->next)
3826             {
3827               gint sibling_index = g_list_index (parent->children, tmp->data);
3828               if (index > sibling_index)
3829                 break;
3830               prev = tmp;
3831             }
3832           /* here, tmp got advanced past all lower stacked siblings */
3833           tmp = g_slist_prepend (tmp, window);
3834           if (prev)
3835             prev->next = tmp;
3836           else
3837             update_windows = tmp;
3838           return;
3839         }
3840
3841       /*  if "window" has an ancestor in the list and tmp is one of
3842        *  "window's" children, insert "window" before tmp
3843        */
3844       if (has_ancestor_in_list && gdk_window_is_ancestor (tmp->data, window))
3845         {
3846           tmp = g_slist_prepend (tmp, window);
3847
3848           if (prev)
3849             prev->next = tmp;
3850           else
3851             update_windows = tmp;
3852           return;
3853         }
3854
3855       /*  if we're at the end of the list and had an ancestor it it,
3856        *  append to the list
3857        */
3858       if (! tmp->next && has_ancestor_in_list)
3859         {
3860           tmp = g_slist_append (tmp, window);
3861           return;
3862         }
3863
3864       prev = tmp;
3865     }
3866
3867   /*  if all above checks failed ("window" is from a different
3868    *  hierarchy than what is already in the list) or the list is
3869    *  empty, prepend
3870    */
3871   update_windows = g_slist_prepend (update_windows, window);
3872 }
3873
3874 static void
3875 gdk_window_remove_update_window (GdkWindow *window)
3876 {
3877   update_windows = g_slist_remove (update_windows, window);
3878 }
3879
3880 static gboolean
3881 gdk_window_update_idle (gpointer data)
3882 {
3883   gdk_window_process_all_updates ();
3884
3885   return FALSE;
3886 }
3887
3888 static gboolean
3889 gdk_window_is_toplevel_frozen (GdkWindow *window)
3890 {
3891   GdkWindow *toplevel;
3892
3893   toplevel = gdk_window_get_toplevel (window);
3894
3895   return toplevel->update_and_descendants_freeze_count > 0;
3896 }
3897
3898 static void
3899 gdk_window_schedule_update (GdkWindow *window)
3900 {
3901   if (window &&
3902       (window->update_freeze_count ||
3903        gdk_window_is_toplevel_frozen (window)))
3904     return;
3905
3906   if (!update_idle)
3907     update_idle =
3908       gdk_threads_add_idle_full (GDK_PRIORITY_REDRAW,
3909                                  gdk_window_update_idle,
3910                                  NULL, NULL);
3911 }
3912
3913 void
3914 _gdk_window_process_updates_recurse (GdkWindow *window,
3915                                      cairo_region_t *expose_region)
3916 {
3917   GdkWindow *child;
3918   cairo_region_t *clipped_expose_region;
3919   GdkRectangle clip_box;
3920   GList *l, *children;
3921   gboolean end_implicit;
3922
3923   if (cairo_region_is_empty (expose_region))
3924     return;
3925
3926   if (gdk_window_is_offscreen (window->impl_window) &&
3927       gdk_window_has_impl (window))
3928     _gdk_window_add_damage ((GdkWindow *) window->impl_window, expose_region);
3929
3930   end_implicit = FALSE;
3931   if (window->alpha != 255 && !gdk_window_has_impl (window))
3932     {
3933       if (window->alpha == 0)
3934         return;
3935
3936       cairo_region_get_extents (expose_region, &clip_box);
3937       clip_box.x += window->abs_x;
3938       clip_box.y += window->abs_y;
3939       end_implicit = gdk_window_begin_implicit_paint (window->impl_window, &clip_box, TRUE, window->alpha);
3940     }
3941
3942   /* Paint the window before the children, clipped to the window region
3943      with visible child windows removed */
3944   clipped_expose_region = cairo_region_copy (expose_region);
3945   cairo_region_intersect (clipped_expose_region, window->clip_region_with_children);
3946
3947   if (!cairo_region_is_empty (clipped_expose_region) &&
3948       !window->destroyed)
3949     {
3950       if (window->event_mask & GDK_EXPOSURE_MASK)
3951         {
3952           GdkEvent event;
3953
3954           event.expose.type = GDK_EXPOSE;
3955           event.expose.window = g_object_ref (window);
3956           event.expose.send_event = FALSE;
3957           event.expose.count = 0;
3958           event.expose.region = clipped_expose_region;
3959           cairo_region_get_extents (clipped_expose_region, &event.expose.area);
3960
3961           _gdk_event_emit (&event);
3962
3963           g_object_unref (window);
3964         }
3965       else if (window->window_type != GDK_WINDOW_FOREIGN)
3966         {
3967           /* No exposure mask set, so nothing will be drawn, the
3968            * app relies on the background being what it specified
3969            * for the window. So, we need to clear this manually.
3970            *
3971            * For foreign windows if expose is not set that generally
3972            * means some other client paints them, so don't clear
3973            * there.
3974            *
3975            * We use begin/end_paint around the clear so that we can
3976            * piggyback on the implicit paint */
3977
3978           gdk_window_begin_paint_region (window, clipped_expose_region);
3979           /* The actual clear happens in begin_paint_region */
3980           gdk_window_end_paint (window);
3981         }
3982     }
3983   cairo_region_destroy (clipped_expose_region);
3984
3985   /* Make this reentrancy safe for expose handlers freeing windows */
3986   children = g_list_copy (window->children);
3987   g_list_foreach (children, (GFunc)g_object_ref, NULL);
3988
3989   /* Iterate over children, starting at bottommost */
3990   for (l = g_list_last (children); l != NULL; l = l->prev)
3991     {
3992       child = l->data;
3993
3994       if (child->destroyed || !GDK_WINDOW_IS_MAPPED (child) || child->input_only || child->composited)
3995         continue;
3996
3997       /* Ignore offscreen children, as they don't draw in their parent and
3998        * don't take part in the clipping */
3999       if (gdk_window_is_offscreen (child))
4000         continue;
4001
4002       /* Client side child, expose */
4003       if (child->impl == window->impl)
4004         {
4005           cairo_region_translate (expose_region, -child->x, -child->y);
4006           _gdk_window_process_updates_recurse ((GdkWindow *)child, expose_region);
4007           cairo_region_translate (expose_region, child->x, child->y);
4008         }
4009     }
4010
4011   g_list_free_full (children, g_object_unref);
4012
4013   if (end_implicit)
4014     gdk_window_end_implicit_paint (window->impl_window);
4015 }
4016
4017 /* Process and remove any invalid area on the native window by creating
4018  * expose events for the window and all non-native descendants.
4019  * Also processes any outstanding moves on the window before doing
4020  * any drawing. Note that its possible to have outstanding moves without
4021  * any invalid area as we use the update idle mechanism to coalesce
4022  * multiple moves as well as multiple invalidations.
4023  */
4024 static void
4025 gdk_window_process_updates_internal (GdkWindow *window)
4026 {
4027   GdkWindowImplClass *impl_class;
4028   gboolean save_region = FALSE;
4029   GdkRectangle clip_box;
4030
4031   /* Ensure the window lives while updating it */
4032   g_object_ref (window);
4033
4034   /* If an update got queued during update processing, we can get a
4035    * window in the update queue that has an empty update_area.
4036    * just ignore it.
4037    */
4038   if (window->update_area)
4039     {
4040       cairo_region_t *update_area = window->update_area;
4041       window->update_area = NULL;
4042
4043       if (gdk_window_is_viewable (window))
4044         {
4045           cairo_region_t *expose_region;
4046           gboolean end_implicit;
4047
4048           /* Clip to part visible in toplevel */
4049           cairo_region_intersect (update_area, window->clip_region);
4050
4051           if (debug_updates)
4052             {
4053               /* Make sure we see the red invalid area before redrawing. */
4054               gdk_display_sync (gdk_window_get_display (window));
4055               g_usleep (70000);
4056             }
4057
4058           /* At this point we will be completely redrawing all of update_area.
4059            * If we have any outstanding moves that end up moving stuff inside
4060            * this area we don't actually need to move that as that part would
4061            * be overdrawn by the expose anyway. So, in order to copy less data
4062            * we remove these areas from the outstanding moves.
4063            */
4064           if (window->outstanding_moves)
4065             {
4066               GdkWindowRegionMove *move;
4067               cairo_region_t *remove;
4068               GList *l, *prev;
4069
4070               remove = cairo_region_copy (update_area);
4071               /* We iterate backwards, starting from the state that would be
4072                  if we had applied all the moves. */
4073               for (l = g_list_last (window->outstanding_moves); l != NULL; l = prev)
4074                 {
4075                   prev = l->prev;
4076                   move = l->data;
4077
4078                   /* Don't need this area */
4079                   cairo_region_subtract (move->dest_region, remove);
4080
4081                   /* However if any of the destination we do need has a source
4082                      in the updated region we do need that as a destination for
4083                      the earlier moves */
4084                   cairo_region_translate (move->dest_region, -move->dx, -move->dy);
4085                   cairo_region_subtract (remove, move->dest_region);
4086
4087                   if (cairo_region_is_empty (move->dest_region))
4088                     {
4089                       gdk_window_region_move_free (move);
4090                       window->outstanding_moves =
4091                         g_list_delete_link (window->outstanding_moves, l);
4092                     }
4093                   else /* move back */
4094                     cairo_region_translate (move->dest_region, move->dx, move->dy);
4095                 }
4096               cairo_region_destroy (remove);
4097             }
4098
4099           /* By now we a set of window moves that should be applied, and then
4100            * an update region that should be repainted. A trivial implementation
4101            * would just do that in order, however in order to get nicer drawing
4102            * we do some tricks:
4103            *
4104            * First of all, each subwindow expose may be double buffered by
4105            * itself (depending on widget setting) via
4106            * gdk_window_begin/end_paint(). But we also do an "implicit" paint,
4107            * creating a single surface the size of the invalid area on the
4108            * native window which all the individual normal paints will draw
4109            * into. This way in the normal case there will be only one surface
4110            * allocated and only once surface draw done for all the windows
4111            * in this native window.
4112            * There are a couple of reasons this may fail, for instance, some
4113            * backends (like quartz) do its own double buffering, so we disable
4114            * gdk double buffering there. Secondly, some subwindow could be
4115            * non-double buffered and draw directly to the window outside a
4116            * begin/end_paint pair. That will be lead to a gdk_window_flush
4117            * which immediately executes all outstanding moves and paints+removes
4118            * the implicit paint (further paints will allocate their own surfaces).
4119            *
4120            * Secondly, in the case of implicit double buffering we expose all
4121            * the child windows into the implicit surface before we execute
4122            * the outstanding moves. This way we minimize the time between
4123            * doing the moves and rendering the new update area, thus minimizing
4124            * flashing. Of course, if any subwindow is non-double buffered we
4125            * well flush earlier than that.
4126            *
4127            * Thirdly, after having done the outstanding moves we queue an
4128            * "antiexpose" on the area that will be drawn by the expose, which
4129            * means that any invalid region on the native window side before
4130            * the first expose drawing operation will be discarded, as it
4131            * has by then been overdrawn with valid data. This means we can
4132            * avoid doing the unnecessary repaint any outstanding expose events.
4133            */
4134
4135           cairo_region_get_extents (update_area, &clip_box);
4136           end_implicit = gdk_window_begin_implicit_paint (window, &clip_box, FALSE, 255);
4137           expose_region = cairo_region_copy (update_area);
4138           impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
4139           if (!end_implicit)
4140             {
4141               /* Rendering is not double buffered by gdk, do outstanding
4142                * moves and queue antiexposure immediately. No need to do
4143                * any tricks */
4144               gdk_window_flush_outstanding_moves (window);
4145               save_region = impl_class->queue_antiexpose (window, update_area);
4146             }
4147           /* Render the invalid areas to the implicit paint, by sending exposes.
4148            * May flush if non-double buffered widget draw. */
4149           impl_class->process_updates_recurse (window, expose_region);
4150
4151           if (end_implicit)
4152             {
4153               /* Do moves right before exposes are rendered to the window */
4154               gdk_window_flush_outstanding_moves (window);
4155
4156               /* By this time we know that any outstanding expose for this
4157                * area is invalid and we can avoid it, so queue an antiexpose.
4158                * we have already started drawing to the window, so it would
4159                * be to late to anti-expose now. Since this is merely an
4160                * optimization we just avoid doing it at all in that case.
4161                */
4162               if (window->implicit_paint != NULL && !((GdkWindowPaint *)window->implicit_paint->data)->flushed)
4163                 save_region = impl_class->queue_antiexpose (window, update_area);
4164
4165               gdk_window_end_implicit_paint (window);
4166             }
4167           cairo_region_destroy (expose_region);
4168         }
4169       if (!save_region)
4170         cairo_region_destroy (update_area);
4171     }
4172
4173   if (window->outstanding_moves)
4174     {
4175       /* Flush any outstanding moves, may happen if we moved a window but got
4176          no actual invalid area */
4177       gdk_window_flush_outstanding_moves (window);
4178     }
4179
4180   g_object_unref (window);
4181 }
4182
4183 static void
4184 flush_all_displays (void)
4185 {
4186   GSList *displays, *l;
4187
4188   displays = gdk_display_manager_list_displays (gdk_display_manager_get ());
4189   for (l = displays; l; l = l->next)
4190     gdk_display_flush (l->data);
4191
4192   g_slist_free (displays);
4193 }
4194
4195 static void
4196 before_process_all_updates (void)
4197 {
4198   GSList *displays, *l;
4199   GdkDisplayClass *display_class;
4200
4201   displays = gdk_display_manager_list_displays (gdk_display_manager_get ());
4202   display_class = GDK_DISPLAY_GET_CLASS (displays->data);
4203   for (l = displays; l; l = l->next)
4204     display_class->before_process_all_updates (l->data);
4205
4206   g_slist_free (displays);
4207 }
4208
4209 static void
4210 after_process_all_updates (void)
4211 {
4212   GSList *displays, *l;
4213   GdkDisplayClass *display_class;
4214
4215   displays = gdk_display_manager_list_displays (gdk_display_manager_get ());
4216   display_class = GDK_DISPLAY_GET_CLASS (displays->data);
4217   for (l = displays; l; l = l->next)
4218     display_class->after_process_all_updates (l->data);
4219
4220   g_slist_free (displays);
4221 }
4222
4223 /* Currently it is not possible to override
4224  * gdk_window_process_all_updates in the same manner as
4225  * gdk_window_process_updates and gdk_window_invalidate_maybe_recurse
4226  * by implementing the GdkPaintable interface.  If in the future a
4227  * backend would need this, the right solution would be to add a
4228  * method to GdkDisplay that can be optionally
4229  * NULL. gdk_window_process_all_updates can then walk the list of open
4230  * displays and call the mehod.
4231  */
4232
4233 /**
4234  * gdk_window_process_all_updates:
4235  *
4236  * Calls gdk_window_process_updates() for all windows (see #GdkWindow)
4237  * in the application.
4238  *
4239  **/
4240 void
4241 gdk_window_process_all_updates (void)
4242 {
4243   GSList *old_update_windows = update_windows;
4244   GSList *tmp_list = update_windows;
4245   static gboolean in_process_all_updates = FALSE;
4246   static gboolean got_recursive_update = FALSE;
4247
4248   if (in_process_all_updates)
4249     {
4250       /* We can't do this now since that would recurse, so
4251          delay it until after the recursion is done. */
4252       got_recursive_update = TRUE;
4253       update_idle = 0;
4254       return;
4255     }
4256
4257   in_process_all_updates = TRUE;
4258   got_recursive_update = FALSE;
4259
4260   if (update_idle)
4261     g_source_remove (update_idle);
4262
4263   update_windows = NULL;
4264   update_idle = 0;
4265
4266   before_process_all_updates ();
4267
4268   g_slist_foreach (old_update_windows, (GFunc)g_object_ref, NULL);
4269
4270   while (tmp_list)
4271     {
4272       GdkWindow *window = tmp_list->data;
4273
4274       if (!GDK_WINDOW_DESTROYED (window))
4275         {
4276           if (window->update_freeze_count ||
4277               gdk_window_is_toplevel_frozen (window))
4278             gdk_window_add_update_window (window);
4279           else
4280             gdk_window_process_updates_internal (window);
4281         }
4282
4283       g_object_unref (window);
4284       tmp_list = tmp_list->next;
4285     }
4286
4287   g_slist_free (old_update_windows);
4288
4289   flush_all_displays ();
4290
4291   after_process_all_updates ();
4292
4293   in_process_all_updates = FALSE;
4294
4295   /* If we ignored a recursive call, schedule a
4296      redraw now so that it eventually happens,
4297      otherwise we could miss an update if nothing
4298      else schedules an update. */
4299   if (got_recursive_update && !update_idle)
4300     update_idle =
4301       gdk_threads_add_idle_full (GDK_PRIORITY_REDRAW,
4302                                  gdk_window_update_idle,
4303                                  NULL, NULL);
4304 }
4305
4306 /**
4307  * gdk_window_process_updates:
4308  * @window: a #GdkWindow
4309  * @update_children: whether to also process updates for child windows
4310  *
4311  * Sends one or more expose events to @window. The areas in each
4312  * expose event will cover the entire update area for the window (see
4313  * gdk_window_invalidate_region() for details). Normally GDK calls
4314  * gdk_window_process_all_updates() on your behalf, so there's no
4315  * need to call this function unless you want to force expose events
4316  * to be delivered immediately and synchronously (vs. the usual
4317  * case, where GDK delivers them in an idle handler). Occasionally
4318  * this is useful to produce nicer scrolling behavior, for example.
4319  *
4320  **/
4321 void
4322 gdk_window_process_updates (GdkWindow *window,
4323                             gboolean   update_children)
4324 {
4325   GdkWindow *impl_window;
4326
4327   g_return_if_fail (GDK_IS_WINDOW (window));
4328
4329   if (GDK_WINDOW_DESTROYED (window))
4330     return;
4331
4332   /* Make sure the window lives during the expose callouts */
4333   g_object_ref (window);
4334
4335   impl_window = gdk_window_get_impl_window (window);
4336   if ((impl_window->update_area ||
4337        impl_window->outstanding_moves) &&
4338       !impl_window->update_freeze_count &&
4339       !gdk_window_is_toplevel_frozen (window) &&
4340
4341       /* Don't recurse into process_updates_internal, we'll
4342        * do the update later when idle instead. */
4343       impl_window->implicit_paint == NULL)
4344     {
4345       gdk_window_process_updates_internal ((GdkWindow *)impl_window);
4346       gdk_window_remove_update_window ((GdkWindow *)impl_window);
4347     }
4348
4349   if (update_children)
4350     {
4351       /* process updates in reverse stacking order so composition or
4352        * painting over achieves the desired effect for offscreen windows
4353        */
4354       GList *node, *children;
4355
4356       children = g_list_copy (window->children);
4357       g_list_foreach (children, (GFunc)g_object_ref, NULL);
4358
4359       for (node = g_list_last (children); node; node = node->prev)
4360         {
4361           gdk_window_process_updates (node->data, TRUE);
4362           g_object_unref (node->data);
4363         }
4364
4365       g_list_free (children);
4366     }
4367
4368   g_object_unref (window);
4369 }
4370
4371 static void
4372 gdk_window_invalidate_rect_full (GdkWindow          *window,
4373                                   const GdkRectangle *rect,
4374                                   gboolean            invalidate_children,
4375                                   ClearBg             clear_bg)
4376 {
4377   GdkRectangle window_rect;
4378   cairo_region_t *region;
4379
4380   g_return_if_fail (GDK_IS_WINDOW (window));
4381
4382   if (GDK_WINDOW_DESTROYED (window))
4383     return;
4384
4385   if (window->input_only || !window->viewable)
4386     return;
4387
4388   if (!rect)
4389     {
4390       window_rect.x = 0;
4391       window_rect.y = 0;
4392       window_rect.width = window->width;
4393       window_rect.height = window->height;
4394       rect = &window_rect;
4395     }
4396
4397   region = cairo_region_create_rectangle (rect);
4398   gdk_window_invalidate_region_full (window, region, invalidate_children, clear_bg);
4399   cairo_region_destroy (region);
4400 }
4401
4402 /**
4403  * gdk_window_invalidate_rect:
4404  * @window: a #GdkWindow
4405  * @rect: (allow-none): rectangle to invalidate or %NULL to invalidate the whole
4406  *      window
4407  * @invalidate_children: whether to also invalidate child windows
4408  *
4409  * A convenience wrapper around gdk_window_invalidate_region() which
4410  * invalidates a rectangular region. See
4411  * gdk_window_invalidate_region() for details.
4412  **/
4413 void
4414 gdk_window_invalidate_rect (GdkWindow          *window,
4415                             const GdkRectangle *rect,
4416                             gboolean            invalidate_children)
4417 {
4418   gdk_window_invalidate_rect_full (window, rect, invalidate_children, CLEAR_BG_NONE);
4419 }
4420
4421 static void
4422 draw_ugly_color (GdkWindow       *window,
4423                  const cairo_region_t *region)
4424 {
4425   cairo_t *cr;
4426
4427   cr = gdk_cairo_create (window);
4428   /* Draw ugly color all over the newly-invalid region */
4429   cairo_set_source_rgb (cr, 50000/65535., 10000/65535., 10000/65535.);
4430   gdk_cairo_region (cr, region);
4431   cairo_fill (cr);
4432
4433   cairo_destroy (cr);
4434 }
4435
4436 static void
4437 impl_window_add_update_area (GdkWindow *impl_window,
4438                              cairo_region_t *region)
4439 {
4440   if (impl_window->update_area)
4441     cairo_region_union (impl_window->update_area, region);
4442   else
4443     {
4444       gdk_window_add_update_window (impl_window);
4445       impl_window->update_area = cairo_region_copy (region);
4446       gdk_window_schedule_update (impl_window);
4447     }
4448 }
4449
4450 /* clear_bg controls if the region will be cleared to
4451  * the background pattern if the exposure mask is not
4452  * set for the window, whereas this might not otherwise be
4453  * done (unless necessary to emulate background settings).
4454  * Set this to CLEAR_BG_WINCLEARED or CLEAR_BG_ALL if you
4455  * need to clear the background, such as when exposing the area beneath a
4456  * hidden or moved window, but not when an app requests repaint or when the
4457  * windowing system exposes a newly visible area (because then the windowing
4458  * system has already cleared the area).
4459  */
4460 static void
4461 gdk_window_invalidate_maybe_recurse_full (GdkWindow            *window,
4462                                           const cairo_region_t *region,
4463                                           ClearBg               clear_bg,
4464                                           GdkWindowChildFunc    child_func,
4465                                           gpointer              user_data)
4466 {
4467   GdkWindow *impl_window;
4468   cairo_region_t *visible_region;
4469   GList *tmp_list;
4470
4471   g_return_if_fail (GDK_IS_WINDOW (window));
4472
4473   if (GDK_WINDOW_DESTROYED (window))
4474     return;
4475
4476   if (window->input_only ||
4477       !window->viewable ||
4478       cairo_region_is_empty (region) ||
4479       window->window_type == GDK_WINDOW_ROOT)
4480     return;
4481
4482   visible_region = gdk_window_get_visible_region (window);
4483   cairo_region_intersect (visible_region, region);
4484
4485   tmp_list = window->children;
4486   while (tmp_list)
4487     {
4488       GdkWindow *child = tmp_list->data;
4489
4490       if (!child->input_only)
4491         {
4492           cairo_region_t *child_region;
4493           GdkRectangle child_rect;
4494
4495           child_rect.x = child->x;
4496           child_rect.y = child->y;
4497           child_rect.width = child->width;
4498           child_rect.height = child->height;
4499           child_region = cairo_region_create_rectangle (&child_rect);
4500
4501           /* remove child area from the invalid area of the parent */
4502           if (GDK_WINDOW_IS_MAPPED (child) && !child->shaped &&
4503               !child->composited &&
4504               !gdk_window_is_offscreen (child))
4505             cairo_region_subtract (visible_region, child_region);
4506
4507           if (child_func && (*child_func) ((GdkWindow *)child, user_data))
4508             {
4509               cairo_region_t *tmp = cairo_region_copy (region);
4510
4511               cairo_region_translate (tmp, - child_rect.x, - child_rect.y);
4512               cairo_region_translate (child_region, - child_rect.x, - child_rect.y);
4513               cairo_region_intersect (child_region, tmp);
4514
4515               gdk_window_invalidate_maybe_recurse_full ((GdkWindow *)child,
4516                                                         child_region, clear_bg, child_func, user_data);
4517
4518               cairo_region_destroy (tmp);
4519             }
4520
4521           cairo_region_destroy (child_region);
4522         }
4523
4524       tmp_list = tmp_list->next;
4525     }
4526
4527   impl_window = gdk_window_get_impl_window (window);
4528
4529   if (!cairo_region_is_empty (visible_region)  ||
4530       /* Even if we're not exposing anything, make sure we process
4531          idles for windows with outstanding moves */
4532       (impl_window->outstanding_moves != NULL &&
4533        impl_window->update_area == NULL))
4534     {
4535       if (debug_updates)
4536         draw_ugly_color (window, region);
4537
4538       /* Convert to impl coords */
4539       cairo_region_translate (visible_region, window->abs_x, window->abs_y);
4540
4541       /* Only invalidate area if app requested expose events or if
4542          we need to clear the area (by request or to emulate background
4543          clearing for non-native windows or native windows with no support
4544          for window backgrounds */
4545       if (window->event_mask & GDK_EXPOSURE_MASK ||
4546           clear_bg == CLEAR_BG_ALL ||
4547           clear_bg == CLEAR_BG_WINCLEARED)
4548         impl_window_add_update_area (impl_window, visible_region);
4549     }
4550
4551   cairo_region_destroy (visible_region);
4552 }
4553
4554 /**
4555  * gdk_window_invalidate_maybe_recurse:
4556  * @window: a #GdkWindow
4557  * @region: a #cairo_region_t
4558  * @child_func: (scope call) (allow-none): function to use to decide if to
4559  *     recurse to a child, %NULL means never recurse.
4560  * @user_data: data passed to @child_func
4561  *
4562  * Adds @region to the update area for @window. The update area is the
4563  * region that needs to be redrawn, or "dirty region." The call
4564  * gdk_window_process_updates() sends one or more expose events to the
4565  * window, which together cover the entire update area. An
4566  * application would normally redraw the contents of @window in
4567  * response to those expose events.
4568  *
4569  * GDK will call gdk_window_process_all_updates() on your behalf
4570  * whenever your program returns to the main loop and becomes idle, so
4571  * normally there's no need to do that manually, you just need to
4572  * invalidate regions that you know should be redrawn.
4573  *
4574  * The @child_func parameter controls whether the region of
4575  * each child window that intersects @region will also be invalidated.
4576  * Only children for which @child_func returns TRUE will have the area
4577  * invalidated.
4578  **/
4579 void
4580 gdk_window_invalidate_maybe_recurse (GdkWindow            *window,
4581                                      const cairo_region_t *region,
4582                                      GdkWindowChildFunc    child_func,
4583                                      gpointer              user_data)
4584 {
4585   gdk_window_invalidate_maybe_recurse_full (window, region, CLEAR_BG_NONE,
4586                                             child_func, user_data);
4587 }
4588
4589 static gboolean
4590 true_predicate (GdkWindow *window,
4591                 gpointer   user_data)
4592 {
4593   return TRUE;
4594 }
4595
4596 static void
4597 gdk_window_invalidate_region_full (GdkWindow       *window,
4598                                     const cairo_region_t *region,
4599                                     gboolean         invalidate_children,
4600                                     ClearBg          clear_bg)
4601 {
4602   gdk_window_invalidate_maybe_recurse_full (window, region, clear_bg,
4603                                             invalidate_children ?
4604                                             true_predicate : (gboolean (*) (GdkWindow *, gpointer))NULL,
4605                                        NULL);
4606 }
4607
4608 /**
4609  * gdk_window_invalidate_region:
4610  * @window: a #GdkWindow
4611  * @region: a #cairo_region_t
4612  * @invalidate_children: %TRUE to also invalidate child windows
4613  *
4614  * Adds @region to the update area for @window. The update area is the
4615  * region that needs to be redrawn, or "dirty region." The call
4616  * gdk_window_process_updates() sends one or more expose events to the
4617  * window, which together cover the entire update area. An
4618  * application would normally redraw the contents of @window in
4619  * response to those expose events.
4620  *
4621  * GDK will call gdk_window_process_all_updates() on your behalf
4622  * whenever your program returns to the main loop and becomes idle, so
4623  * normally there's no need to do that manually, you just need to
4624  * invalidate regions that you know should be redrawn.
4625  *
4626  * The @invalidate_children parameter controls whether the region of
4627  * each child window that intersects @region will also be invalidated.
4628  * If %FALSE, then the update area for child windows will remain
4629  * unaffected. See gdk_window_invalidate_maybe_recurse if you need
4630  * fine grained control over which children are invalidated.
4631  **/
4632 void
4633 gdk_window_invalidate_region (GdkWindow       *window,
4634                               const cairo_region_t *region,
4635                               gboolean         invalidate_children)
4636 {
4637   gdk_window_invalidate_maybe_recurse (window, region,
4638                                        invalidate_children ?
4639                                          true_predicate : (gboolean (*) (GdkWindow *, gpointer))NULL,
4640                                        NULL);
4641 }
4642
4643 /**
4644  * _gdk_window_invalidate_for_expose:
4645  * @window: a #GdkWindow
4646  * @region: a #cairo_region_t
4647  *
4648  * Adds @region to the update area for @window. The update area is the
4649  * region that needs to be redrawn, or "dirty region." The call
4650  * gdk_window_process_updates() sends one or more expose events to the
4651  * window, which together cover the entire update area. An
4652  * application would normally redraw the contents of @window in
4653  * response to those expose events.
4654  *
4655  * GDK will call gdk_window_process_all_updates() on your behalf
4656  * whenever your program returns to the main loop and becomes idle, so
4657  * normally there's no need to do that manually, you just need to
4658  * invalidate regions that you know should be redrawn.
4659  *
4660  * This version of invalidation is used when you recieve expose events
4661  * from the native window system. It exposes the native window, plus
4662  * any non-native child windows (but not native child windows, as those would
4663  * have gotten their own expose events).
4664  **/
4665 void
4666 _gdk_window_invalidate_for_expose (GdkWindow       *window,
4667                                    cairo_region_t       *region)
4668 {
4669   GdkWindowRegionMove *move;
4670   cairo_region_t *move_region;
4671   GList *l;
4672
4673   /* Any invalidations comming from the windowing system will
4674      be in areas that may be moved by outstanding moves,
4675      so we need to modify the expose region correspondingly,
4676      otherwise we would expose in the wrong place, as the
4677      outstanding moves will be copied before we draw the
4678      exposes. */
4679   for (l = window->outstanding_moves; l != NULL; l = l->next)
4680     {
4681       move = l->data;
4682
4683       /* covert to move source region */
4684       move_region = cairo_region_copy (move->dest_region);
4685       cairo_region_translate (move_region, -move->dx, -move->dy);
4686
4687       /* Move area of region that intersects with move source
4688          by dx, dy of the move*/
4689       cairo_region_intersect (move_region, region);
4690       cairo_region_subtract (region, move_region);
4691       cairo_region_translate (move_region, move->dx, move->dy);
4692       cairo_region_union (region, move_region);
4693
4694       cairo_region_destroy (move_region);
4695     }
4696
4697   gdk_window_invalidate_maybe_recurse_full (window, region, CLEAR_BG_WINCLEARED,
4698                                             (gboolean (*) (GdkWindow *, gpointer))gdk_window_has_no_impl,
4699                                             NULL);
4700 }
4701
4702
4703 /**
4704  * gdk_window_get_update_area:
4705  * @window: a #GdkWindow
4706  *
4707  * Transfers ownership of the update area from @window to the caller
4708  * of the function. That is, after calling this function, @window will
4709  * no longer have an invalid/dirty region; the update area is removed
4710  * from @window and handed to you. If a window has no update area,
4711  * gdk_window_get_update_area() returns %NULL. You are responsible for
4712  * calling cairo_region_destroy() on the returned region if it's non-%NULL.
4713  *
4714  * Return value: the update area for @window
4715  **/
4716 cairo_region_t *
4717 gdk_window_get_update_area (GdkWindow *window)
4718 {
4719   GdkWindow *impl_window;
4720   cairo_region_t *tmp_region, *to_remove;
4721
4722   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
4723
4724   impl_window = gdk_window_get_impl_window (window);
4725
4726   if (impl_window->update_area)
4727     {
4728       tmp_region = cairo_region_copy (window->clip_region_with_children);
4729       /* Convert to impl coords */
4730       cairo_region_translate (tmp_region, window->abs_x, window->abs_y);
4731       cairo_region_intersect (tmp_region, impl_window->update_area);
4732
4733       if (cairo_region_is_empty (tmp_region))
4734         {
4735           cairo_region_destroy (tmp_region);
4736           return NULL;
4737         }
4738       else
4739         {
4740           /* Convert from impl coords */
4741           cairo_region_translate (tmp_region, -window->abs_x, -window->abs_y);
4742
4743           /* Don't remove any update area that is overlapped by non-opaque windows
4744              (children or siblings) with alpha, as these really need to be repainted
4745              independently of this window. */
4746           to_remove = cairo_region_copy (tmp_region);
4747           cairo_region_subtract (to_remove, window->parent->layered_region);
4748           remove_layered_child_area (window, to_remove);
4749
4750           /* Remove from update_area */
4751           cairo_region_translate (to_remove, window->abs_x, window->abs_y);
4752           cairo_region_subtract (impl_window->update_area, to_remove);
4753
4754           cairo_region_destroy (to_remove);
4755
4756           if (cairo_region_is_empty (impl_window->update_area) &&
4757               impl_window->outstanding_moves == NULL)
4758             {
4759               cairo_region_destroy (impl_window->update_area);
4760               impl_window->update_area = NULL;
4761
4762               gdk_window_remove_update_window ((GdkWindow *)impl_window);
4763             }
4764
4765           return tmp_region;
4766         }
4767     }
4768   else
4769     return NULL;
4770 }
4771
4772 /**
4773  * _gdk_window_clear_update_area:
4774  * @window: a #GdkWindow.
4775  *
4776  * Internal function to clear the update area for a window. This
4777  * is called when the window is hidden or destroyed.
4778  **/
4779 void
4780 _gdk_window_clear_update_area (GdkWindow *window)
4781 {
4782   g_return_if_fail (GDK_IS_WINDOW (window));
4783
4784   if (window->update_area)
4785     {
4786       gdk_window_remove_update_window (window);
4787
4788       cairo_region_destroy (window->update_area);
4789       window->update_area = NULL;
4790     }
4791 }
4792
4793 /**
4794  * gdk_window_freeze_updates:
4795  * @window: a #GdkWindow
4796  *
4797  * Temporarily freezes a window such that it won't receive expose
4798  * events.  The window will begin receiving expose events again when
4799  * gdk_window_thaw_updates() is called. If gdk_window_freeze_updates()
4800  * has been called more than once, gdk_window_thaw_updates() must be called
4801  * an equal number of times to begin processing exposes.
4802  **/
4803 void
4804 gdk_window_freeze_updates (GdkWindow *window)
4805 {
4806   GdkWindow *impl_window;
4807
4808   g_return_if_fail (GDK_IS_WINDOW (window));
4809
4810   impl_window = gdk_window_get_impl_window (window);
4811   impl_window->update_freeze_count++;
4812 }
4813
4814 /**
4815  * gdk_window_thaw_updates:
4816  * @window: a #GdkWindow
4817  *
4818  * Thaws a window frozen with gdk_window_freeze_updates().
4819  **/
4820 void
4821 gdk_window_thaw_updates (GdkWindow *window)
4822 {
4823   GdkWindow *impl_window;
4824
4825   g_return_if_fail (GDK_IS_WINDOW (window));
4826
4827   impl_window = gdk_window_get_impl_window (window);
4828
4829   g_return_if_fail (impl_window->update_freeze_count > 0);
4830
4831   if (--impl_window->update_freeze_count == 0)
4832     gdk_window_schedule_update (GDK_WINDOW (impl_window));
4833 }
4834
4835 /**
4836  * gdk_window_freeze_toplevel_updates_libgtk_only:
4837  * @window: a #GdkWindow
4838  *
4839  * Temporarily freezes a window and all its descendants such that it won't
4840  * receive expose events.  The window will begin receiving expose events
4841  * again when gdk_window_thaw_toplevel_updates_libgtk_only() is called. If
4842  * gdk_window_freeze_toplevel_updates_libgtk_only()
4843  * has been called more than once,
4844  * gdk_window_thaw_toplevel_updates_libgtk_only() must be called
4845  * an equal number of times to begin processing exposes.
4846  *
4847  * This function is not part of the GDK public API and is only
4848  * for use by GTK+.
4849  **/
4850 void
4851 gdk_window_freeze_toplevel_updates_libgtk_only (GdkWindow *window)
4852 {
4853   g_return_if_fail (GDK_IS_WINDOW (window));
4854   g_return_if_fail (window->window_type != GDK_WINDOW_CHILD);
4855
4856   window->update_and_descendants_freeze_count++;
4857 }
4858
4859 /**
4860  * gdk_window_thaw_toplevel_updates_libgtk_only:
4861  * @window: a #GdkWindow
4862  *
4863  * Thaws a window frozen with
4864  * gdk_window_freeze_toplevel_updates_libgtk_only().
4865  *
4866  * This function is not part of the GDK public API and is only
4867  * for use by GTK+.
4868  **/
4869 void
4870 gdk_window_thaw_toplevel_updates_libgtk_only (GdkWindow *window)
4871 {
4872   g_return_if_fail (GDK_IS_WINDOW (window));
4873   g_return_if_fail (window->window_type != GDK_WINDOW_CHILD);
4874   g_return_if_fail (window->update_and_descendants_freeze_count > 0);
4875
4876   window->update_and_descendants_freeze_count--;
4877
4878   gdk_window_schedule_update (window);
4879 }
4880
4881 /**
4882  * gdk_window_set_debug_updates:
4883  * @setting: %TRUE to turn on update debugging
4884  *
4885  * With update debugging enabled, calls to
4886  * gdk_window_invalidate_region() clear the invalidated region of the
4887  * screen to a noticeable color, and GDK pauses for a short time
4888  * before sending exposes to windows during
4889  * gdk_window_process_updates().  The net effect is that you can see
4890  * the invalid region for each window and watch redraws as they
4891  * occur. This allows you to diagnose inefficiencies in your application.
4892  *
4893  * In essence, because the GDK rendering model prevents all flicker,
4894  * if you are redrawing the same region 400 times you may never
4895  * notice, aside from noticing a speed problem. Enabling update
4896  * debugging causes GTK to flicker slowly and noticeably, so you can
4897  * see exactly what's being redrawn when, in what order.
4898  *
4899  * The --gtk-debug=updates command line option passed to GTK+ programs
4900  * enables this debug option at application startup time. That's
4901  * usually more useful than calling gdk_window_set_debug_updates()
4902  * yourself, though you might want to use this function to enable
4903  * updates sometime after application startup time.
4904  *
4905  **/
4906 void
4907 gdk_window_set_debug_updates (gboolean setting)
4908 {
4909   debug_updates = setting;
4910 }
4911
4912 /**
4913  * gdk_window_constrain_size:
4914  * @geometry: a #GdkGeometry structure
4915  * @flags: a mask indicating what portions of @geometry are set
4916  * @width: desired width of window
4917  * @height: desired height of the window
4918  * @new_width: (out): location to store resulting width
4919  * @new_height: (out): location to store resulting height
4920  *
4921  * Constrains a desired width and height according to a
4922  * set of geometry hints (such as minimum and maximum size).
4923  */
4924 void
4925 gdk_window_constrain_size (GdkGeometry *geometry,
4926                            guint        flags,
4927                            gint         width,
4928                            gint         height,
4929                            gint        *new_width,
4930                            gint        *new_height)
4931 {
4932   /* This routine is partially borrowed from fvwm.
4933    *
4934    * Copyright 1993, Robert Nation
4935    *     You may use this code for any purpose, as long as the original
4936    *     copyright remains in the source code and all documentation
4937    *
4938    * which in turn borrows parts of the algorithm from uwm
4939    */
4940   gint min_width = 0;
4941   gint min_height = 0;
4942   gint base_width = 0;
4943   gint base_height = 0;
4944   gint xinc = 1;
4945   gint yinc = 1;
4946   gint max_width = G_MAXINT;
4947   gint max_height = G_MAXINT;
4948
4949 #define FLOOR(value, base)      ( ((gint) ((value) / (base))) * (base) )
4950
4951   if ((flags & GDK_HINT_BASE_SIZE) && (flags & GDK_HINT_MIN_SIZE))
4952     {
4953       base_width = geometry->base_width;
4954       base_height = geometry->base_height;
4955       min_width = geometry->min_width;
4956       min_height = geometry->min_height;
4957     }
4958   else if (flags & GDK_HINT_BASE_SIZE)
4959     {
4960       base_width = geometry->base_width;
4961       base_height = geometry->base_height;
4962       min_width = geometry->base_width;
4963       min_height = geometry->base_height;
4964     }
4965   else if (flags & GDK_HINT_MIN_SIZE)
4966     {
4967       base_width = geometry->min_width;
4968       base_height = geometry->min_height;
4969       min_width = geometry->min_width;
4970       min_height = geometry->min_height;
4971     }
4972
4973   if (flags & GDK_HINT_MAX_SIZE)
4974     {
4975       max_width = geometry->max_width ;
4976       max_height = geometry->max_height;
4977     }
4978
4979   if (flags & GDK_HINT_RESIZE_INC)
4980     {
4981       xinc = MAX (xinc, geometry->width_inc);
4982       yinc = MAX (yinc, geometry->height_inc);
4983     }
4984
4985   /* clamp width and height to min and max values
4986    */
4987   width = CLAMP (width, min_width, max_width);
4988   height = CLAMP (height, min_height, max_height);
4989
4990   /* shrink to base + N * inc
4991    */
4992   width = base_width + FLOOR (width - base_width, xinc);
4993   height = base_height + FLOOR (height - base_height, yinc);
4994
4995   /* constrain aspect ratio, according to:
4996    *
4997    *                width
4998    * min_aspect <= -------- <= max_aspect
4999    *                height
5000    */
5001
5002   if (flags & GDK_HINT_ASPECT &&
5003       geometry->min_aspect > 0 &&
5004       geometry->max_aspect > 0)
5005     {
5006       gint delta;
5007
5008       if (geometry->min_aspect * height > width)
5009         {
5010           delta = FLOOR (height - width / geometry->min_aspect, yinc);
5011           if (height - delta >= min_height)
5012             height -= delta;
5013           else
5014             {
5015               delta = FLOOR (height * geometry->min_aspect - width, xinc);
5016               if (width + delta <= max_width)
5017                 width += delta;
5018             }
5019         }
5020
5021       if (geometry->max_aspect * height < width)
5022         {
5023           delta = FLOOR (width - height * geometry->max_aspect, xinc);
5024           if (width - delta >= min_width)
5025             width -= delta;
5026           else
5027             {
5028               delta = FLOOR (width / geometry->max_aspect - height, yinc);
5029               if (height + delta <= max_height)
5030                 height += delta;
5031             }
5032         }
5033     }
5034
5035 #undef FLOOR
5036
5037   *new_width = width;
5038   *new_height = height;
5039 }
5040
5041 /**
5042  * gdk_window_get_pointer:
5043  * @window: a #GdkWindow
5044  * @x: (out) (allow-none): return location for X coordinate of pointer or %NULL to not
5045  *      return the X coordinate
5046  * @y: (out) (allow-none):  return location for Y coordinate of pointer or %NULL to not
5047  *      return the Y coordinate
5048  * @mask: (out) (allow-none): return location for modifier mask or %NULL to not return the
5049  *      modifier mask
5050  *
5051  * Obtains the current pointer position and modifier state.
5052  * The position is given in coordinates relative to the upper left
5053  * corner of @window.
5054  *
5055  * Return value: (transfer none): the window containing the pointer (as with
5056  * gdk_window_at_pointer()), or %NULL if the window containing the
5057  * pointer isn't known to GDK
5058  *
5059  * Deprecated: 3.0: Use gdk_window_get_device_position() instead.
5060  **/
5061 GdkWindow*
5062 gdk_window_get_pointer (GdkWindow         *window,
5063                         gint              *x,
5064                         gint              *y,
5065                         GdkModifierType   *mask)
5066 {
5067   GdkDisplay *display;
5068
5069   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
5070
5071   display = gdk_window_get_display (window);
5072
5073   return gdk_window_get_device_position (window, display->core_pointer, x, y, mask);
5074 }
5075
5076 /**
5077  * gdk_window_get_device_position:
5078  * @window: a #GdkWindow.
5079  * @device: pointer #GdkDevice to query to.
5080  * @x: (out) (allow-none): return location for the X coordinate of @device, or %NULL.
5081  * @y: (out) (allow-none): return location for the Y coordinate of @device, or %NULL.
5082  * @mask: (out) (allow-none): return location for the modifier mask, or %NULL.
5083  *
5084  * Obtains the current device position and modifier state.
5085  * The position is given in coordinates relative to the upper left
5086  * corner of @window.
5087  *
5088  * Return value: (transfer none): The window underneath @device (as with
5089  * gdk_device_get_window_at_position()), or %NULL if the window is not known to GDK.
5090  *
5091  * Since: 3.0
5092  **/
5093 GdkWindow *
5094 gdk_window_get_device_position (GdkWindow       *window,
5095                                 GdkDevice       *device,
5096                                 gint            *x,
5097                                 gint            *y,
5098                                 GdkModifierType *mask)
5099 {
5100   gint tmp_x, tmp_y;
5101   GdkModifierType tmp_mask;
5102   gboolean normal_child;
5103
5104   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
5105   g_return_val_if_fail (GDK_IS_DEVICE (device), NULL);
5106   g_return_val_if_fail (gdk_device_get_source (device) != GDK_SOURCE_KEYBOARD, NULL);
5107
5108   normal_child = GDK_WINDOW_IMPL_GET_CLASS (window->impl)->get_device_state (window,
5109                                                                              device,
5110                                                                              &tmp_x, &tmp_y,
5111                                                                              &tmp_mask);
5112   /* We got the coords on the impl, convert to the window */
5113   tmp_x -= window->abs_x;
5114   tmp_y -= window->abs_y;
5115
5116   if (x)
5117     *x = tmp_x;
5118   if (y)
5119     *y = tmp_y;
5120   if (mask)
5121     *mask = tmp_mask;
5122
5123   _gdk_display_enable_motion_hints (gdk_window_get_display (window), device);
5124
5125   if (normal_child)
5126     return _gdk_window_find_child_at (window, tmp_x, tmp_y);
5127   return NULL;
5128 }
5129
5130 /**
5131  * gdk_get_default_root_window:
5132  *
5133  * Obtains the root window (parent all other windows are inside)
5134  * for the default display and screen.
5135  *
5136  * Return value: (transfer none): the default root window
5137  **/
5138 GdkWindow *
5139 gdk_get_default_root_window (void)
5140 {
5141   return gdk_screen_get_root_window (gdk_screen_get_default ());
5142 }
5143
5144 static void
5145 get_all_native_children (GdkWindow *window,
5146                          GList **native)
5147 {
5148   GdkWindow *child;
5149   GList *l;
5150
5151   for (l = window->children; l != NULL; l = l->next)
5152     {
5153       child = l->data;
5154
5155       if (gdk_window_has_impl (child))
5156         *native = g_list_prepend (*native, child);
5157       else
5158         get_all_native_children (child, native);
5159     }
5160 }
5161
5162
5163 static inline void
5164 gdk_window_raise_internal (GdkWindow *window)
5165 {
5166   GdkWindow *parent = window->parent;
5167   GdkWindow *above;
5168   GList *native_children;
5169   GList *l, listhead;
5170   GdkWindowImplClass *impl_class;
5171
5172   if (parent)
5173     {
5174       parent->children = g_list_remove (parent->children, window);
5175       parent->children = g_list_prepend (parent->children, window);
5176     }
5177
5178   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
5179   /* Just do native raise for toplevels */
5180   if (gdk_window_is_toplevel (window) ||
5181       /* The restack_under codepath should work correctly even if the parent
5182          is native, but it relies on the order of ->children to be correct,
5183          and some apps like SWT reorder the x windows without gdks knowledge,
5184          so we use raise directly in order to make these behave as before
5185          when using native windows */
5186       (gdk_window_has_impl (window) && gdk_window_has_impl (parent)))
5187     {
5188       impl_class->raise (window);
5189     }
5190   else if (gdk_window_has_impl (window))
5191     {
5192       above = find_native_sibling_above (parent, window);
5193       if (above)
5194         {
5195           listhead.data = window;
5196           listhead.next = NULL;
5197           listhead.prev = NULL;
5198           impl_class->restack_under ((GdkWindow *)above,
5199                                      &listhead);
5200         }
5201       else
5202         impl_class->raise (window);
5203     }
5204   else
5205     {
5206       native_children = NULL;
5207       get_all_native_children (window, &native_children);
5208       if (native_children != NULL)
5209         {
5210           above = find_native_sibling_above (parent, window);
5211
5212           if (above)
5213             impl_class->restack_under (above, native_children);
5214           else
5215             {
5216               /* Right order, since native_children is bottom-topmost first */
5217               for (l = native_children; l != NULL; l = l->next)
5218                 impl_class->raise (l->data);
5219             }
5220
5221           g_list_free (native_children);
5222         }
5223
5224     }
5225 }
5226
5227 /* Returns TRUE If the native window was mapped or unmapped */
5228 static gboolean
5229 set_viewable (GdkWindow *w,
5230               gboolean val)
5231 {
5232   GdkWindow *child;
5233   GdkWindowImplClass *impl_class;
5234   GList *l;
5235
5236   if (w->viewable == val)
5237     return FALSE;
5238
5239   w->viewable = val;
5240
5241   if (val)
5242     recompute_visible_regions (w, FALSE, FALSE);
5243
5244   for (l = w->children; l != NULL; l = l->next)
5245     {
5246       child = l->data;
5247
5248       if (GDK_WINDOW_IS_MAPPED (child) &&
5249           child->window_type != GDK_WINDOW_FOREIGN)
5250         set_viewable (child, val);
5251     }
5252
5253   if (gdk_window_has_impl (w)  &&
5254       w->window_type != GDK_WINDOW_FOREIGN &&
5255       !gdk_window_is_toplevel (w))
5256     {
5257       /* For most native windows we show/hide them not when they are
5258        * mapped/unmapped, because that may not produce the correct results.
5259        * For instance, if a native window have a non-native parent which is
5260        * hidden, but its native parent is viewable then showing the window
5261        * would make it viewable to X but its not viewable wrt the non-native
5262        * hierarchy. In order to handle this we track the gdk side viewability
5263        * and only map really viewable windows.
5264        *
5265        * There are two exceptions though:
5266        *
5267        * For foreign windows we don't want ever change the mapped state
5268        * except when explicitly done via gdk_window_show/hide, as this may
5269        * cause problems for client owning the foreign window when its window
5270        * is suddenly mapped or unmapped.
5271        *
5272        * For toplevel windows embedded in a foreign window (e.g. a plug)
5273        * we sometimes synthesize a map of a window, but the native
5274        * window is really shown by the embedder, so we don't want to
5275        * do the show ourselves. We can't really tell this case from the normal
5276        * toplevel show as such toplevels are seen by gdk as parents of the
5277        * root window, so we make an exception for all toplevels.
5278        */
5279
5280       impl_class = GDK_WINDOW_IMPL_GET_CLASS (w->impl);
5281       if (val)
5282         impl_class->show ((GdkWindow *)w, FALSE);
5283       else
5284         impl_class->hide ((GdkWindow *)w);
5285
5286       return TRUE;
5287     }
5288
5289   return FALSE;
5290 }
5291
5292 /* Returns TRUE If the native window was mapped or unmapped */
5293 gboolean
5294 _gdk_window_update_viewable (GdkWindow *window)
5295 {
5296   gboolean viewable;
5297
5298   if (window->window_type == GDK_WINDOW_FOREIGN ||
5299       window->window_type == GDK_WINDOW_ROOT)
5300     viewable = TRUE;
5301   else if (gdk_window_is_toplevel (window) ||
5302            window->parent->viewable)
5303     viewable = GDK_WINDOW_IS_MAPPED (window);
5304   else
5305     viewable = FALSE;
5306
5307   return set_viewable (window, viewable);
5308 }
5309
5310 static void
5311 gdk_window_show_internal (GdkWindow *window, gboolean raise)
5312 {
5313   GdkWindowImplClass *impl_class;
5314   gboolean was_mapped, was_viewable;
5315   gboolean did_show;
5316
5317   g_return_if_fail (GDK_IS_WINDOW (window));
5318
5319   if (window->destroyed)
5320     return;
5321
5322   was_mapped = GDK_WINDOW_IS_MAPPED (window);
5323   was_viewable = window->viewable;
5324
5325   if (raise)
5326     /* Keep children in (reverse) stacking order */
5327     gdk_window_raise_internal (window);
5328
5329   if (gdk_window_has_impl (window))
5330     {
5331       if (!was_mapped)
5332         gdk_synthesize_window_state (window,
5333                                      GDK_WINDOW_STATE_WITHDRAWN,
5334                                      GDK_WINDOW_STATE_FOCUSED);
5335     }
5336   else
5337     {
5338       window->state = 0;
5339     }
5340
5341   did_show = _gdk_window_update_viewable (window);
5342
5343   /* If it was already viewable the backend show op won't be called, call it
5344      again to ensure things happen right if the mapped tracking was not right
5345      for e.g. a foreign window.
5346      Dunno if this is strictly needed but its what happened pre-csw.
5347      Also show if not done by gdk_window_update_viewable. */
5348   if (gdk_window_has_impl (window) && (was_viewable || !did_show))
5349     {
5350       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
5351       impl_class->show (window, !did_show ? was_mapped : TRUE);
5352     }
5353
5354   if (!was_mapped && !gdk_window_has_impl (window))
5355     {
5356       if (window->event_mask & GDK_STRUCTURE_MASK)
5357         _gdk_make_event (window, GDK_MAP, NULL, FALSE);
5358
5359       if (window->parent && window->parent->event_mask & GDK_SUBSTRUCTURE_MASK)
5360         _gdk_make_event (window, GDK_MAP, NULL, FALSE);
5361     }
5362
5363   if (!was_mapped || raise)
5364     {
5365       recompute_visible_regions (window, TRUE, FALSE);
5366
5367       /* If any decendants became visible we need to send visibility notify */
5368       gdk_window_update_visibility_recursively (window, NULL);
5369
5370       if (gdk_window_is_viewable (window))
5371         {
5372           _gdk_synthesize_crossing_events_for_geometry_change (window);
5373           gdk_window_invalidate_rect_full (window, NULL, TRUE, CLEAR_BG_ALL);
5374         }
5375     }
5376 }
5377
5378 /**
5379  * gdk_window_show_unraised:
5380  * @window: a #GdkWindow
5381  *
5382  * Shows a #GdkWindow onscreen, but does not modify its stacking
5383  * order. In contrast, gdk_window_show() will raise the window
5384  * to the top of the window stack.
5385  *
5386  * On the X11 platform, in Xlib terms, this function calls
5387  * XMapWindow() (it also updates some internal GDK state, which means
5388  * that you can't really use XMapWindow() directly on a GDK window).
5389  */
5390 void
5391 gdk_window_show_unraised (GdkWindow *window)
5392 {
5393   gdk_window_show_internal (window, FALSE);
5394 }
5395
5396 /**
5397  * gdk_window_raise:
5398  * @window: a #GdkWindow
5399  *
5400  * Raises @window to the top of the Z-order (stacking order), so that
5401  * other windows with the same parent window appear below @window.
5402  * This is true whether or not the windows are visible.
5403  *
5404  * If @window is a toplevel, the window manager may choose to deny the
5405  * request to move the window in the Z-order, gdk_window_raise() only
5406  * requests the restack, does not guarantee it.
5407  */
5408 void
5409 gdk_window_raise (GdkWindow *window)
5410 {
5411   g_return_if_fail (GDK_IS_WINDOW (window));
5412
5413   if (window->destroyed)
5414     return;
5415
5416   /* Keep children in (reverse) stacking order */
5417   gdk_window_raise_internal (window);
5418
5419   recompute_visible_regions (window, TRUE, FALSE);
5420
5421   if (gdk_window_is_viewable (window) &&
5422       !window->input_only)
5423     gdk_window_invalidate_region_full (window, window->clip_region, TRUE, CLEAR_BG_ALL);
5424 }
5425
5426 static void
5427 gdk_window_lower_internal (GdkWindow *window)
5428 {
5429   GdkWindow *parent = window->parent;
5430   GdkWindowImplClass *impl_class;
5431   GdkWindow *above;
5432   GList *native_children;
5433   GList *l, listhead;
5434
5435   if (parent)
5436     {
5437       parent->children = g_list_remove (parent->children, window);
5438       parent->children = g_list_append (parent->children, window);
5439     }
5440
5441   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
5442   /* Just do native lower for toplevels */
5443   if (gdk_window_is_toplevel (window) ||
5444       /* The restack_under codepath should work correctly even if the parent
5445          is native, but it relies on the order of ->children to be correct,
5446          and some apps like SWT reorder the x windows without gdks knowledge,
5447          so we use lower directly in order to make these behave as before
5448          when using native windows */
5449       (gdk_window_has_impl (window) && gdk_window_has_impl (parent)))
5450     {
5451       impl_class->lower (window);
5452     }
5453   else if (gdk_window_has_impl (window))
5454     {
5455       above = find_native_sibling_above (parent, window);
5456       if (above)
5457         {
5458           listhead.data = window;
5459           listhead.next = NULL;
5460           listhead.prev = NULL;
5461           impl_class->restack_under ((GdkWindow *)above, &listhead);
5462         }
5463       else
5464         impl_class->raise (window);
5465     }
5466   else
5467     {
5468       native_children = NULL;
5469       get_all_native_children (window, &native_children);
5470       if (native_children != NULL)
5471         {
5472           above = find_native_sibling_above (parent, window);
5473
5474           if (above)
5475             impl_class->restack_under ((GdkWindow *)above,
5476                                        native_children);
5477           else
5478             {
5479               /* Right order, since native_children is bottom-topmost first */
5480               for (l = native_children; l != NULL; l = l->next)
5481                 impl_class->raise (l->data);
5482             }
5483
5484           g_list_free (native_children);
5485         }
5486
5487     }
5488 }
5489
5490 static void
5491 gdk_window_invalidate_in_parent (GdkWindow *private)
5492 {
5493   GdkRectangle r, child;
5494
5495   if (gdk_window_is_toplevel (private))
5496     return;
5497
5498   /* get the visible rectangle of the parent */
5499   r.x = r.y = 0;
5500   r.width = private->parent->width;
5501   r.height = private->parent->height;
5502
5503   child.x = private->x;
5504   child.y = private->y;
5505   child.width = private->width;
5506   child.height = private->height;
5507   gdk_rectangle_intersect (&r, &child, &r);
5508
5509   gdk_window_invalidate_rect_full (private->parent, &r, TRUE, CLEAR_BG_ALL);
5510 }
5511
5512
5513 /**
5514  * gdk_window_lower:
5515  * @window: a #GdkWindow
5516  *
5517  * Lowers @window to the bottom of the Z-order (stacking order), so that
5518  * other windows with the same parent window appear above @window.
5519  * This is true whether or not the other windows are visible.
5520  *
5521  * If @window is a toplevel, the window manager may choose to deny the
5522  * request to move the window in the Z-order, gdk_window_lower() only
5523  * requests the restack, does not guarantee it.
5524  *
5525  * Note that gdk_window_show() raises the window again, so don't call this
5526  * function before gdk_window_show(). (Try gdk_window_show_unraised().)
5527  */
5528 void
5529 gdk_window_lower (GdkWindow *window)
5530 {
5531   g_return_if_fail (GDK_IS_WINDOW (window));
5532
5533   if (window->destroyed)
5534     return;
5535
5536   /* Keep children in (reverse) stacking order */
5537   gdk_window_lower_internal (window);
5538
5539   recompute_visible_regions (window, TRUE, FALSE);
5540
5541   _gdk_synthesize_crossing_events_for_geometry_change (window);
5542   gdk_window_invalidate_in_parent (window);
5543 }
5544
5545 /**
5546  * gdk_window_restack:
5547  * @window: a #GdkWindow
5548  * @sibling: (allow-none): a #GdkWindow that is a sibling of @window, or %NULL
5549  * @above: a boolean
5550  *
5551  * Changes the position of  @window in the Z-order (stacking order), so that
5552  * it is above @sibling (if @above is %TRUE) or below @sibling (if @above is
5553  * %FALSE).
5554  *
5555  * If @sibling is %NULL, then this either raises (if @above is %TRUE) or
5556  * lowers the window.
5557  *
5558  * If @window is a toplevel, the window manager may choose to deny the
5559  * request to move the window in the Z-order, gdk_window_restack() only
5560  * requests the restack, does not guarantee it.
5561  *
5562  * Since: 2.18
5563  */
5564 void
5565 gdk_window_restack (GdkWindow     *window,
5566                     GdkWindow     *sibling,
5567                     gboolean       above)
5568 {
5569   GdkWindowImplClass *impl_class;
5570   GdkWindow *parent;
5571   GdkWindow *above_native;
5572   GList *sibling_link;
5573   GList *native_children;
5574   GList *l, listhead;
5575
5576   g_return_if_fail (GDK_IS_WINDOW (window));
5577   g_return_if_fail (sibling == NULL || GDK_IS_WINDOW (sibling));
5578
5579   if (window->destroyed)
5580     return;
5581
5582   if (sibling == NULL)
5583     {
5584       if (above)
5585         gdk_window_raise (window);
5586       else
5587         gdk_window_lower (window);
5588       return;
5589     }
5590
5591   if (gdk_window_is_toplevel (window))
5592     {
5593       g_return_if_fail (gdk_window_is_toplevel (sibling));
5594       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
5595       impl_class->restack_toplevel (window, sibling, above);
5596       return;
5597     }
5598
5599   parent = window->parent;
5600   if (parent)
5601     {
5602       sibling_link = g_list_find (parent->children, sibling);
5603       g_return_if_fail (sibling_link != NULL);
5604       if (sibling_link == NULL)
5605         return;
5606
5607       parent->children = g_list_remove (parent->children, window);
5608       if (above)
5609         parent->children = g_list_insert_before (parent->children,
5610                                                  sibling_link,
5611                                                  window);
5612       else
5613         parent->children = g_list_insert_before (parent->children,
5614                                                  sibling_link->next,
5615                                                  window);
5616
5617       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
5618       if (gdk_window_has_impl (window))
5619         {
5620           above_native = find_native_sibling_above (parent, window);
5621           if (above_native)
5622             {
5623               listhead.data = window;
5624               listhead.next = NULL;
5625               listhead.prev = NULL;
5626               impl_class->restack_under (above_native, &listhead);
5627             }
5628           else
5629             impl_class->raise (window);
5630         }
5631       else
5632         {
5633           native_children = NULL;
5634           get_all_native_children (window, &native_children);
5635           if (native_children != NULL)
5636             {
5637               above_native = find_native_sibling_above (parent, window);
5638               if (above_native)
5639                 impl_class->restack_under (above_native,
5640                                            native_children);
5641               else
5642                 {
5643                   /* Right order, since native_children is bottom-topmost first */
5644                   for (l = native_children; l != NULL; l = l->next)
5645                     impl_class->raise (l->data);
5646                 }
5647
5648               g_list_free (native_children);
5649             }
5650         }
5651     }
5652
5653   recompute_visible_regions (window, TRUE, FALSE);
5654
5655   _gdk_synthesize_crossing_events_for_geometry_change (window);
5656   gdk_window_invalidate_in_parent (window);
5657 }
5658
5659
5660 /**
5661  * gdk_window_show:
5662  * @window: a #GdkWindow
5663  *
5664  * Like gdk_window_show_unraised(), but also raises the window to the
5665  * top of the window stack (moves the window to the front of the
5666  * Z-order).
5667  *
5668  * This function maps a window so it's visible onscreen. Its opposite
5669  * is gdk_window_hide().
5670  *
5671  * When implementing a #GtkWidget, you should call this function on the widget's
5672  * #GdkWindow as part of the "map" method.
5673  */
5674 void
5675 gdk_window_show (GdkWindow *window)
5676 {
5677   gdk_window_show_internal (window, TRUE);
5678 }
5679
5680 /**
5681  * gdk_window_hide:
5682  * @window: a #GdkWindow
5683  *
5684  * For toplevel windows, withdraws them, so they will no longer be
5685  * known to the window manager; for all windows, unmaps them, so
5686  * they won't be displayed. Normally done automatically as
5687  * part of gtk_widget_hide().
5688  */
5689 void
5690 gdk_window_hide (GdkWindow *window)
5691 {
5692   GdkWindowImplClass *impl_class;
5693   gboolean was_mapped, did_hide;
5694
5695   g_return_if_fail (GDK_IS_WINDOW (window));
5696
5697   if (window->destroyed)
5698     return;
5699
5700   was_mapped = GDK_WINDOW_IS_MAPPED (window);
5701
5702   if (gdk_window_has_impl (window))
5703     {
5704
5705       if (GDK_WINDOW_IS_MAPPED (window))
5706         gdk_synthesize_window_state (window,
5707                                      0,
5708                                      GDK_WINDOW_STATE_WITHDRAWN);
5709     }
5710   else if (was_mapped)
5711     {
5712       GdkDisplay *display;
5713       GdkDeviceManager *device_manager;
5714       GList *devices, *d;
5715
5716       /* May need to break grabs on children */
5717       display = gdk_window_get_display (window);
5718       device_manager = gdk_display_get_device_manager (display);
5719
5720       /* Get all devices */
5721       devices = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_MASTER);
5722       devices = g_list_concat (devices, gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_SLAVE));
5723       devices = g_list_concat (devices, gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_FLOATING));
5724
5725       for (d = devices; d; d = d->next)
5726         {
5727           GdkDevice *device = d->data;
5728
5729           if (_gdk_display_end_device_grab (display,
5730                                             device,
5731                                             _gdk_display_get_next_serial (display),
5732                                             window,
5733                                             TRUE))
5734             gdk_device_ungrab (device, GDK_CURRENT_TIME);
5735         }
5736
5737       window->state = GDK_WINDOW_STATE_WITHDRAWN;
5738       g_list_free (devices);
5739     }
5740
5741   did_hide = _gdk_window_update_viewable (window);
5742
5743   /* Hide foreign window as those are not handled by update_viewable. */
5744   if (gdk_window_has_impl (window) && (!did_hide))
5745     {
5746       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
5747       impl_class->hide (window);
5748     }
5749
5750   recompute_visible_regions (window, TRUE, FALSE);
5751
5752   /* all decendants became non-visible, we need to send visibility notify */
5753   gdk_window_update_visibility_recursively (window, NULL);
5754
5755   if (was_mapped && !gdk_window_has_impl (window))
5756     {
5757       if (window->event_mask & GDK_STRUCTURE_MASK)
5758         _gdk_make_event (window, GDK_UNMAP, NULL, FALSE);
5759
5760       if (window->parent && window->parent->event_mask & GDK_SUBSTRUCTURE_MASK)
5761         _gdk_make_event (window, GDK_UNMAP, NULL, FALSE);
5762
5763       _gdk_synthesize_crossing_events_for_geometry_change (window->parent);
5764     }
5765
5766   /* Invalidate the rect */
5767   if (was_mapped)
5768     gdk_window_invalidate_in_parent (window);
5769 }
5770
5771 /**
5772  * gdk_window_withdraw:
5773  * @window: a toplevel #GdkWindow
5774  *
5775  * Withdraws a window (unmaps it and asks the window manager to forget about it).
5776  * This function is not really useful as gdk_window_hide() automatically
5777  * withdraws toplevel windows before hiding them.
5778  **/
5779 void
5780 gdk_window_withdraw (GdkWindow *window)
5781 {
5782   GdkWindowImplClass *impl_class;
5783   gboolean was_mapped;
5784
5785   g_return_if_fail (GDK_IS_WINDOW (window));
5786
5787   if (window->destroyed)
5788     return;
5789
5790   was_mapped = GDK_WINDOW_IS_MAPPED (window);
5791
5792   if (gdk_window_has_impl (window))
5793     {
5794       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
5795       impl_class->withdraw (window);
5796
5797       if (was_mapped)
5798         {
5799           if (window->event_mask & GDK_STRUCTURE_MASK)
5800             _gdk_make_event (window, GDK_UNMAP, NULL, FALSE);
5801
5802           if (window->parent && window->parent->event_mask & GDK_SUBSTRUCTURE_MASK)
5803             _gdk_make_event (window, GDK_UNMAP, NULL, FALSE);
5804
5805           _gdk_synthesize_crossing_events_for_geometry_change (window->parent);
5806         }
5807
5808       recompute_visible_regions (window, TRUE, FALSE);
5809     }
5810 }
5811
5812 /**
5813  * gdk_window_set_events:
5814  * @window: a #GdkWindow
5815  * @event_mask: event mask for @window
5816  *
5817  * The event mask for a window determines which events will be reported
5818  * for that window from all master input devices. For example, an event mask
5819  * including #GDK_BUTTON_PRESS_MASK means the window should report button
5820  * press events. The event mask is the bitwise OR of values from the
5821  * #GdkEventMask enumeration.
5822  **/
5823 void
5824 gdk_window_set_events (GdkWindow       *window,
5825                        GdkEventMask     event_mask)
5826 {
5827   GdkWindowImplClass *impl_class;
5828   GdkDisplay *display;
5829
5830   g_return_if_fail (GDK_IS_WINDOW (window));
5831
5832   if (window->destroyed)
5833     return;
5834
5835   /* If motion hint is disabled, enable motion events again */
5836   display = gdk_window_get_display (window);
5837   if ((window->event_mask & GDK_POINTER_MOTION_HINT_MASK) &&
5838       !(event_mask & GDK_POINTER_MOTION_HINT_MASK))
5839     {
5840       GList *devices = window->devices_inside;
5841
5842       while (devices)
5843         {
5844           _gdk_display_enable_motion_hints (display, (GdkDevice *) devices->data);
5845           devices = devices->next;
5846         }
5847     }
5848
5849   window->event_mask = event_mask;
5850
5851   if (gdk_window_has_impl (window))
5852     {
5853       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
5854       impl_class->set_events (window,
5855                               get_native_event_mask (window));
5856     }
5857
5858 }
5859
5860 /**
5861  * gdk_window_get_events:
5862  * @window: a #GdkWindow
5863  *
5864  * Gets the event mask for @window for all master input devices. See
5865  * gdk_window_set_events().
5866  *
5867  * Return value: event mask for @window
5868  **/
5869 GdkEventMask
5870 gdk_window_get_events (GdkWindow *window)
5871 {
5872   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
5873
5874   if (window->destroyed)
5875     return 0;
5876
5877   return window->event_mask;
5878 }
5879
5880 /**
5881  * gdk_window_set_device_events:
5882  * @window: a #GdkWindow
5883  * @device: #GdkDevice to enable events for.
5884  * @event_mask: event mask for @window
5885  *
5886  * Sets the event mask for a given device (Normally a floating device, not
5887  * attached to any visible pointer) to @window. For example, an event mask
5888  * including #GDK_BUTTON_PRESS_MASK means the window should report button
5889  * press events. The event mask is the bitwise OR of values from the
5890  * #GdkEventMask enumeration.
5891  *
5892  * Since: 3.0
5893  **/
5894 void
5895 gdk_window_set_device_events (GdkWindow    *window,
5896                               GdkDevice    *device,
5897                               GdkEventMask  event_mask)
5898 {
5899   GdkEventMask device_mask;
5900   GdkDisplay *display;
5901   GdkWindow *native;
5902
5903   g_return_if_fail (GDK_IS_WINDOW (window));
5904   g_return_if_fail (GDK_IS_DEVICE (device));
5905
5906   if (GDK_WINDOW_DESTROYED (window))
5907     return;
5908
5909   /* If motion hint is disabled, enable motion events again */
5910   display = gdk_window_get_display (window);
5911   if ((window->event_mask & GDK_POINTER_MOTION_HINT_MASK) &&
5912       !(event_mask & GDK_POINTER_MOTION_HINT_MASK))
5913     _gdk_display_enable_motion_hints (display, device);
5914
5915   if (G_UNLIKELY (!window->device_events))
5916     window->device_events = g_hash_table_new (NULL, NULL);
5917
5918   if (event_mask == 0)
5919     {
5920       /* FIXME: unsetting events on a master device
5921        * would restore window->event_mask
5922        */
5923       g_hash_table_remove (window->device_events, device);
5924     }
5925   else
5926     g_hash_table_insert (window->device_events, device,
5927                          GINT_TO_POINTER (event_mask));
5928
5929   native = gdk_window_get_toplevel (window);
5930
5931   while (gdk_window_is_offscreen (native))
5932     {
5933       native = gdk_offscreen_window_get_embedder (native);
5934
5935       if (native == NULL ||
5936           (!_gdk_window_has_impl (native) &&
5937            !gdk_window_is_viewable (native)))
5938         return;
5939
5940       native = gdk_window_get_toplevel (native);
5941     }
5942
5943   device_mask = get_native_device_event_mask (window, device);
5944   GDK_DEVICE_GET_CLASS (device)->select_window_events (device, native, device_mask);
5945 }
5946
5947 /**
5948  * gdk_window_get_device_events:
5949  * @window: a #GdkWindow.
5950  * @device: a #GdkDevice.
5951  *
5952  * Returns the event mask for @window corresponding to an specific device.
5953  *
5954  * Returns: device event mask for @window
5955  *
5956  * Since: 3.0
5957  **/
5958 GdkEventMask
5959 gdk_window_get_device_events (GdkWindow *window,
5960                               GdkDevice *device)
5961 {
5962   GdkEventMask mask;
5963
5964   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
5965   g_return_val_if_fail (GDK_IS_DEVICE (device), 0);
5966
5967   if (GDK_WINDOW_DESTROYED (window))
5968     return 0;
5969
5970   if (!window->device_events)
5971     return 0;
5972
5973   mask = GPOINTER_TO_INT (g_hash_table_lookup (window->device_events, device));
5974
5975   /* FIXME: device could be controlled by window->event_mask */
5976
5977   return mask;
5978 }
5979
5980 static void
5981 gdk_window_move_resize_toplevel (GdkWindow *window,
5982                                  gboolean   with_move,
5983                                  gint       x,
5984                                  gint       y,
5985                                  gint       width,
5986                                  gint       height)
5987 {
5988   cairo_region_t *old_region, *new_region;
5989   GdkWindowImplClass *impl_class;
5990   gboolean expose;
5991   gboolean is_resize;
5992
5993   expose = FALSE;
5994   old_region = NULL;
5995
5996   is_resize = (width != -1) || (height != -1);
5997
5998   if (gdk_window_is_viewable (window) &&
5999       !window->input_only)
6000     {
6001       expose = TRUE;
6002       old_region = cairo_region_copy (window->clip_region);
6003     }
6004
6005   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
6006   impl_class->move_resize (window, with_move, x, y, width, height);
6007
6008   /* Avoid recomputing for pure toplevel moves, for performance reasons */
6009   if (is_resize)
6010     recompute_visible_regions (window, TRUE, FALSE);
6011
6012   if (expose)
6013     {
6014       new_region = cairo_region_copy (window->clip_region);
6015
6016       /* This is the newly exposed area (due to any resize),
6017        * X will expose it, but lets do that without the roundtrip
6018        */
6019       cairo_region_subtract (new_region, old_region);
6020       gdk_window_invalidate_region_full (window, new_region, TRUE, CLEAR_BG_WINCLEARED);
6021
6022       cairo_region_destroy (old_region);
6023       cairo_region_destroy (new_region);
6024     }
6025
6026   _gdk_synthesize_crossing_events_for_geometry_change (window);
6027 }
6028
6029
6030 static void
6031 move_native_children (GdkWindow *private)
6032 {
6033   GList *l;
6034   GdkWindow *child;
6035   GdkWindowImplClass *impl_class;
6036
6037   for (l = private->children; l; l = l->next)
6038     {
6039       child = l->data;
6040
6041       if (child->impl != private->impl)
6042         {
6043           impl_class = GDK_WINDOW_IMPL_GET_CLASS (child->impl);
6044           impl_class->move_resize (child, TRUE,
6045                                    child->x, child->y,
6046                                    child->width, child->height);
6047         }
6048       else
6049         move_native_children  (child);
6050     }
6051 }
6052
6053 static gboolean
6054 collect_native_child_region_helper (GdkWindow *window,
6055                                     GdkWindowImpl *impl,
6056                                     cairo_region_t **region,
6057                                     int x_offset,
6058                                     int y_offset)
6059 {
6060   GdkWindow *child;
6061   cairo_region_t *tmp;
6062   GList *l;
6063
6064   for (l = window->children; l != NULL; l = l->next)
6065     {
6066       child = l->data;
6067
6068       if (!GDK_WINDOW_IS_MAPPED (child) || child->input_only)
6069         continue;
6070
6071       if (child->impl != impl)
6072         {
6073           tmp = cairo_region_copy (child->clip_region);
6074           cairo_region_translate (tmp,
6075                              x_offset + child->x,
6076                              y_offset + child->y);
6077           if (*region == NULL)
6078             *region = tmp;
6079           else
6080             {
6081               cairo_region_union (*region, tmp);
6082               cairo_region_destroy (tmp);
6083             }
6084         }
6085       else
6086         collect_native_child_region_helper (child, impl, region,
6087                                             x_offset + child->x,
6088                                             y_offset + child->y);
6089     }
6090
6091   return FALSE;
6092 }
6093
6094 static cairo_region_t *
6095 collect_native_child_region (GdkWindow *window,
6096                              gboolean include_this)
6097 {
6098   cairo_region_t *region;
6099
6100   if (include_this && gdk_window_has_impl (window) && window->viewable)
6101     return cairo_region_copy (window->clip_region);
6102
6103   region = NULL;
6104
6105   collect_native_child_region_helper (window, window->impl, &region, 0, 0);
6106
6107   return region;
6108 }
6109
6110
6111 static void
6112 gdk_window_move_resize_internal (GdkWindow *window,
6113                                  gboolean   with_move,
6114                                  gint       x,
6115                                  gint       y,
6116                                  gint       width,
6117                                  gint       height)
6118 {
6119   cairo_region_t *old_region, *old_layered, *new_region, *copy_area;
6120   cairo_region_t *old_native_child_region, *new_native_child_region;
6121   GdkWindow *impl_window;
6122   GdkWindowImplClass *impl_class;
6123   gboolean expose;
6124   int old_x, old_y, old_abs_x, old_abs_y;
6125   int dx, dy;
6126
6127   g_return_if_fail (GDK_IS_WINDOW (window));
6128
6129   if (window->destroyed)
6130     return;
6131
6132   if (gdk_window_is_toplevel (window))
6133     {
6134       gdk_window_move_resize_toplevel (window, with_move, x, y, width, height);
6135       return;
6136     }
6137
6138   /* Bail early if no change */
6139   if (window->width == width &&
6140       window->height == height &&
6141       (!with_move ||
6142        (window->x == x &&
6143         window->y == y)))
6144     return;
6145
6146   /* Handle child windows */
6147
6148   expose = FALSE;
6149   old_region = NULL;
6150   old_layered = NULL;
6151
6152   impl_window = gdk_window_get_impl_window (window);
6153
6154   old_x = window->x;
6155   old_y = window->y;
6156
6157   old_native_child_region = NULL;
6158   if (gdk_window_is_viewable (window) &&
6159       !window->input_only)
6160     {
6161       expose = TRUE;
6162
6163       old_region = cairo_region_copy (window->clip_region);
6164       old_layered = cairo_region_copy (window->layered_region);
6165       /* Adjust regions to parent window coords */
6166       cairo_region_translate (old_region, window->x, window->y);
6167       cairo_region_translate (old_layered, window->x, window->y);
6168
6169       old_native_child_region = collect_native_child_region (window, TRUE);
6170       if (old_native_child_region)
6171         {
6172           /* Adjust region to parent window coords */
6173           cairo_region_translate (old_native_child_region, window->x, window->y);
6174
6175           /* Any native window move will immediately copy stuff to the destination, which may overwrite a
6176            * source or destination for a delayed GdkWindowRegionMove. So, we need
6177            * to flush those here for the parent window and all overlapped subwindows
6178            * of it. And we need to do this before setting the new clips as those will be
6179            * affecting this.
6180            */
6181           gdk_window_flush_recursive (window->parent);
6182         }
6183     }
6184
6185   /* Set the new position and size */
6186   if (with_move)
6187     {
6188       window->x = x;
6189       window->y = y;
6190     }
6191   if (!(width < 0 && height < 0))
6192     {
6193       if (width < 1)
6194         width = 1;
6195       window->width = width;
6196       if (height < 1)
6197         height = 1;
6198       window->height = height;
6199     }
6200
6201   dx = window->x - old_x;
6202   dy = window->y - old_y;
6203
6204   old_abs_x = window->abs_x;
6205   old_abs_y = window->abs_y;
6206
6207   recompute_visible_regions (window, TRUE, FALSE);
6208
6209   new_native_child_region = NULL;
6210   if (old_native_child_region)
6211     {
6212       new_native_child_region = collect_native_child_region (window, TRUE);
6213       /* Adjust region to parent window coords */
6214       cairo_region_translate (new_native_child_region, window->x, window->y);
6215     }
6216
6217   if (gdk_window_has_impl (window))
6218     {
6219       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
6220
6221       /* Do the actual move after recomputing things, as this will have set the shape to
6222          the now correct one, thus avoiding copying regions that should not be copied. */
6223       impl_class->move_resize (window, TRUE,
6224                                window->x, window->y,
6225                                window->width, window->height);
6226     }
6227   else if (old_abs_x != window->abs_x ||
6228            old_abs_y != window->abs_y)
6229     move_native_children (window);
6230
6231   if (expose)
6232     {
6233       new_region = cairo_region_copy (window->clip_region);
6234       /* Adjust region to parent window coords */
6235       cairo_region_translate (new_region, window->x, window->y);
6236
6237       /* copy_area:
6238        * Part of the data at the new location can be copied from the
6239        * old location, this area is the intersection of the old region
6240        * moved as the copy will move it and then intersected with
6241        * the new region.
6242        *
6243        * new_region:
6244        * Everything in the old and new regions that is not copied must be
6245        * invalidated (including children) as this is newly exposed
6246        */
6247       if (gdk_window_has_alpha (window))
6248         copy_area = cairo_region_create (); /* Copy nothing for alpha windows */
6249       else
6250         copy_area = cairo_region_copy (new_region);
6251
6252       /* Don't copy from a previously layered region */
6253       cairo_region_translate (old_layered, dx, dy);
6254       cairo_region_subtract (copy_area, old_layered);
6255
6256       /* Don't copy into a layered region */
6257       cairo_region_translate (copy_area, -window->x, -window->y);
6258       cairo_region_subtract (copy_area, window->layered_region);
6259       cairo_region_translate (copy_area, window->x, window->y);
6260
6261       cairo_region_union (new_region, old_region);
6262
6263       if (old_native_child_region)
6264         {
6265           /* Don't copy from inside native children, as this is copied by
6266            * the native window move.
6267            */
6268           cairo_region_subtract (old_region, old_native_child_region);
6269         }
6270       cairo_region_translate (old_region, dx, dy);
6271
6272       cairo_region_intersect (copy_area, old_region);
6273
6274       if (new_native_child_region)
6275         {
6276           /* Don't copy any bits that would cause a read from the moved
6277              native windows, as we can't read that data */
6278           cairo_region_translate (new_native_child_region, dx, dy);
6279           cairo_region_subtract (copy_area, new_native_child_region);
6280           cairo_region_translate (new_native_child_region, -dx, -dy);
6281         }
6282
6283       cairo_region_subtract (new_region, copy_area);
6284
6285       /* Convert old region to impl coords */
6286       cairo_region_translate (old_region, -dx + window->abs_x - window->x, -dy + window->abs_y - window->y);
6287
6288       /* convert from parent coords to impl */
6289       cairo_region_translate (copy_area, window->abs_x - window->x, window->abs_y - window->y);
6290
6291       move_region_on_impl (impl_window, copy_area, dx, dy); /* takes ownership of copy_area */
6292
6293       /* Invalidate affected part in the parent window
6294        *  (no higher window should be affected)
6295        * We also invalidate any children in that area, which could include
6296        * this window if it still overlaps that area.
6297        */
6298       if (old_native_child_region)
6299         {
6300           /* No need to expose the region that the native window move copies */
6301           cairo_region_translate (old_native_child_region, dx, dy);
6302           cairo_region_intersect (old_native_child_region, new_native_child_region);
6303           cairo_region_subtract (new_region, old_native_child_region);
6304         }
6305       gdk_window_invalidate_region_full (window->parent, new_region, TRUE, CLEAR_BG_ALL);
6306
6307       cairo_region_destroy (old_region);
6308       cairo_region_destroy (old_layered);
6309       cairo_region_destroy (new_region);
6310     }
6311
6312   if (old_native_child_region)
6313     {
6314       cairo_region_destroy (old_native_child_region);
6315       cairo_region_destroy (new_native_child_region);
6316     }
6317
6318   _gdk_synthesize_crossing_events_for_geometry_change (window);
6319 }
6320
6321
6322
6323 /**
6324  * gdk_window_move:
6325  * @window: a #GdkWindow
6326  * @x: X coordinate relative to window's parent
6327  * @y: Y coordinate relative to window's parent
6328  *
6329  * Repositions a window relative to its parent window.
6330  * For toplevel windows, window managers may ignore or modify the move;
6331  * you should probably use gtk_window_move() on a #GtkWindow widget
6332  * anyway, instead of using GDK functions. For child windows,
6333  * the move will reliably succeed.
6334  *
6335  * If you're also planning to resize the window, use gdk_window_move_resize()
6336  * to both move and resize simultaneously, for a nicer visual effect.
6337  **/
6338 void
6339 gdk_window_move (GdkWindow *window,
6340                  gint       x,
6341                  gint       y)
6342 {
6343   gdk_window_move_resize_internal (window, TRUE, x, y, -1, -1);
6344 }
6345
6346 /**
6347  * gdk_window_resize:
6348  * @window: a #GdkWindow
6349  * @width: new width of the window
6350  * @height: new height of the window
6351  *
6352  * Resizes @window; for toplevel windows, asks the window manager to resize
6353  * the window. The window manager may not allow the resize. When using GTK+,
6354  * use gtk_window_resize() instead of this low-level GDK function.
6355  *
6356  * Windows may not be resized below 1x1.
6357  *
6358  * If you're also planning to move the window, use gdk_window_move_resize()
6359  * to both move and resize simultaneously, for a nicer visual effect.
6360  **/
6361 void
6362 gdk_window_resize (GdkWindow *window,
6363                    gint       width,
6364                    gint       height)
6365 {
6366   gdk_window_move_resize_internal (window, FALSE, 0, 0, width, height);
6367 }
6368
6369
6370 /**
6371  * gdk_window_move_resize:
6372  * @window: a #GdkWindow
6373  * @x: new X position relative to window's parent
6374  * @y: new Y position relative to window's parent
6375  * @width: new width
6376  * @height: new height
6377  *
6378  * Equivalent to calling gdk_window_move() and gdk_window_resize(),
6379  * except that both operations are performed at once, avoiding strange
6380  * visual effects. (i.e. the user may be able to see the window first
6381  * move, then resize, if you don't use gdk_window_move_resize().)
6382  **/
6383 void
6384 gdk_window_move_resize (GdkWindow *window,
6385                         gint       x,
6386                         gint       y,
6387                         gint       width,
6388                         gint       height)
6389 {
6390   gdk_window_move_resize_internal (window, TRUE, x, y, width, height);
6391 }
6392
6393
6394 /**
6395  * gdk_window_scroll:
6396  * @window: a #GdkWindow
6397  * @dx: Amount to scroll in the X direction
6398  * @dy: Amount to scroll in the Y direction
6399  *
6400  * Scroll the contents of @window, both pixels and children, by the
6401  * given amount. @window itself does not move. Portions of the window
6402  * that the scroll operation brings in from offscreen areas are
6403  * invalidated. The invalidated region may be bigger than what would
6404  * strictly be necessary.
6405  *
6406  * For X11, a minimum area will be invalidated if the window has no
6407  * subwindows, or if the edges of the window's parent do not extend
6408  * beyond the edges of the window. In other cases, a multi-step process
6409  * is used to scroll the window which may produce temporary visual
6410  * artifacts and unnecessary invalidations.
6411  **/
6412 void
6413 gdk_window_scroll (GdkWindow *window,
6414                    gint       dx,
6415                    gint       dy)
6416 {
6417   GdkWindow *impl_window;
6418   cairo_region_t *copy_area, *noncopy_area, *old_layered_area;
6419   cairo_region_t *old_native_child_region, *new_native_child_region;
6420   GList *tmp_list;
6421
6422   g_return_if_fail (GDK_IS_WINDOW (window));
6423
6424   if (dx == 0 && dy == 0)
6425     return;
6426
6427   if (window->destroyed)
6428     return;
6429
6430   old_layered_area = cairo_region_copy (window->layered_region);
6431   old_native_child_region = collect_native_child_region (window, FALSE);
6432   if (old_native_child_region)
6433     {
6434       /* Any native window move will immediately copy stuff to the destination, which may overwrite a
6435        * source or destination for a delayed GdkWindowRegionMove. So, we need
6436        * to flush those here for the window and all overlapped subwindows
6437        * of it. And we need to do this before setting the new clips as those will be
6438        * affecting this.
6439        */
6440       gdk_window_flush_recursive (window);
6441     }
6442
6443
6444   /* First move all child windows, without causing invalidation */
6445
6446   tmp_list = window->children;
6447   while (tmp_list)
6448     {
6449       GdkWindow *child = GDK_WINDOW (tmp_list->data);
6450
6451       /* Just update the positions, the bits will move with the copy */
6452       child->x += dx;
6453       child->y += dy;
6454
6455       tmp_list = tmp_list->next;
6456     }
6457
6458   recompute_visible_regions (window, FALSE, TRUE);
6459
6460   new_native_child_region = NULL;
6461   if (old_native_child_region)
6462     new_native_child_region = collect_native_child_region (window, FALSE);
6463
6464   move_native_children (window);
6465
6466   /* Then copy the actual bits of the window w/ child windows */
6467
6468   impl_window = gdk_window_get_impl_window (window);
6469
6470   /* Calculate the area that can be gotten by copying the old area */
6471   if (gdk_window_has_alpha (window))
6472     copy_area = cairo_region_create (); /* Copy nothing for alpha windows */
6473   else
6474     copy_area = cairo_region_copy (window->clip_region);
6475   cairo_region_subtract (copy_area, old_layered_area);
6476   if (old_native_child_region)
6477     {
6478       /* Don't copy from inside native children, as this is copied by
6479        * the native window move.
6480        */
6481       cairo_region_subtract (copy_area, old_native_child_region);
6482
6483       /* Don't copy any bits that would cause a read from the moved
6484          native windows, as we can't read that data */
6485       cairo_region_subtract (copy_area, new_native_child_region);
6486     }
6487   cairo_region_translate (copy_area, dx, dy);
6488   cairo_region_intersect (copy_area, window->clip_region);
6489   cairo_region_subtract (copy_area, window->layered_region);
6490
6491   /* And the rest need to be invalidated */
6492   noncopy_area = cairo_region_copy (window->clip_region);
6493   cairo_region_subtract (noncopy_area, copy_area);
6494
6495   /* convert from window coords to impl */
6496   cairo_region_translate (copy_area, window->abs_x, window->abs_y);
6497
6498   move_region_on_impl (impl_window, copy_area, dx, dy); /* takes ownership of copy_area */
6499
6500   /* Invalidate not copied regions */
6501   if (old_native_child_region)
6502     {
6503       /* No need to expose the region that the native window move copies */
6504       cairo_region_translate (old_native_child_region, dx, dy);
6505       cairo_region_intersect (old_native_child_region, new_native_child_region);
6506       cairo_region_subtract (noncopy_area, old_native_child_region);
6507     }
6508   gdk_window_invalidate_region_full (window, noncopy_area, TRUE, CLEAR_BG_ALL);
6509
6510   cairo_region_destroy (noncopy_area);
6511   cairo_region_destroy (old_layered_area);
6512
6513   if (old_native_child_region)
6514     {
6515       cairo_region_destroy (old_native_child_region);
6516       cairo_region_destroy (new_native_child_region);
6517     }
6518
6519   _gdk_synthesize_crossing_events_for_geometry_change (window);
6520 }
6521
6522 /**
6523  * gdk_window_move_region:
6524  * @window: a #GdkWindow
6525  * @region: The #cairo_region_t to move
6526  * @dx: Amount to move in the X direction
6527  * @dy: Amount to move in the Y direction
6528  *
6529  * Move the part of @window indicated by @region by @dy pixels in the Y
6530  * direction and @dx pixels in the X direction. The portions of @region
6531  * that not covered by the new position of @region are invalidated.
6532  *
6533  * Child windows are not moved.
6534  *
6535  * Since: 2.8
6536  */
6537 void
6538 gdk_window_move_region (GdkWindow       *window,
6539                         const cairo_region_t *region,
6540                         gint             dx,
6541                         gint             dy)
6542 {
6543   GdkWindow *impl_window;
6544   cairo_region_t *nocopy_area;
6545   cairo_region_t *copy_area;
6546
6547   g_return_if_fail (GDK_IS_WINDOW (window));
6548   g_return_if_fail (region != NULL);
6549
6550   if (dx == 0 && dy == 0)
6551     return;
6552
6553   if (window->destroyed)
6554     return;
6555
6556   impl_window = gdk_window_get_impl_window (window);
6557
6558   /* compute source regions */
6559   if (gdk_window_has_alpha (window))
6560     copy_area = cairo_region_create (); /* Copy nothing for alpha windows */
6561   else
6562     copy_area = cairo_region_copy (region);
6563   cairo_region_intersect (copy_area, window->clip_region_with_children);
6564   cairo_region_subtract (copy_area, window->layered_region);
6565   remove_layered_child_area (window, copy_area);
6566
6567   /* compute destination regions */
6568   cairo_region_translate (copy_area, dx, dy);
6569   cairo_region_intersect (copy_area, window->clip_region_with_children);
6570   cairo_region_subtract (copy_area, window->layered_region);
6571   remove_layered_child_area (window, copy_area);
6572
6573   /* Invalidate parts of the region (source and dest) not covered
6574      by the copy */
6575   nocopy_area = cairo_region_copy (region);
6576   cairo_region_translate (nocopy_area, dx, dy);
6577   cairo_region_union (nocopy_area, region);
6578   cairo_region_subtract (nocopy_area, copy_area);
6579
6580   /* convert from window coords to impl */
6581   cairo_region_translate (copy_area, window->abs_x, window->abs_y);
6582   move_region_on_impl (impl_window, copy_area, dx, dy); /* Takes ownership of copy_area */
6583
6584   gdk_window_invalidate_region_full (window, nocopy_area, FALSE, CLEAR_BG_ALL);
6585   cairo_region_destroy (nocopy_area);
6586 }
6587
6588 /**
6589  * gdk_window_set_background:
6590  * @window: a #GdkWindow
6591  * @color: a #GdkColor
6592  *
6593  * Sets the background color of @window. (However, when using GTK+,
6594  * set the background of a widget with gtk_widget_modify_bg() - if
6595  * you're an application - or gtk_style_set_background() - if you're
6596  * implementing a custom widget.)
6597  *
6598  * See also gdk_window_set_background_pattern().
6599  *
6600  * Deprecated: 3.4: Use gdk_window_set_background_rgba() instead.
6601  */
6602 void
6603 gdk_window_set_background (GdkWindow      *window,
6604                            const GdkColor *color)
6605 {
6606   cairo_pattern_t *pattern;
6607
6608   g_return_if_fail (GDK_IS_WINDOW (window));
6609
6610   pattern = cairo_pattern_create_rgb (color->red   / 65535.,
6611                                       color->green / 65535.,
6612                                       color->blue  / 65535.);
6613
6614   gdk_window_set_background_pattern (window, pattern);
6615
6616   cairo_pattern_destroy (pattern);
6617 }
6618
6619 /**
6620  * gdk_window_set_background_rgba:
6621  * @window: a #GdkWindow
6622  * @rgba: a #GdkRGBA color
6623  *
6624  * Sets the background color of @window.
6625  *
6626  * See also gdk_window_set_background_pattern().
6627  **/
6628 void
6629 gdk_window_set_background_rgba (GdkWindow     *window,
6630                                 const GdkRGBA *rgba)
6631 {
6632   cairo_pattern_t *pattern;
6633
6634   g_return_if_fail (GDK_IS_WINDOW (window));
6635   g_return_if_fail (rgba != NULL);
6636
6637   pattern = cairo_pattern_create_rgba (rgba->red, rgba->green,
6638                                        rgba->blue, rgba->alpha);
6639
6640   gdk_window_set_background_pattern (window, pattern);
6641
6642   cairo_pattern_destroy (pattern);
6643 }
6644
6645
6646 /* Updates has_alpha_background recursively for all child windows
6647    that have parent-relative alpha */
6648 static void
6649 _gdk_window_propagate_has_alpha_background (GdkWindow *window)
6650 {
6651   GdkWindow *child;
6652   GList *l;
6653
6654   for (l = window->children; l; l = l->next)
6655     {
6656       child = l->data;
6657
6658       if (child->background == NULL &&
6659           child->has_alpha_background != window->has_alpha_background)
6660         {
6661           child->has_alpha_background = window->has_alpha_background;
6662           recompute_visible_regions (child, TRUE, FALSE);
6663           _gdk_window_propagate_has_alpha_background (child);
6664         }
6665     }
6666 }
6667
6668 /**
6669  * gdk_window_set_background_pattern:
6670  * @window: a #GdkWindow
6671  * @pattern: (allow-none): a pattern to use, or %NULL
6672  *
6673  * Sets the background of @window.
6674  *
6675  * A background of %NULL means that the window will inherit its
6676  * background form its parent window.
6677  *
6678  * The windowing system will normally fill a window with its background
6679  * when the window is obscured then exposed.
6680  */
6681 void
6682 gdk_window_set_background_pattern (GdkWindow *window,
6683                                    cairo_pattern_t *pattern)
6684 {
6685   gboolean has_alpha;
6686   cairo_pattern_type_t type;
6687   
6688   g_return_if_fail (GDK_IS_WINDOW (window));
6689
6690   if (window->input_only)
6691     return;
6692
6693   if (pattern)
6694     cairo_pattern_reference (pattern);
6695   if (window->background)
6696     cairo_pattern_destroy (window->background);
6697   window->background = pattern;
6698
6699   has_alpha = TRUE;
6700
6701   if (pattern == NULL)
6702     {
6703       /* parent-relative, copy has_alpha from parent */
6704       if (window->parent == NULL ||
6705           window->parent->window_type == GDK_WINDOW_ROOT)
6706         has_alpha = FALSE;
6707       else
6708         has_alpha = window->parent->has_alpha_background;
6709     }
6710   else
6711     {
6712       type = cairo_pattern_get_type (pattern);
6713
6714       if (type == CAIRO_PATTERN_TYPE_SOLID)
6715         {
6716           double alpha;
6717           cairo_pattern_get_rgba (pattern, NULL, NULL, NULL, &alpha);
6718           if (alpha == 1.0)
6719             has_alpha = FALSE;
6720         }
6721       else if (type == CAIRO_PATTERN_TYPE_LINEAR ||
6722                type == CAIRO_PATTERN_TYPE_RADIAL)
6723         {
6724           int i, n;
6725           double alpha;
6726
6727           n = 0;
6728           cairo_pattern_get_color_stop_count (pattern, &n);
6729           has_alpha = FALSE;
6730           for (i = 0; i < n; i++)
6731             {
6732               cairo_pattern_get_color_stop_rgba (pattern, i, NULL,
6733                                                  NULL, NULL, NULL, &alpha);
6734               if (alpha != 1.0)
6735                 {
6736                   has_alpha = TRUE;
6737                   break;
6738                 }
6739             }
6740         }
6741       else if (type == CAIRO_PATTERN_TYPE_SURFACE)
6742         {
6743           cairo_surface_t *surface;
6744           cairo_content_t content;
6745
6746           cairo_pattern_get_surface (pattern, &surface);
6747           content = cairo_surface_get_content (surface);
6748           has_alpha =
6749             (content == CAIRO_CONTENT_ALPHA) ||
6750             (content == CAIRO_CONTENT_COLOR_ALPHA);
6751         }
6752     }
6753
6754   if (has_alpha != window->has_alpha_background)
6755     {
6756       window->has_alpha_background = has_alpha;  
6757       recompute_visible_regions (window, TRUE, FALSE);
6758
6759       _gdk_window_propagate_has_alpha_background (window);
6760     }
6761
6762   if (gdk_window_has_impl (window))
6763     {
6764       GdkWindowImplClass *impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
6765       impl_class->set_background (window, pattern);
6766     }
6767   else
6768     gdk_window_invalidate_rect_full (window, NULL, TRUE, CLEAR_BG_ALL);
6769 }
6770
6771 /**
6772  * gdk_window_get_background_pattern:
6773  * @window: a window
6774  *
6775  * Gets the pattern used to clear the background on @window. If @window
6776  * does not have its own background and reuses the parent's, %NULL is
6777  * returned and you'll have to query it yourself.
6778  *
6779  * Returns: (transfer none): The pattern to use for the background or
6780  *     %NULL to use the parent's background.
6781  *
6782  * Since: 2.22
6783  **/
6784 cairo_pattern_t *
6785 gdk_window_get_background_pattern (GdkWindow *window)
6786 {
6787   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
6788
6789   return window->background;
6790 }
6791
6792 static void
6793 gdk_window_set_cursor_internal (GdkWindow *window,
6794                                 GdkDevice *device,
6795                                 GdkCursor *cursor)
6796 {
6797   if (GDK_WINDOW_DESTROYED (window))
6798     return;
6799
6800   if (window->window_type == GDK_WINDOW_ROOT ||
6801       window->window_type == GDK_WINDOW_FOREIGN)
6802     GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_device_cursor (window, device, cursor);
6803   else
6804     {
6805       GdkPointerWindowInfo *pointer_info;
6806       GdkDisplay *display;
6807
6808       display = gdk_window_get_display (window);
6809       pointer_info = _gdk_display_get_pointer_info (display, device);
6810
6811       if (_gdk_window_event_parent_of (window, pointer_info->window_under_pointer))
6812         update_cursor (display, device);
6813     }
6814 }
6815
6816 /**
6817  * gdk_window_get_cursor:
6818  * @window: a #GdkWindow
6819  *
6820  * Retrieves a #GdkCursor pointer for the cursor currently set on the
6821  * specified #GdkWindow, or %NULL.  If the return value is %NULL then
6822  * there is no custom cursor set on the specified window, and it is
6823  * using the cursor for its parent window.
6824  *
6825  * Return value: (transfer none): a #GdkCursor, or %NULL. The returned
6826  *   object is owned by the #GdkWindow and should not be unreferenced
6827  *   directly. Use gdk_window_set_cursor() to unset the cursor of the
6828  *   window
6829  *
6830  * Since: 2.18
6831  */
6832 GdkCursor *
6833 gdk_window_get_cursor (GdkWindow *window)
6834 {
6835   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
6836
6837   return window->cursor;
6838 }
6839
6840 /**
6841  * gdk_window_set_cursor:
6842  * @window: a #GdkWindow
6843  * @cursor: (allow-none): a cursor
6844  *
6845  * Sets the default mouse pointer for a #GdkWindow. Use gdk_cursor_new_for_display()
6846  * or gdk_cursor_new_from_pixbuf() to create the cursor. To make the cursor
6847  * invisible, use %GDK_BLANK_CURSOR. Passing %NULL for the @cursor argument
6848  * to gdk_window_set_cursor() means that @window will use the cursor of its
6849  * parent window. Most windows should use this default.
6850  */
6851 void
6852 gdk_window_set_cursor (GdkWindow *window,
6853                        GdkCursor *cursor)
6854 {
6855   GdkDisplay *display;
6856
6857   g_return_if_fail (GDK_IS_WINDOW (window));
6858
6859   display = gdk_window_get_display (window);
6860
6861   if (window->cursor)
6862     {
6863       g_object_unref (window->cursor);
6864       window->cursor = NULL;
6865     }
6866
6867   if (!GDK_WINDOW_DESTROYED (window))
6868     {
6869       GdkDeviceManager *device_manager;
6870       GList *devices, *d;
6871
6872       if (cursor)
6873         window->cursor = g_object_ref (cursor);
6874
6875       device_manager = gdk_display_get_device_manager (display);
6876       devices = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_MASTER);
6877
6878       for (d = devices; d; d = d->next)
6879         {
6880           GdkDevice *device;
6881
6882           device = d->data;
6883
6884           if (gdk_device_get_source (device) == GDK_SOURCE_KEYBOARD)
6885             continue;
6886
6887           gdk_window_set_cursor_internal (window, device, window->cursor);
6888         }
6889
6890       g_list_free (devices);
6891       g_object_notify (G_OBJECT (window), "cursor");
6892     }
6893 }
6894
6895 /**
6896  * gdk_window_get_device_cursor:
6897  * @window: a #GdkWindow.
6898  * @device: a master, pointer #GdkDevice.
6899  *
6900  * Retrieves a #GdkCursor pointer for the @device currently set on the
6901  * specified #GdkWindow, or %NULL.  If the return value is %NULL then
6902  * there is no custom cursor set on the specified window, and it is
6903  * using the cursor for its parent window.
6904  *
6905  * Returns: (transfer none): a #GdkCursor, or %NULL. The returned
6906  *   object is owned by the #GdkWindow and should not be unreferenced
6907  *   directly. Use gdk_window_set_cursor() to unset the cursor of the
6908  *   window
6909  *
6910  * Since: 3.0
6911  **/
6912 GdkCursor *
6913 gdk_window_get_device_cursor (GdkWindow *window,
6914                               GdkDevice *device)
6915 {
6916   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
6917   g_return_val_if_fail (GDK_IS_DEVICE (device), NULL);
6918   g_return_val_if_fail (gdk_device_get_source (device) != GDK_SOURCE_KEYBOARD, NULL);
6919   g_return_val_if_fail (gdk_device_get_device_type (device) == GDK_DEVICE_TYPE_MASTER, NULL);
6920
6921   return g_hash_table_lookup (window->device_cursor, device);
6922 }
6923
6924 /**
6925  * gdk_window_set_device_cursor:
6926  * @window: a #Gdkwindow
6927  * @device: a master, pointer #GdkDevice
6928  * @cursor: a #GdkCursor
6929  *
6930  * Sets a specific #GdkCursor for a given device when it gets inside @window.
6931  * Use gdk_cursor_new_for_display() or gdk_cursor_new_from_pixbuf() to create
6932  * the cursor. To make the cursor invisible, use %GDK_BLANK_CURSOR. Passing
6933  * %NULL for the @cursor argument to gdk_window_set_cursor() means that
6934  * @window will use the cursor of its parent window. Most windows should
6935  * use this default.
6936  *
6937  * Since: 3.0
6938  **/
6939 void
6940 gdk_window_set_device_cursor (GdkWindow *window,
6941                               GdkDevice *device,
6942                               GdkCursor *cursor)
6943 {
6944   g_return_if_fail (GDK_IS_WINDOW (window));
6945   g_return_if_fail (GDK_IS_DEVICE (device));
6946   g_return_if_fail (gdk_device_get_source (device) != GDK_SOURCE_KEYBOARD);
6947   g_return_if_fail (gdk_device_get_device_type (device) == GDK_DEVICE_TYPE_MASTER);
6948
6949   if (!cursor)
6950     g_hash_table_remove (window->device_cursor, device);
6951   else
6952     g_hash_table_replace (window->device_cursor, device, g_object_ref (cursor));
6953
6954   gdk_window_set_cursor_internal (window, device, cursor);
6955 }
6956
6957 /**
6958  * gdk_window_get_geometry:
6959  * @window: a #GdkWindow
6960  * @x: (out) (allow-none): return location for X coordinate of window (relative to its parent)
6961  * @y: (out) (allow-none): return location for Y coordinate of window (relative to its parent)
6962  * @width: (out) (allow-none): return location for width of window
6963  * @height: (out) (allow-none): return location for height of window
6964  *
6965  * Any of the return location arguments to this function may be %NULL,
6966  * if you aren't interested in getting the value of that field.
6967  *
6968  * The X and Y coordinates returned are relative to the parent window
6969  * of @window, which for toplevels usually means relative to the
6970  * window decorations (titlebar, etc.) rather than relative to the
6971  * root window (screen-size background window).
6972  *
6973  * On the X11 platform, the geometry is obtained from the X server,
6974  * so reflects the latest position of @window; this may be out-of-sync
6975  * with the position of @window delivered in the most-recently-processed
6976  * #GdkEventConfigure. gdk_window_get_position() in contrast gets the
6977  * position from the most recent configure event.
6978  *
6979  * <note>
6980  * If @window is not a toplevel, it is <emphasis>much</emphasis> better
6981  * to call gdk_window_get_position(), gdk_window_get_width() and
6982  * gdk_window_get_height() instead, because it avoids the roundtrip to
6983  * the X server and because these functions support the full 32-bit
6984  * coordinate space, whereas gdk_window_get_geometry() is restricted to
6985  * the 16-bit coordinates of X11.
6986  *</note>
6987  **/
6988 void
6989 gdk_window_get_geometry (GdkWindow *window,
6990                          gint      *x,
6991                          gint      *y,
6992                          gint      *width,
6993                          gint      *height)
6994 {
6995   GdkWindow *parent;
6996   GdkWindowImplClass *impl_class;
6997
6998   if (!window)
6999     {
7000       GDK_NOTE (MULTIHEAD,
7001                 g_message ("gdk_window_get_geometry(): Window needs "
7002                            "to be non-NULL to be multi head safe"));
7003       window = gdk_screen_get_root_window ((gdk_screen_get_default ()));
7004     }
7005
7006   g_return_if_fail (GDK_IS_WINDOW (window));
7007
7008   if (!GDK_WINDOW_DESTROYED (window))
7009     {
7010       if (gdk_window_has_impl (window))
7011         {
7012           impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
7013           impl_class->get_geometry (window, x, y,
7014                                     width, height);
7015           /* This reports the position wrt to the native parent, we need to convert
7016              it to be relative to the client side parent */
7017           parent = window->parent;
7018           if (parent && !gdk_window_has_impl (parent))
7019             {
7020               if (x)
7021                 *x -= parent->abs_x;
7022               if (y)
7023                 *y -= parent->abs_y;
7024             }
7025         }
7026       else
7027         {
7028           if (x)
7029             *x = window->x;
7030           if (y)
7031             *y = window->y;
7032           if (width)
7033             *width = window->width;
7034           if (height)
7035             *height = window->height;
7036         }
7037     }
7038 }
7039
7040 /**
7041  * gdk_window_get_width:
7042  * @window: a #GdkWindow
7043  *
7044  * Returns the width of the given @window.
7045  *
7046  * On the X11 platform the returned size is the size reported in the
7047  * most-recently-processed configure event, rather than the current
7048  * size on the X server.
7049  *
7050  * Returns: The width of @window
7051  *
7052  * Since: 2.24
7053  */
7054 int
7055 gdk_window_get_width (GdkWindow *window)
7056 {
7057   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
7058
7059   return window->width;
7060 }
7061
7062 /**
7063  * gdk_window_get_height:
7064  * @window: a #GdkWindow
7065  *
7066  * Returns the height of the given @window.
7067  *
7068  * On the X11 platform the returned size is the size reported in the
7069  * most-recently-processed configure event, rather than the current
7070  * size on the X server.
7071  *
7072  * Returns: The height of @window
7073  *
7074  * Since: 2.24
7075  */
7076 int
7077 gdk_window_get_height (GdkWindow *window)
7078 {
7079   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
7080
7081   return window->height;
7082 }
7083
7084 /**
7085  * gdk_window_get_origin:
7086  * @window: a #GdkWindow
7087  * @x: (out) (allow-none): return location for X coordinate
7088  * @y: (out) (allow-none): return location for Y coordinate
7089  *
7090  * Obtains the position of a window in root window coordinates.
7091  * (Compare with gdk_window_get_position() and
7092  * gdk_window_get_geometry() which return the position of a window
7093  * relative to its parent window.)
7094  *
7095  * Return value: not meaningful, ignore
7096  */
7097 gint
7098 gdk_window_get_origin (GdkWindow *window,
7099                        gint      *x,
7100                        gint      *y)
7101 {
7102   GdkWindowImplClass *impl_class;
7103
7104   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
7105
7106   if (GDK_WINDOW_DESTROYED (window))
7107     {
7108       if (x)
7109         *x = 0;
7110       if (y)
7111         *y = 0;
7112       return 0;
7113     }
7114
7115   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
7116   impl_class->get_root_coords (window,
7117                                window->abs_x,
7118                                window->abs_y,
7119                                x, y);
7120
7121   return TRUE;
7122 }
7123
7124 /**
7125  * gdk_window_get_root_coords:
7126  * @window: a #GdkWindow
7127  * @x: X coordinate in window
7128  * @y: Y coordinate in window
7129  * @root_x: (out): return location for X coordinate
7130  * @root_y: (out): return location for Y coordinate
7131  *
7132  * Obtains the position of a window position in root
7133  * window coordinates. This is similar to
7134  * gdk_window_get_origin() but allows you go pass
7135  * in any position in the window, not just the origin.
7136  *
7137  * Since: 2.18
7138  */
7139 void
7140 gdk_window_get_root_coords (GdkWindow *window,
7141                             gint       x,
7142                             gint       y,
7143                             gint      *root_x,
7144                             gint      *root_y)
7145 {
7146   GdkWindowImplClass *impl_class;
7147
7148   g_return_if_fail (GDK_IS_WINDOW (window));
7149
7150   if (GDK_WINDOW_DESTROYED (window))
7151     {
7152       *root_x = 0;
7153       *root_y = 0;
7154       return;
7155     }
7156   
7157   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
7158   impl_class->get_root_coords (window,
7159                                x + window->abs_x,
7160                                y + window->abs_y,
7161                                root_x, root_y);
7162 }
7163
7164 /**
7165  * gdk_window_coords_to_parent:
7166  * @window: a child window
7167  * @x: X coordinate in child's coordinate system
7168  * @y: Y coordinate in child's coordinate system
7169  * @parent_x: (out) (allow-none): return location for X coordinate
7170  * in parent's coordinate system, or %NULL
7171  * @parent_y: (out) (allow-none): return location for Y coordinate
7172  * in parent's coordinate system, or %NULL
7173  *
7174  * Transforms window coordinates from a child window to its parent
7175  * window, where the parent window is the normal parent as returned by
7176  * gdk_window_get_parent() for normal windows, and the window's
7177  * embedder as returned by gdk_offscreen_window_get_embedder() for
7178  * offscreen windows.
7179  *
7180  * For normal windows, calling this function is equivalent to adding
7181  * the return values of gdk_window_get_position() to the child coordinates.
7182  * For offscreen windows however (which can be arbitrarily transformed),
7183  * this function calls the GdkWindow::to-embedder: signal to translate
7184  * the coordinates.
7185  *
7186  * You should always use this function when writing generic code that
7187  * walks up a window hierarchy.
7188  *
7189  * See also: gdk_window_coords_from_parent()
7190  *
7191  * Since: 2.22
7192  **/
7193 void
7194 gdk_window_coords_to_parent (GdkWindow *window,
7195                              gdouble    x,
7196                              gdouble    y,
7197                              gdouble   *parent_x,
7198                              gdouble   *parent_y)
7199 {
7200   g_return_if_fail (GDK_IS_WINDOW (window));
7201
7202   if (gdk_window_is_offscreen (window))
7203     {
7204       gdouble px, py;
7205
7206       to_embedder (window, x, y, &px, &py);
7207
7208       if (parent_x)
7209         *parent_x = px;
7210
7211       if (parent_y)
7212         *parent_y = py;
7213     }
7214   else
7215     {
7216       if (parent_x)
7217         *parent_x = x + window->x;
7218
7219       if (parent_y)
7220         *parent_y = y + window->y;
7221     }
7222 }
7223
7224 /**
7225  * gdk_window_coords_from_parent:
7226  * @window: a child window
7227  * @parent_x: X coordinate in parent's coordinate system
7228  * @parent_y: Y coordinate in parent's coordinate system
7229  * @x: (out) (allow-none): return location for X coordinate in child's coordinate system
7230  * @y: (out) (allow-none): return location for Y coordinate in child's coordinate system
7231  *
7232  * Transforms window coordinates from a parent window to a child
7233  * window, where the parent window is the normal parent as returned by
7234  * gdk_window_get_parent() for normal windows, and the window's
7235  * embedder as returned by gdk_offscreen_window_get_embedder() for
7236  * offscreen windows.
7237  *
7238  * For normal windows, calling this function is equivalent to subtracting
7239  * the return values of gdk_window_get_position() from the parent coordinates.
7240  * For offscreen windows however (which can be arbitrarily transformed),
7241  * this function calls the GdkWindow::from-embedder: signal to translate
7242  * the coordinates.
7243  *
7244  * You should always use this function when writing generic code that
7245  * walks down a window hierarchy.
7246  *
7247  * See also: gdk_window_coords_to_parent()
7248  *
7249  * Since: 2.22
7250  **/
7251 void
7252 gdk_window_coords_from_parent (GdkWindow *window,
7253                                gdouble    parent_x,
7254                                gdouble    parent_y,
7255                                gdouble   *x,
7256                                gdouble   *y)
7257 {
7258   g_return_if_fail (GDK_IS_WINDOW (window));
7259
7260   if (gdk_window_is_offscreen (window))
7261     {
7262       gdouble cx, cy;
7263
7264       from_embedder (window, parent_x, parent_y, &cx, &cy);
7265
7266       if (x)
7267         *x = cx;
7268
7269       if (y)
7270         *y = cy;
7271     }
7272   else
7273     {
7274       if (x)
7275         *x = parent_x - window->x;
7276
7277       if (y)
7278         *y = parent_y - window->y;
7279     }
7280 }
7281
7282 /**
7283  * gdk_window_shape_combine_region:
7284  * @window: a #GdkWindow
7285  * @shape_region: (allow-none): region of window to be non-transparent
7286  * @offset_x: X position of @shape_region in @window coordinates
7287  * @offset_y: Y position of @shape_region in @window coordinates
7288  *
7289  * Makes pixels in @window outside @shape_region be transparent,
7290  * so that the window may be nonrectangular.
7291  *
7292  * If @shape_region is %NULL, the shape will be unset, so the whole
7293  * window will be opaque again. @offset_x and @offset_y are ignored
7294  * if @shape_region is %NULL.
7295  *
7296  * On the X11 platform, this uses an X server extension which is
7297  * widely available on most common platforms, but not available on
7298  * very old X servers, and occasionally the implementation will be
7299  * buggy. On servers without the shape extension, this function
7300  * will do nothing.
7301  *
7302  * This function works on both toplevel and child windows.
7303  */
7304 void
7305 gdk_window_shape_combine_region (GdkWindow       *window,
7306                                  const cairo_region_t *shape_region,
7307                                  gint             offset_x,
7308                                  gint             offset_y)
7309 {
7310   cairo_region_t *old_region, *new_region, *diff;
7311
7312   g_return_if_fail (GDK_IS_WINDOW (window));
7313
7314   if (GDK_WINDOW_DESTROYED (window))
7315     return;
7316
7317   if (!window->shape && shape_region == NULL)
7318     return;
7319
7320   window->shaped = (shape_region != NULL);
7321
7322   if (window->shape)
7323     cairo_region_destroy (window->shape);
7324
7325   old_region = NULL;
7326   if (GDK_WINDOW_IS_MAPPED (window))
7327     old_region = cairo_region_copy (window->clip_region);
7328
7329   if (shape_region)
7330     {
7331       window->shape = cairo_region_copy (shape_region);
7332       cairo_region_translate (window->shape, offset_x, offset_y);
7333     }
7334   else
7335     window->shape = NULL;
7336
7337   recompute_visible_regions (window, TRUE, FALSE);
7338
7339   if (gdk_window_has_impl (window) &&
7340       !should_apply_clip_as_shape (window))
7341     apply_shape (window, window->shape);
7342
7343   if (old_region)
7344     {
7345       new_region = cairo_region_copy (window->clip_region);
7346
7347       /* New area in the window, needs invalidation */
7348       diff = cairo_region_copy (new_region);
7349       cairo_region_subtract (diff, old_region);
7350
7351       gdk_window_invalidate_region_full (window, diff, TRUE, CLEAR_BG_ALL);
7352
7353       cairo_region_destroy (diff);
7354
7355       if (!gdk_window_is_toplevel (window))
7356         {
7357           /* New area in the non-root parent window, needs invalidation */
7358           diff = cairo_region_copy (old_region);
7359           cairo_region_subtract (diff, new_region);
7360
7361           /* Adjust region to parent window coords */
7362           cairo_region_translate (diff, window->x, window->y);
7363
7364           gdk_window_invalidate_region_full (window->parent, diff, TRUE, CLEAR_BG_ALL);
7365
7366           cairo_region_destroy (diff);
7367         }
7368
7369       cairo_region_destroy (new_region);
7370       cairo_region_destroy (old_region);
7371     }
7372 }
7373
7374 static void
7375 do_child_shapes (GdkWindow *window,
7376                  gboolean merge)
7377 {
7378   GdkRectangle r;
7379   cairo_region_t *region;
7380
7381   r.x = 0;
7382   r.y = 0;
7383   r.width = window->width;
7384   r.height = window->height;
7385
7386   region = cairo_region_create_rectangle (&r);
7387   remove_child_area (window, NULL, FALSE, region, NULL);
7388
7389   if (merge && window->shape)
7390     cairo_region_subtract (region, window->shape);
7391
7392   gdk_window_shape_combine_region (window, region, 0, 0);
7393 }
7394
7395 /**
7396  * gdk_window_set_child_shapes:
7397  * @window: a #GdkWindow
7398  *
7399  * Sets the shape mask of @window to the union of shape masks
7400  * for all children of @window, ignoring the shape mask of @window
7401  * itself. Contrast with gdk_window_merge_child_shapes() which includes
7402  * the shape mask of @window in the masks to be merged.
7403  **/
7404 void
7405 gdk_window_set_child_shapes (GdkWindow *window)
7406 {
7407   g_return_if_fail (GDK_IS_WINDOW (window));
7408
7409   do_child_shapes (window, FALSE);
7410 }
7411
7412 /**
7413  * gdk_window_merge_child_shapes:
7414  * @window: a #GdkWindow
7415  *
7416  * Merges the shape masks for any child windows into the
7417  * shape mask for @window. i.e. the union of all masks
7418  * for @window and its children will become the new mask
7419  * for @window. See gdk_window_shape_combine_region().
7420  *
7421  * This function is distinct from gdk_window_set_child_shapes()
7422  * because it includes @window's shape mask in the set of shapes to
7423  * be merged.
7424  */
7425 void
7426 gdk_window_merge_child_shapes (GdkWindow *window)
7427 {
7428   g_return_if_fail (GDK_IS_WINDOW (window));
7429
7430   do_child_shapes (window, TRUE);
7431 }
7432
7433 /**
7434  * gdk_window_input_shape_combine_region:
7435  * @window: a #GdkWindow
7436  * @shape_region: region of window to be non-transparent
7437  * @offset_x: X position of @shape_region in @window coordinates
7438  * @offset_y: Y position of @shape_region in @window coordinates
7439  *
7440  * Like gdk_window_shape_combine_region(), but the shape applies
7441  * only to event handling. Mouse events which happen while
7442  * the pointer position corresponds to an unset bit in the
7443  * mask will be passed on the window below @window.
7444  *
7445  * An input shape is typically used with RGBA windows.
7446  * The alpha channel of the window defines which pixels are
7447  * invisible and allows for nicely antialiased borders,
7448  * and the input shape controls where the window is
7449  * "clickable".
7450  *
7451  * On the X11 platform, this requires version 1.1 of the
7452  * shape extension.
7453  *
7454  * On the Win32 platform, this functionality is not present and the
7455  * function does nothing.
7456  *
7457  * Since: 2.10
7458  */
7459 void
7460 gdk_window_input_shape_combine_region (GdkWindow       *window,
7461                                        const cairo_region_t *shape_region,
7462                                        gint             offset_x,
7463                                        gint             offset_y)
7464 {
7465   GdkWindowImplClass *impl_class;
7466
7467   g_return_if_fail (GDK_IS_WINDOW (window));
7468
7469   if (GDK_WINDOW_DESTROYED (window))
7470     return;
7471
7472   if (window->input_shape)
7473     cairo_region_destroy (window->input_shape);
7474
7475   if (shape_region)
7476     {
7477       window->input_shape = cairo_region_copy (shape_region);
7478       cairo_region_translate (window->input_shape, offset_x, offset_y);
7479     }
7480   else
7481     window->input_shape = NULL;
7482
7483   if (gdk_window_has_impl (window))
7484     {
7485       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
7486       impl_class->input_shape_combine_region (window, window->input_shape, 0, 0);
7487     }
7488
7489   /* Pointer may have e.g. moved outside window due to the input mask change */
7490   _gdk_synthesize_crossing_events_for_geometry_change (window);
7491 }
7492
7493 static void
7494 do_child_input_shapes (GdkWindow *window,
7495                        gboolean merge)
7496 {
7497   GdkRectangle r;
7498   cairo_region_t *region;
7499
7500   r.x = 0;
7501   r.y = 0;
7502   r.width = window->width;
7503   r.height = window->height;
7504
7505   region = cairo_region_create_rectangle (&r);
7506   remove_child_area (window, NULL, TRUE, region, NULL);
7507
7508   if (merge && window->shape)
7509     cairo_region_subtract (region, window->shape);
7510   if (merge && window->input_shape)
7511     cairo_region_subtract (region, window->input_shape);
7512
7513   gdk_window_input_shape_combine_region (window, region, 0, 0);
7514 }
7515
7516
7517 /**
7518  * gdk_window_set_child_input_shapes:
7519  * @window: a #GdkWindow
7520  *
7521  * Sets the input shape mask of @window to the union of input shape masks
7522  * for all children of @window, ignoring the input shape mask of @window
7523  * itself. Contrast with gdk_window_merge_child_input_shapes() which includes
7524  * the input shape mask of @window in the masks to be merged.
7525  *
7526  * Since: 2.10
7527  **/
7528 void
7529 gdk_window_set_child_input_shapes (GdkWindow *window)
7530 {
7531   g_return_if_fail (GDK_IS_WINDOW (window));
7532
7533   do_child_input_shapes (window, FALSE);
7534 }
7535
7536 /**
7537  * gdk_window_merge_child_input_shapes:
7538  * @window: a #GdkWindow
7539  *
7540  * Merges the input shape masks for any child windows into the
7541  * input shape mask for @window. i.e. the union of all input masks
7542  * for @window and its children will become the new input mask
7543  * for @window. See gdk_window_input_shape_combine_region().
7544  *
7545  * This function is distinct from gdk_window_set_child_input_shapes()
7546  * because it includes @window's input shape mask in the set of
7547  * shapes to be merged.
7548  *
7549  * Since: 2.10
7550  **/
7551 void
7552 gdk_window_merge_child_input_shapes (GdkWindow *window)
7553 {
7554   g_return_if_fail (GDK_IS_WINDOW (window));
7555
7556   do_child_input_shapes (window, TRUE);
7557 }
7558
7559
7560 /**
7561  * gdk_window_set_static_gravities:
7562  * @window: a #GdkWindow
7563  * @use_static: %TRUE to turn on static gravity
7564  *
7565  * Set the bit gravity of the given window to static, and flag it so
7566  * all children get static subwindow gravity. This is used if you are
7567  * implementing scary features that involve deep knowledge of the
7568  * windowing system. Don't worry about it unless you have to.
7569  *
7570  * Return value: %TRUE if the server supports static gravity
7571  */
7572 gboolean
7573 gdk_window_set_static_gravities (GdkWindow *window,
7574                                  gboolean   use_static)
7575 {
7576   GdkWindowImplClass *impl_class;
7577
7578   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
7579
7580   if (gdk_window_has_impl (window))
7581     {
7582       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
7583       return impl_class->set_static_gravities (window, use_static);
7584     }
7585
7586   return FALSE;
7587 }
7588
7589 /**
7590  * gdk_window_get_composited:
7591  * @window: a #GdkWindow
7592  *
7593  * Determines whether @window is composited.
7594  *
7595  * See gdk_window_set_composited().
7596  *
7597  * Returns: %TRUE if the window is composited.
7598  *
7599  * Since: 2.22
7600  **/
7601 gboolean
7602 gdk_window_get_composited (GdkWindow *window)
7603 {
7604   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
7605
7606   return window->composited;
7607 }
7608
7609 /**
7610  * gdk_window_set_composited:
7611  * @window: a #GdkWindow
7612  * @composited: %TRUE to set the window as composited
7613  *
7614  * Sets a #GdkWindow as composited, or unsets it. Composited
7615  * windows do not automatically have their contents drawn to
7616  * the screen. Drawing is redirected to an offscreen buffer
7617  * and an expose event is emitted on the parent of the composited
7618  * window. It is the responsibility of the parent's expose handler
7619  * to manually merge the off-screen content onto the screen in
7620  * whatever way it sees fit. See <xref linkend="composited-window-example"/>
7621  * for an example.
7622  *
7623  * It only makes sense for child windows to be composited; see
7624  * gdk_window_set_opacity() if you need translucent toplevel
7625  * windows.
7626  *
7627  * An additional effect of this call is that the area of this
7628  * window is no longer clipped from regions marked for
7629  * invalidation on its parent. Draws done on the parent
7630  * window are also no longer clipped by the child.
7631  *
7632  * This call is only supported on some systems (currently,
7633  * only X11 with new enough Xcomposite and Xdamage extensions).
7634  * You must call gdk_display_supports_composite() to check if
7635  * setting a window as composited is supported before
7636  * attempting to do so.
7637  *
7638  * Since: 2.12
7639  */
7640 void
7641 gdk_window_set_composited (GdkWindow *window,
7642                            gboolean   composited)
7643 {
7644   GdkDisplay *display;
7645   GdkWindowImplClass *impl_class;
7646
7647   g_return_if_fail (GDK_IS_WINDOW (window));
7648
7649   composited = composited != FALSE;
7650
7651   if (window->composited == composited)
7652     return;
7653
7654   if (composited)
7655     gdk_window_ensure_native (window);
7656
7657   display = gdk_window_get_display (window);
7658
7659   impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
7660
7661   if (composited && (!gdk_display_supports_composite (display) || !impl_class->set_composited))
7662     {
7663       g_warning ("gdk_window_set_composited called but "
7664                  "compositing is not supported");
7665       return;
7666     }
7667
7668   impl_class->set_composited (window, composited);
7669
7670   recompute_visible_regions (window, TRUE, FALSE);
7671
7672   if (GDK_WINDOW_IS_MAPPED (window))
7673     gdk_window_invalidate_in_parent (window);
7674
7675   window->composited = composited;
7676 }
7677
7678 /**
7679  * gdk_window_get_modal_hint:
7680  * @window: A toplevel #GdkWindow.
7681  *
7682  * Determines whether or not the window manager is hinted that @window
7683  * has modal behaviour.
7684  *
7685  * Return value: whether or not the window has the modal hint set.
7686  *
7687  * Since: 2.22
7688  */
7689 gboolean
7690 gdk_window_get_modal_hint (GdkWindow *window)
7691 {
7692   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
7693
7694   return window->modal_hint;
7695 }
7696
7697 /**
7698  * gdk_window_get_accept_focus:
7699  * @window: a toplevel #GdkWindow.
7700  *
7701  * Determines whether or not the desktop environment shuld be hinted that
7702  * the window does not want to receive input focus.
7703  *
7704  * Return value: whether or not the window should receive input focus.
7705  *
7706  * Since: 2.22
7707  */
7708 gboolean
7709 gdk_window_get_accept_focus (GdkWindow *window)
7710 {
7711   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
7712
7713   return window->accept_focus;
7714 }
7715
7716 /**
7717  * gdk_window_get_focus_on_map:
7718  * @window: a toplevel #GdkWindow.
7719  *
7720  * Determines whether or not the desktop environment should be hinted that the
7721  * window does not want to receive input focus when it is mapped.
7722  *
7723  * Return value: whether or not the window wants to receive input focus when
7724  * it is mapped.
7725  *
7726  * Since: 2.22
7727  */
7728 gboolean
7729 gdk_window_get_focus_on_map (GdkWindow *window)
7730 {
7731   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
7732
7733   return window->focus_on_map;
7734 }
7735
7736 /**
7737  * gdk_window_is_input_only:
7738  * @window: a toplevel #GdkWindow
7739  *
7740  * Determines whether or not the window is an input only window.
7741  *
7742  * Return value: %TRUE if @window is input only
7743  *
7744  * Since: 2.22
7745  */
7746 gboolean
7747 gdk_window_is_input_only (GdkWindow *window)
7748 {
7749   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
7750
7751   return window->input_only;
7752 }
7753
7754 /**
7755  * gdk_window_is_shaped:
7756  * @window: a toplevel #GdkWindow
7757  *
7758  * Determines whether or not the window is shaped.
7759  *
7760  * Return value: %TRUE if @window is shaped
7761  *
7762  * Since: 2.22
7763  */
7764 gboolean
7765 gdk_window_is_shaped (GdkWindow *window)
7766 {
7767   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
7768
7769   return window->shaped;
7770 }
7771
7772 void
7773 _gdk_window_add_damage (GdkWindow *toplevel,
7774                         cairo_region_t *damaged_region)
7775 {
7776   GdkDisplay *display;
7777   GdkEvent event = { 0, };
7778   event.expose.type = GDK_DAMAGE;
7779   event.expose.window = toplevel;
7780   event.expose.send_event = FALSE;
7781   event.expose.region = damaged_region;
7782   cairo_region_get_extents (event.expose.region, &event.expose.area);
7783   display = gdk_window_get_display (event.expose.window);
7784   _gdk_event_queue_append (display, gdk_event_copy (&event));
7785 }
7786
7787 /* Gets the toplevel for a window as used for events,
7788    i.e. including offscreen parents */
7789 static GdkWindow *
7790 get_event_parent (GdkWindow *window)
7791 {
7792   if (gdk_window_is_offscreen (window))
7793     return gdk_offscreen_window_get_embedder ((GdkWindow *)window);
7794   else
7795     return window->parent;
7796 }
7797
7798 /* Gets the toplevel for a window as used for events,
7799    i.e. including offscreen parents going up to the native
7800    toplevel */
7801 static GdkWindow *
7802 get_event_toplevel (GdkWindow *window)
7803 {
7804   GdkWindow *parent;
7805
7806   while ((parent = get_event_parent (window)) != NULL &&
7807          (parent->window_type != GDK_WINDOW_ROOT))
7808     window = parent;
7809
7810   return window;
7811 }
7812
7813 gboolean
7814 _gdk_window_event_parent_of (GdkWindow *parent,
7815                              GdkWindow *child)
7816 {
7817   GdkWindow *w;
7818
7819   w = child;
7820   while (w != NULL)
7821     {
7822       if (w == parent)
7823         return TRUE;
7824
7825       w = get_event_parent (w);
7826     }
7827
7828   return FALSE;
7829 }
7830
7831 static void
7832 update_cursor (GdkDisplay *display,
7833                GdkDevice  *device)
7834 {
7835   GdkWindow *cursor_window, *parent, *toplevel;
7836   GdkWindow *pointer_window;
7837   GdkWindowImplClass *impl_class;
7838   GdkPointerWindowInfo *pointer_info;
7839   GdkDeviceGrabInfo *grab;
7840   GdkCursor *cursor;
7841
7842   pointer_info = _gdk_display_get_pointer_info (display, device);
7843   pointer_window = pointer_info->window_under_pointer;
7844
7845   /* We ignore the serials here and just pick the last grab
7846      we've sent, as that would shortly be used anyway. */
7847   grab = _gdk_display_get_last_device_grab (display, device);
7848   if (/* have grab */
7849       grab != NULL &&
7850       /* the pointer is not in a descendant of the grab window */
7851       !_gdk_window_event_parent_of (grab->window, pointer_window))
7852     {
7853       /* use the cursor from the grab window */
7854       cursor_window = grab->window;
7855     }
7856   else
7857     {
7858       /* otherwise use the cursor from the pointer window */
7859       cursor_window = pointer_window;
7860     }
7861
7862   /* Find the first window with the cursor actually set, as
7863      the cursor is inherited from the parent */
7864   while (cursor_window->cursor == NULL &&
7865          (parent = get_event_parent (cursor_window)) != NULL &&
7866          parent->window_type != GDK_WINDOW_ROOT)
7867     cursor_window = parent;
7868
7869   cursor = g_hash_table_lookup (cursor_window->device_cursor, device);
7870
7871   if (!cursor)
7872     cursor = cursor_window->cursor;
7873
7874   /* Set all cursors on toplevel, otherwise its tricky to keep track of
7875    * which native window has what cursor set. */
7876   toplevel = get_event_toplevel (pointer_window);
7877   impl_class = GDK_WINDOW_IMPL_GET_CLASS (toplevel->impl);
7878   impl_class->set_device_cursor (toplevel, device, cursor);
7879 }
7880
7881 static gboolean
7882 point_in_window (GdkWindow *window,
7883                  gdouble    x,
7884                  gdouble    y)
7885 {
7886   return
7887     x >= 0 && x < window->width &&
7888     y >= 0 && y < window->height &&
7889     (window->shape == NULL ||
7890      cairo_region_contains_point (window->shape,
7891                           x, y)) &&
7892     (window->input_shape == NULL ||
7893      cairo_region_contains_point (window->input_shape,
7894                           x, y));
7895 }
7896
7897 static GdkWindow *
7898 convert_native_coords_to_toplevel (GdkWindow *window,
7899                                    gdouble    child_x,
7900                                    gdouble    child_y,
7901                                    gdouble   *toplevel_x,
7902                                    gdouble   *toplevel_y)
7903 {
7904   gdouble x, y;
7905
7906   x = child_x;
7907   y = child_y;
7908
7909   while (!gdk_window_is_toplevel (window))
7910     {
7911       x += window->x;
7912       y += window->y;
7913       window = window->parent;
7914     }
7915
7916   *toplevel_x = x;
7917   *toplevel_y = y;
7918
7919   return window;
7920 }
7921
7922 static void
7923 convert_toplevel_coords_to_window (GdkWindow *window,
7924                                    gdouble    toplevel_x,
7925                                    gdouble    toplevel_y,
7926                                    gdouble   *window_x,
7927                                    gdouble   *window_y)
7928 {
7929   GdkWindow *parent;
7930   gdouble x, y;
7931   GList *children, *l;
7932
7933   x = toplevel_x;
7934   y = toplevel_y;
7935
7936   children = NULL;
7937   while ((parent = get_event_parent (window)) != NULL &&
7938          (parent->window_type != GDK_WINDOW_ROOT))
7939     {
7940       children = g_list_prepend (children, window);
7941       window = parent;
7942     }
7943
7944   for (l = children; l != NULL; l = l->next)
7945     gdk_window_coords_from_parent (l->data, x, y, &x, &y);
7946
7947   g_list_free (children);
7948
7949   *window_x = x;
7950   *window_y = y;
7951 }
7952
7953 static GdkWindow *
7954 pick_embedded_child (GdkWindow *window,
7955                      gdouble    x,
7956                      gdouble    y)
7957 {
7958   GdkWindow *res;
7959
7960   res = NULL;
7961   g_signal_emit (window,
7962                  signals[PICK_EMBEDDED_CHILD], 0,
7963                  x, y, &res);
7964
7965   return res;
7966 }
7967
7968 GdkWindow *
7969 _gdk_window_find_child_at (GdkWindow *window,
7970                            int        x,
7971                            int        y)
7972 {
7973   GdkWindow *sub;
7974   double child_x, child_y;
7975   GList *l;
7976
7977   if (point_in_window (window, x, y))
7978     {
7979       /* Children is ordered in reverse stack order, i.e. first is topmost */
7980       for (l = window->children; l != NULL; l = l->next)
7981         {
7982           sub = l->data;
7983
7984           if (!GDK_WINDOW_IS_MAPPED (sub))
7985             continue;
7986
7987           gdk_window_coords_from_parent ((GdkWindow *)sub,
7988                                          x, y,
7989                                          &child_x, &child_y);
7990           if (point_in_window (sub, child_x, child_y))
7991             return (GdkWindow *)sub;
7992         }
7993
7994       if (window->num_offscreen_children > 0)
7995         {
7996           sub = pick_embedded_child (window,
7997                                      x, y);
7998           if (sub)
7999             return (GdkWindow *)sub;
8000         }
8001     }
8002
8003   return NULL;
8004 }
8005
8006 GdkWindow *
8007 _gdk_window_find_descendant_at (GdkWindow *window,
8008                                 gdouble    x,
8009                                 gdouble    y,
8010                                 gdouble   *found_x,
8011                                 gdouble   *found_y)
8012 {
8013   GdkWindow *sub;
8014   gdouble child_x, child_y;
8015   GList *l;
8016   gboolean found;
8017
8018   if (point_in_window (window, x, y))
8019     {
8020       do
8021         {
8022           found = FALSE;
8023           /* Children is ordered in reverse stack order, i.e. first is topmost */
8024           for (l = window->children; l != NULL; l = l->next)
8025             {
8026               sub = l->data;
8027
8028               if (!GDK_WINDOW_IS_MAPPED (sub))
8029                 continue;
8030
8031               gdk_window_coords_from_parent ((GdkWindow *)sub,
8032                                              x, y,
8033                                              &child_x, &child_y);
8034               if (point_in_window (sub, child_x, child_y))
8035                 {
8036                   x = child_x;
8037                   y = child_y;
8038                   window = sub;
8039                   found = TRUE;
8040                   break;
8041                 }
8042             }
8043           if (!found &&
8044               window->num_offscreen_children > 0)
8045             {
8046               sub = pick_embedded_child (window,
8047                                          x, y);
8048               if (sub)
8049                 {
8050                   found = TRUE;
8051                   window = sub;
8052                   from_embedder (sub, x, y, &x, &y);
8053                 }
8054             }
8055         }
8056       while (found);
8057     }
8058   else
8059     {
8060       /* Not in window at all */
8061       window = NULL;
8062     }
8063
8064   if (found_x)
8065     *found_x = x;
8066   if (found_y)
8067     *found_y = y;
8068
8069   return window;
8070 }
8071
8072 /**
8073  * gdk_window_beep:
8074  * @window: a toplevel #GdkWindow
8075  *
8076  * Emits a short beep associated to @window in the appropriate
8077  * display, if supported. Otherwise, emits a short beep on
8078  * the display just as gdk_display_beep().
8079  *
8080  * Since: 2.12
8081  **/
8082 void
8083 gdk_window_beep (GdkWindow *window)
8084 {
8085   GdkDisplay *display;
8086   GdkWindow *toplevel;
8087
8088   g_return_if_fail (GDK_IS_WINDOW (window));
8089
8090   if (GDK_WINDOW_DESTROYED (window))
8091     return;
8092
8093   toplevel = get_event_toplevel (window);
8094   display = gdk_window_get_display (window);
8095
8096   if (toplevel)
8097     {
8098       if (GDK_WINDOW_IMPL_GET_CLASS (toplevel->impl)->beep (toplevel))
8099         return;
8100     }
8101   
8102   /* If windows fail to beep, we beep the display. */
8103   gdk_display_beep (display);
8104 }
8105
8106 /**
8107  * gdk_window_set_support_multidevice:
8108  * @window: a #GdkWindow.
8109  * @support_multidevice: %TRUE to enable multidevice support in @window.
8110  *
8111  * This function will enable multidevice features in @window.
8112  *
8113  * Multidevice aware windows will need to handle properly multiple,
8114  * per device enter/leave events, device grabs and grab ownerships.
8115  *
8116  * Since: 3.0
8117  **/
8118 void
8119 gdk_window_set_support_multidevice (GdkWindow *window,
8120                                     gboolean   support_multidevice)
8121 {
8122   g_return_if_fail (GDK_IS_WINDOW (window));
8123
8124   if (GDK_WINDOW_DESTROYED (window))
8125     return;
8126
8127   if (window->support_multidevice == support_multidevice)
8128     return;
8129
8130   window->support_multidevice = support_multidevice;
8131
8132   /* FIXME: What to do if called when some pointers are inside the window ? */
8133 }
8134
8135 /**
8136  * gdk_window_get_support_multidevice:
8137  * @window: a #GdkWindow.
8138  *
8139  * Returns %TRUE if the window is aware of the existence of multiple
8140  * devices.
8141  *
8142  * Returns: %TRUE if the window handles multidevice features.
8143  *
8144  * Since: 3.0
8145  **/
8146 gboolean
8147 gdk_window_get_support_multidevice (GdkWindow *window)
8148 {
8149   g_return_val_if_fail (GDK_IS_WINDOW (window), FALSE);
8150
8151   if (GDK_WINDOW_DESTROYED (window))
8152     return FALSE;
8153
8154   return window->support_multidevice;
8155 }
8156
8157 static const guint type_masks[] = {
8158   GDK_SUBSTRUCTURE_MASK, /* GDK_DELETE                 = 0  */
8159   GDK_STRUCTURE_MASK, /* GDK_DESTROY                   = 1  */
8160   GDK_EXPOSURE_MASK, /* GDK_EXPOSE                     = 2  */
8161   GDK_POINTER_MOTION_MASK, /* GDK_MOTION_NOTIFY        = 3  */
8162   GDK_BUTTON_PRESS_MASK, /* GDK_BUTTON_PRESS           = 4  */
8163   GDK_BUTTON_PRESS_MASK, /* GDK_2BUTTON_PRESS          = 5  */
8164   GDK_BUTTON_PRESS_MASK, /* GDK_3BUTTON_PRESS          = 6  */
8165   GDK_BUTTON_RELEASE_MASK, /* GDK_BUTTON_RELEASE       = 7  */
8166   GDK_KEY_PRESS_MASK, /* GDK_KEY_PRESS                 = 8  */
8167   GDK_KEY_RELEASE_MASK, /* GDK_KEY_RELEASE             = 9  */
8168   GDK_ENTER_NOTIFY_MASK, /* GDK_ENTER_NOTIFY           = 10 */
8169   GDK_LEAVE_NOTIFY_MASK, /* GDK_LEAVE_NOTIFY           = 11 */
8170   GDK_FOCUS_CHANGE_MASK, /* GDK_FOCUS_CHANGE           = 12 */
8171   GDK_STRUCTURE_MASK, /* GDK_CONFIGURE                 = 13 */
8172   GDK_VISIBILITY_NOTIFY_MASK, /* GDK_MAP               = 14 */
8173   GDK_VISIBILITY_NOTIFY_MASK, /* GDK_UNMAP             = 15 */
8174   GDK_PROPERTY_CHANGE_MASK, /* GDK_PROPERTY_NOTIFY     = 16 */
8175   GDK_PROPERTY_CHANGE_MASK, /* GDK_SELECTION_CLEAR     = 17 */
8176   GDK_PROPERTY_CHANGE_MASK, /* GDK_SELECTION_REQUEST   = 18 */
8177   GDK_PROPERTY_CHANGE_MASK, /* GDK_SELECTION_NOTIFY    = 19 */
8178   GDK_PROXIMITY_IN_MASK, /* GDK_PROXIMITY_IN           = 20 */
8179   GDK_PROXIMITY_OUT_MASK, /* GDK_PROXIMITY_OUT         = 21 */
8180   GDK_ALL_EVENTS_MASK, /* GDK_DRAG_ENTER               = 22 */
8181   GDK_ALL_EVENTS_MASK, /* GDK_DRAG_LEAVE               = 23 */
8182   GDK_ALL_EVENTS_MASK, /* GDK_DRAG_MOTION              = 24 */
8183   GDK_ALL_EVENTS_MASK, /* GDK_DRAG_STATUS              = 25 */
8184   GDK_ALL_EVENTS_MASK, /* GDK_DROP_START               = 26 */
8185   GDK_ALL_EVENTS_MASK, /* GDK_DROP_FINISHED            = 27 */
8186   GDK_ALL_EVENTS_MASK, /* GDK_CLIENT_EVENT             = 28 */
8187   GDK_VISIBILITY_NOTIFY_MASK, /* GDK_VISIBILITY_NOTIFY = 29 */
8188   GDK_EXPOSURE_MASK, /* GDK_NO_EXPOSE                  = 30 */
8189   GDK_SCROLL_MASK | GDK_SMOOTH_SCROLL_MASK,/* GDK_SCROLL= 31 */
8190   0, /* GDK_WINDOW_STATE = 32 */
8191   0, /* GDK_SETTING = 33 */
8192   0, /* GDK_OWNER_CHANGE = 34 */
8193   0, /* GDK_GRAB_BROKEN = 35 */
8194   0, /* GDK_DAMAGE = 36 */
8195   GDK_TOUCH_MASK, /* GDK_TOUCH_BEGIN = 37 */
8196   GDK_TOUCH_MASK, /* GDK_TOUCH_UPDATE = 38 */
8197   GDK_TOUCH_MASK, /* GDK_TOUCH_END = 39 */
8198   GDK_TOUCH_MASK /* GDK_TOUCH_CANCEL = 40 */
8199 };
8200 G_STATIC_ASSERT (G_N_ELEMENTS (type_masks) == GDK_EVENT_LAST);
8201
8202 /* send motion events if the right buttons are down */
8203 static guint
8204 update_evmask_for_button_motion (guint           evmask,
8205                                  GdkModifierType mask)
8206 {
8207   if (evmask & GDK_BUTTON_MOTION_MASK &&
8208       mask & (GDK_BUTTON1_MASK |
8209               GDK_BUTTON2_MASK |
8210               GDK_BUTTON3_MASK |
8211               GDK_BUTTON4_MASK |
8212               GDK_BUTTON5_MASK))
8213     evmask |= GDK_POINTER_MOTION_MASK;
8214
8215   if ((evmask & GDK_BUTTON1_MOTION_MASK && mask & GDK_BUTTON1_MASK) ||
8216       (evmask & GDK_BUTTON2_MOTION_MASK && mask & GDK_BUTTON2_MASK) ||
8217       (evmask & GDK_BUTTON3_MOTION_MASK && mask & GDK_BUTTON3_MASK))
8218     evmask |= GDK_POINTER_MOTION_MASK;
8219
8220   return evmask;
8221 }
8222
8223 static gboolean
8224 is_button_type (GdkEventType type)
8225 {
8226   return type == GDK_BUTTON_PRESS ||
8227          type == GDK_2BUTTON_PRESS ||
8228          type == GDK_3BUTTON_PRESS ||
8229          type == GDK_BUTTON_RELEASE ||
8230          type == GDK_TOUCH_BEGIN ||
8231          type == GDK_TOUCH_END ||
8232          type == GDK_SCROLL;
8233 }
8234
8235 static gboolean
8236 is_motion_type (GdkEventType type)
8237 {
8238   return type == GDK_MOTION_NOTIFY ||
8239          type == GDK_TOUCH_UPDATE ||
8240          type == GDK_ENTER_NOTIFY ||
8241          type == GDK_LEAVE_NOTIFY;
8242 }
8243
8244 static gboolean
8245 is_touch_type (GdkEventType type)
8246 {
8247   return type == GDK_TOUCH_BEGIN ||
8248          type == GDK_TOUCH_UPDATE ||
8249          type == GDK_TOUCH_END ||
8250          type == GDK_TOUCH_CANCEL;
8251 }
8252
8253 static GdkWindow *
8254 find_common_ancestor (GdkWindow *win1,
8255                       GdkWindow *win2)
8256 {
8257   GdkWindow *tmp;
8258   GList *path1 = NULL, *path2 = NULL;
8259   GList *list1, *list2;
8260
8261   tmp = win1;
8262   while (tmp != NULL && tmp->window_type != GDK_WINDOW_ROOT)
8263     {
8264       path1 = g_list_prepend (path1, tmp);
8265       tmp = get_event_parent (tmp);
8266     }
8267
8268   tmp = win2;
8269   while (tmp != NULL && tmp->window_type != GDK_WINDOW_ROOT)
8270     {
8271       path2 = g_list_prepend (path2, tmp);
8272       tmp = get_event_parent (tmp);
8273     }
8274
8275   list1 = path1;
8276   list2 = path2;
8277   tmp = NULL;
8278   while (list1 && list2 && (list1->data == list2->data))
8279     {
8280       tmp = list1->data;
8281       list1 = g_list_next (list1);
8282       list2 = g_list_next (list2);
8283     }
8284   g_list_free (path1);
8285   g_list_free (path2);
8286
8287   return tmp;
8288 }
8289
8290 GdkEvent *
8291 _gdk_make_event (GdkWindow    *window,
8292                  GdkEventType  type,
8293                  GdkEvent     *event_in_queue,
8294                  gboolean      before_event)
8295 {
8296   GdkEvent *event = gdk_event_new (type);
8297   guint32 the_time;
8298   GdkModifierType the_state;
8299
8300   the_time = gdk_event_get_time (event_in_queue);
8301   gdk_event_get_state (event_in_queue, &the_state);
8302
8303   event->any.window = g_object_ref (window);
8304   event->any.send_event = FALSE;
8305   if (event_in_queue && event_in_queue->any.send_event)
8306     event->any.send_event = TRUE;
8307
8308   switch (type)
8309     {
8310     case GDK_MOTION_NOTIFY:
8311       event->motion.time = the_time;
8312       event->motion.axes = NULL;
8313       event->motion.state = the_state;
8314       break;
8315
8316     case GDK_BUTTON_PRESS:
8317     case GDK_2BUTTON_PRESS:
8318     case GDK_3BUTTON_PRESS:
8319     case GDK_BUTTON_RELEASE:
8320       event->button.time = the_time;
8321       event->button.axes = NULL;
8322       event->button.state = the_state;
8323       break;
8324
8325     case GDK_TOUCH_BEGIN:
8326     case GDK_TOUCH_UPDATE:
8327     case GDK_TOUCH_END:
8328     case GDK_TOUCH_CANCEL:
8329       event->touch.time = the_time;
8330       event->touch.axes = NULL;
8331       event->touch.state = the_state;
8332       break;
8333
8334     case GDK_SCROLL:
8335       event->scroll.time = the_time;
8336       event->scroll.state = the_state;
8337       break;
8338
8339     case GDK_KEY_PRESS:
8340     case GDK_KEY_RELEASE:
8341       event->key.time = the_time;
8342       event->key.state = the_state;
8343       break;
8344
8345     case GDK_ENTER_NOTIFY:
8346     case GDK_LEAVE_NOTIFY:
8347       event->crossing.time = the_time;
8348       event->crossing.state = the_state;
8349       break;
8350
8351     case GDK_PROPERTY_NOTIFY:
8352       event->property.time = the_time;
8353       event->property.state = the_state;
8354       break;
8355
8356     case GDK_SELECTION_CLEAR:
8357     case GDK_SELECTION_REQUEST:
8358     case GDK_SELECTION_NOTIFY:
8359       event->selection.time = the_time;
8360       break;
8361
8362     case GDK_PROXIMITY_IN:
8363     case GDK_PROXIMITY_OUT:
8364       event->proximity.time = the_time;
8365       break;
8366
8367     case GDK_DRAG_ENTER:
8368     case GDK_DRAG_LEAVE:
8369     case GDK_DRAG_MOTION:
8370     case GDK_DRAG_STATUS:
8371     case GDK_DROP_START:
8372     case GDK_DROP_FINISHED:
8373       event->dnd.time = the_time;
8374       break;
8375
8376     case GDK_FOCUS_CHANGE:
8377     case GDK_CONFIGURE:
8378     case GDK_MAP:
8379     case GDK_UNMAP:
8380     case GDK_CLIENT_EVENT:
8381     case GDK_VISIBILITY_NOTIFY:
8382     case GDK_DELETE:
8383     case GDK_DESTROY:
8384     case GDK_EXPOSE:
8385     default:
8386       break;
8387     }
8388
8389   if (event_in_queue)
8390     {
8391     if (before_event)
8392       _gdk_event_queue_insert_before (gdk_window_get_display (window), event_in_queue, event);
8393     else
8394       _gdk_event_queue_insert_after (gdk_window_get_display (window), event_in_queue, event);
8395     }
8396   else
8397     _gdk_event_queue_append (gdk_window_get_display (window), event);
8398
8399   return event;
8400 }
8401
8402 static void
8403 send_crossing_event (GdkDisplay                 *display,
8404                      GdkWindow                  *toplevel,
8405                      GdkWindow                  *window,
8406                      GdkEventType                type,
8407                      GdkCrossingMode             mode,
8408                      GdkNotifyType               notify_type,
8409                      GdkWindow                  *subwindow,
8410                      GdkDevice                  *device,
8411                      GdkDevice                  *source_device,
8412                      gint                        toplevel_x,
8413                      gint                        toplevel_y,
8414                      GdkModifierType             mask,
8415                      guint32                     time_,
8416                      GdkEvent                   *event_in_queue,
8417                      gulong                      serial)
8418 {
8419   GdkEvent *event;
8420   guint32 window_event_mask, type_event_mask;
8421   GdkDeviceGrabInfo *grab;
8422   GdkTouchGrabInfo *touch_grab = NULL;
8423   GdkPointerWindowInfo *pointer_info;
8424   gboolean block_event = FALSE;
8425   GdkEventSequence *sequence;
8426
8427   grab = _gdk_display_has_device_grab (display, device, serial);
8428   pointer_info = _gdk_display_get_pointer_info (display, device);
8429
8430   sequence = gdk_event_get_event_sequence (event_in_queue);
8431   if (sequence)
8432     touch_grab = _gdk_display_has_touch_grab (display, device, sequence, serial);
8433
8434   if (touch_grab)
8435     {
8436       if (window != touch_grab->window)
8437         return;
8438
8439       window_event_mask = touch_grab->event_mask;
8440     }
8441   else if (grab != NULL &&
8442            !grab->owner_events)
8443     {
8444       /* !owner_event => only report events wrt grab window, ignore rest */
8445       if ((GdkWindow *)window != grab->window)
8446         return;
8447       window_event_mask = grab->event_mask;
8448     }
8449   else
8450     window_event_mask = window->event_mask;
8451
8452   if (type == GDK_ENTER_NOTIFY &&
8453       (pointer_info->need_touch_press_enter ||
8454        gdk_device_get_source (source_device) == GDK_SOURCE_TOUCHSCREEN) &&
8455       mode != GDK_CROSSING_TOUCH_BEGIN &&
8456       mode != GDK_CROSSING_TOUCH_END)
8457     {
8458       pointer_info->need_touch_press_enter = TRUE;
8459       block_event = TRUE;
8460     }
8461   else if (type == GDK_LEAVE_NOTIFY)
8462     {
8463       type_event_mask = GDK_LEAVE_NOTIFY_MASK;
8464       window->devices_inside = g_list_remove (window->devices_inside, device);
8465
8466       if (!window->support_multidevice && window->devices_inside)
8467         {
8468           /* Block leave events unless it's the last pointer */
8469           block_event = TRUE;
8470         }
8471     }
8472   else
8473     {
8474       type_event_mask = GDK_ENTER_NOTIFY_MASK;
8475
8476       if (!window->support_multidevice && window->devices_inside)
8477         {
8478           /* Only emit enter events for the first device */
8479           block_event = TRUE;
8480         }
8481
8482       if (gdk_device_get_device_type (device) == GDK_DEVICE_TYPE_MASTER &&
8483           gdk_device_get_mode (device) != GDK_MODE_DISABLED &&
8484           !g_list_find (window->devices_inside, device))
8485         window->devices_inside = g_list_prepend (window->devices_inside, device);
8486     }
8487
8488   if (block_event)
8489     return;
8490
8491   if (window_event_mask & type_event_mask)
8492     {
8493       event = _gdk_make_event ((GdkWindow *)window, type, event_in_queue, TRUE);
8494       gdk_event_set_device (event, device);
8495
8496       if (source_device)
8497         gdk_event_set_source_device (event, source_device);
8498
8499       event->crossing.time = time_;
8500       event->crossing.subwindow = subwindow;
8501       if (subwindow)
8502         g_object_ref (subwindow);
8503       convert_toplevel_coords_to_window ((GdkWindow *)window,
8504                                          toplevel_x, toplevel_y,
8505                                          &event->crossing.x, &event->crossing.y);
8506       event->crossing.x_root = toplevel_x + toplevel->x;
8507       event->crossing.y_root = toplevel_y + toplevel->y;
8508       event->crossing.mode = mode;
8509       event->crossing.detail = notify_type;
8510       event->crossing.focus = FALSE;
8511       event->crossing.state = mask;
8512     }
8513 }
8514
8515
8516 /* The coordinates are in the toplevel window that src/dest are in.
8517  * src and dest are always (if != NULL) in the same toplevel, as
8518  * we get a leave-notify and set the window_under_pointer to null
8519  * before crossing to another toplevel.
8520  */
8521 void
8522 _gdk_synthesize_crossing_events (GdkDisplay                 *display,
8523                                  GdkWindow                  *src,
8524                                  GdkWindow                  *dest,
8525                                  GdkDevice                  *device,
8526                                  GdkDevice                  *source_device,
8527                                  GdkCrossingMode             mode,
8528                                  gint                        toplevel_x,
8529                                  gint                        toplevel_y,
8530                                  GdkModifierType             mask,
8531                                  guint32                     time_,
8532                                  GdkEvent                   *event_in_queue,
8533                                  gulong                      serial,
8534                                  gboolean                    non_linear)
8535 {
8536   GdkWindow *c;
8537   GdkWindow *win, *last, *next;
8538   GList *path, *list;
8539   GdkWindow *a;
8540   GdkWindow *b;
8541   GdkWindow *toplevel;
8542   GdkNotifyType notify_type;
8543
8544   /* TODO: Don't send events to toplevel, as we get those from the windowing system */
8545
8546   a = src;
8547   b = dest;
8548   if (src == dest)
8549     return; /* No crossings generated between src and dest */
8550
8551   if (gdk_device_get_device_type (device) != GDK_DEVICE_TYPE_MASTER)
8552     {
8553       if (a && gdk_window_get_device_events (src, device) == 0)
8554         a = NULL;
8555
8556       if (b && gdk_window_get_device_events (dest, device) == 0)
8557         b = NULL;
8558     }
8559
8560   if (!a && !b)
8561     return;
8562
8563   c = find_common_ancestor (a, b);
8564
8565   non_linear |= (c != a) && (c != b);
8566
8567   if (a) /* There might not be a source (i.e. if no previous pointer_in_window) */
8568     {
8569       toplevel = gdk_window_get_toplevel (a);
8570
8571       /* Traverse up from a to (excluding) c sending leave events */
8572       if (non_linear)
8573         notify_type = GDK_NOTIFY_NONLINEAR;
8574       else if (c == a)
8575         notify_type = GDK_NOTIFY_INFERIOR;
8576       else
8577         notify_type = GDK_NOTIFY_ANCESTOR;
8578       send_crossing_event (display, toplevel,
8579                            a, GDK_LEAVE_NOTIFY,
8580                            mode,
8581                            notify_type,
8582                            NULL, device, source_device,
8583                            toplevel_x, toplevel_y,
8584                            mask, time_,
8585                            event_in_queue,
8586                            serial);
8587
8588       if (c != a)
8589         {
8590           if (non_linear)
8591             notify_type = GDK_NOTIFY_NONLINEAR_VIRTUAL;
8592           else
8593             notify_type = GDK_NOTIFY_VIRTUAL;
8594
8595           last = a;
8596           win = get_event_parent (a);
8597           while (win != c && win->window_type != GDK_WINDOW_ROOT)
8598             {
8599               send_crossing_event (display, toplevel,
8600                                    win, GDK_LEAVE_NOTIFY,
8601                                    mode,
8602                                    notify_type,
8603                                    (GdkWindow *)last,
8604                                    device, source_device,
8605                                    toplevel_x, toplevel_y,
8606                                    mask, time_,
8607                                    event_in_queue,
8608                                    serial);
8609
8610               last = win;
8611               win = get_event_parent (win);
8612             }
8613         }
8614     }
8615
8616   if (b) /* Might not be a dest, e.g. if we're moving out of the window */
8617     {
8618       toplevel = gdk_window_get_toplevel ((GdkWindow *)b);
8619
8620       /* Traverse down from c to b */
8621       if (c != b)
8622         {
8623           path = NULL;
8624           win = get_event_parent (b);
8625           while (win != c && win->window_type != GDK_WINDOW_ROOT)
8626             {
8627               path = g_list_prepend (path, win);
8628               win = get_event_parent (win);
8629             }
8630
8631           if (non_linear)
8632             notify_type = GDK_NOTIFY_NONLINEAR_VIRTUAL;
8633           else
8634             notify_type = GDK_NOTIFY_VIRTUAL;
8635
8636           list = path;
8637           while (list)
8638             {
8639               win = list->data;
8640               list = g_list_next (list);
8641               if (list)
8642                 next = list->data;
8643               else
8644                 next = b;
8645
8646               send_crossing_event (display, toplevel,
8647                                    win, GDK_ENTER_NOTIFY,
8648                                    mode,
8649                                    notify_type,
8650                                    (GdkWindow *)next,
8651                                    device, source_device,
8652                                    toplevel_x, toplevel_y,
8653                                    mask, time_,
8654                                    event_in_queue,
8655                                    serial);
8656             }
8657           g_list_free (path);
8658         }
8659
8660
8661       if (non_linear)
8662         notify_type = GDK_NOTIFY_NONLINEAR;
8663       else if (c == a)
8664         notify_type = GDK_NOTIFY_ANCESTOR;
8665       else
8666         notify_type = GDK_NOTIFY_INFERIOR;
8667
8668       send_crossing_event (display, toplevel,
8669                            b, GDK_ENTER_NOTIFY,
8670                            mode,
8671                            notify_type,
8672                            NULL,
8673                            device, source_device,
8674                            toplevel_x, toplevel_y,
8675                            mask, time_,
8676                            event_in_queue,
8677                            serial);
8678     }
8679 }
8680
8681 /* Returns the window inside the event window with the pointer in it
8682  * at the specified coordinates, or NULL if its not in any child of
8683  * the toplevel. It also takes into account !owner_events grabs.
8684  */
8685 static GdkWindow *
8686 get_pointer_window (GdkDisplay *display,
8687                     GdkWindow *event_window,
8688                     GdkDevice *device,
8689                     gdouble toplevel_x,
8690                     gdouble toplevel_y,
8691                     gulong serial)
8692 {
8693   GdkWindow *pointer_window;
8694   GdkDeviceGrabInfo *grab;
8695   GdkPointerWindowInfo *pointer_info;
8696
8697   pointer_info = _gdk_display_get_pointer_info (display, device);
8698
8699   if (event_window == pointer_info->toplevel_under_pointer)
8700     pointer_window =
8701       _gdk_window_find_descendant_at (event_window,
8702                                       toplevel_x, toplevel_y,
8703                                       NULL, NULL);
8704   else
8705     pointer_window = NULL;
8706
8707   grab = _gdk_display_has_device_grab (display, device, serial);
8708   if (grab != NULL &&
8709       !grab->owner_events &&
8710       pointer_window != grab->window)
8711     pointer_window = NULL;
8712
8713   return pointer_window;
8714 }
8715
8716 void
8717 _gdk_display_set_window_under_pointer (GdkDisplay *display,
8718                                        GdkDevice  *device,
8719                                        GdkWindow  *window)
8720 {
8721   GdkPointerWindowInfo *device_info;
8722
8723   device_info = _gdk_display_get_pointer_info (display, device);
8724
8725   if (device_info->window_under_pointer)
8726     g_object_unref (device_info->window_under_pointer);
8727   device_info->window_under_pointer = window;
8728
8729   if (window)
8730     {
8731       g_object_ref (window);
8732       update_cursor (display, device);
8733     }
8734
8735   _gdk_display_enable_motion_hints (display, device);
8736 }
8737
8738 /**
8739  * gdk_pointer_grab:
8740  * @window: the #GdkWindow which will own the grab (the grab window).
8741  * @owner_events: if %FALSE then all pointer events are reported with respect to
8742  *                @window and are only reported if selected by @event_mask. If %TRUE then pointer
8743  *                events for this application are reported as normal, but pointer events outside
8744  *                this application are reported with respect to @window and only if selected by
8745  *                @event_mask. In either mode, unreported events are discarded.
8746  * @event_mask: specifies the event mask, which is used in accordance with
8747  *              @owner_events. Note that only pointer events (i.e. button and motion events)
8748  *              may be selected.
8749  * @confine_to: (allow-none): If non-%NULL, the pointer will be confined to this
8750  *              window during the grab. If the pointer is outside @confine_to, it will
8751  *              automatically be moved to the closest edge of @confine_to and enter
8752  *              and leave events will be generated as necessary.
8753  * @cursor: (allow-none): the cursor to display while the grab is active. If this is %NULL then
8754  *          the normal cursors are used for @window and its descendants, and the cursor
8755  *          for @window is used for all other windows.
8756  * @time_: the timestamp of the event which led to this pointer grab. This usually
8757  *         comes from a #GdkEventButton struct, though %GDK_CURRENT_TIME can be used if
8758  *         the time isn't known.
8759  *
8760  * Grabs the pointer (usually a mouse) so that all events are passed to this
8761  * application until the pointer is ungrabbed with gdk_pointer_ungrab(), or
8762  * the grab window becomes unviewable.
8763  * This overrides any previous pointer grab by this client.
8764  *
8765  * Pointer grabs are used for operations which need complete control over mouse
8766  * events, even if the mouse leaves the application.
8767  * For example in GTK+ it is used for Drag and Drop, for dragging the handle in
8768  * the #GtkHPaned and #GtkVPaned widgets.
8769  *
8770  * Note that if the event mask of an X window has selected both button press and
8771  * button release events, then a button press event will cause an automatic
8772  * pointer grab until the button is released.
8773  * X does this automatically since most applications expect to receive button
8774  * press and release events in pairs.
8775  * It is equivalent to a pointer grab on the window with @owner_events set to
8776  * %TRUE.
8777  *
8778  * If you set up anything at the time you take the grab that needs to be cleaned
8779  * up when the grab ends, you should handle the #GdkEventGrabBroken events that
8780  * are emitted when the grab ends unvoluntarily.
8781  *
8782  * Returns: %GDK_GRAB_SUCCESS if the grab was successful.
8783  *
8784  * Deprecated: 3.0: Use gdk_device_grab() instead.
8785  **/
8786 GdkGrabStatus
8787 gdk_pointer_grab (GdkWindow *     window,
8788                   gboolean        owner_events,
8789                   GdkEventMask    event_mask,
8790                   GdkWindow *     confine_to,
8791                   GdkCursor *     cursor,
8792                   guint32         time)
8793 {
8794   GdkWindow *native;
8795   GdkDisplay *display;
8796   GdkDeviceManager *device_manager;
8797   GdkDevice *device;
8798   GdkGrabStatus res = 0;
8799   gulong serial;
8800   GList *devices, *dev;
8801
8802   g_return_val_if_fail (window != NULL, 0);
8803   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
8804   g_return_val_if_fail (confine_to == NULL || GDK_IS_WINDOW (confine_to), 0);
8805
8806   /* We need a native window for confine to to work, ensure we have one */
8807   if (confine_to)
8808     {
8809       if (!gdk_window_ensure_native (confine_to))
8810         {
8811           g_warning ("Can't confine to grabbed window, not native");
8812           confine_to = NULL;
8813         }
8814     }
8815
8816   /* Non-viewable client side window => fail */
8817   if (!_gdk_window_has_impl (window) &&
8818       !gdk_window_is_viewable (window))
8819     return GDK_GRAB_NOT_VIEWABLE;
8820
8821   native = gdk_window_get_toplevel (window);
8822   while (gdk_window_is_offscreen (native))
8823     {
8824       native = gdk_offscreen_window_get_embedder (native);
8825
8826       if (native == NULL ||
8827           (!_gdk_window_has_impl (native) &&
8828            !gdk_window_is_viewable (native)))
8829         return GDK_GRAB_NOT_VIEWABLE;
8830
8831       native = gdk_window_get_toplevel (native);
8832     }
8833
8834   display = gdk_window_get_display (window);
8835
8836   serial = _gdk_display_get_next_serial (display);
8837   device_manager = gdk_display_get_device_manager (display);
8838   devices = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_MASTER);
8839
8840   /* FIXME: Should this be generic to all backends? */
8841   /* FIXME: What happens with extended devices? */
8842   for (dev = devices; dev; dev = dev->next)
8843     {
8844       device = dev->data;
8845
8846       if (gdk_device_get_source (device) != GDK_SOURCE_MOUSE)
8847         continue;
8848
8849       res = GDK_DEVICE_GET_CLASS (device)->grab (device,
8850                                                  native,
8851                                                  owner_events,
8852                                                  get_native_grab_event_mask (event_mask),
8853                                                  confine_to,
8854                                                  cursor,
8855                                                  time);
8856
8857       if (res == GDK_GRAB_SUCCESS)
8858         _gdk_display_add_device_grab (display,
8859                                       device,
8860                                       window,
8861                                       native,
8862                                       GDK_OWNERSHIP_NONE,
8863                                       owner_events,
8864                                       event_mask,
8865                                       serial,
8866                                       time,
8867                                       FALSE);
8868     }
8869
8870   /* FIXME: handle errors when grabbing */
8871
8872   g_list_free (devices);
8873
8874   return res;
8875 }
8876
8877 /**
8878  * gdk_keyboard_grab:
8879  * @window: the #GdkWindow which will own the grab (the grab window).
8880  * @owner_events: if %FALSE then all keyboard events are reported with respect to
8881  *   @window. If %TRUE then keyboard events for this application are
8882  *   reported as normal, but keyboard events outside this application
8883  *   are reported with respect to @window. Both key press and key
8884  *   release events are always reported, independant of the event mask
8885  *   set by the application.
8886  * @time_: a timestamp from a #GdkEvent, or %GDK_CURRENT_TIME if no timestamp is
8887  *   available.
8888  *
8889  * Grabs the keyboard so that all events are passed to this
8890  * application until the keyboard is ungrabbed with gdk_keyboard_ungrab().
8891  * This overrides any previous keyboard grab by this client.
8892  *
8893  * If you set up anything at the time you take the grab that needs to be cleaned
8894  * up when the grab ends, you should handle the #GdkEventGrabBroken events that
8895  * are emitted when the grab ends unvoluntarily.
8896  *
8897  * Returns: %GDK_GRAB_SUCCESS if the grab was successful.
8898  *
8899  * Deprecated: 3.0: Use gdk_device_grab() instead.
8900  **/
8901 GdkGrabStatus
8902 gdk_keyboard_grab (GdkWindow *window,
8903                    gboolean   owner_events,
8904                    guint32    time)
8905 {
8906   GdkWindow *native;
8907   GdkDisplay *display;
8908   GdkDeviceManager *device_manager;
8909   GdkDevice *device;
8910   GdkGrabStatus res = 0;
8911   gulong serial;
8912   GList *devices, *dev;
8913
8914   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
8915
8916   /* Non-viewable client side window => fail */
8917   if (!_gdk_window_has_impl (window) &&
8918       !gdk_window_is_viewable (window))
8919     return GDK_GRAB_NOT_VIEWABLE;
8920
8921   native = gdk_window_get_toplevel (window);
8922
8923   while (gdk_window_is_offscreen (native))
8924     {
8925       native = gdk_offscreen_window_get_embedder (native);
8926
8927       if (native == NULL ||
8928           (!_gdk_window_has_impl (native) &&
8929            !gdk_window_is_viewable (native)))
8930         return GDK_GRAB_NOT_VIEWABLE;
8931
8932       native = gdk_window_get_toplevel (native);
8933     }
8934
8935   display = gdk_window_get_display (window);
8936   serial = _gdk_display_get_next_serial (display);
8937   device_manager = gdk_display_get_device_manager (display);
8938   devices = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_MASTER);
8939
8940   /* FIXME: Should this be generic to all backends? */
8941   /* FIXME: What happens with extended devices? */
8942   for (dev = devices; dev; dev = dev->next)
8943     {
8944       device = dev->data;
8945
8946       if (gdk_device_get_source (device) != GDK_SOURCE_KEYBOARD)
8947         continue;
8948
8949       res = GDK_DEVICE_GET_CLASS (device)->grab (device,
8950                                                  native,
8951                                                  owner_events,
8952                                                  GDK_KEY_PRESS_MASK | GDK_KEY_RELEASE_MASK,
8953                                                  NULL,
8954                                                  NULL,
8955                                                  time);
8956
8957       if (res == GDK_GRAB_SUCCESS)
8958         _gdk_display_add_device_grab (display,
8959                                       device,
8960                                       window,
8961                                       native,
8962                                       GDK_OWNERSHIP_NONE,
8963                                       owner_events, 0,
8964                                       serial,
8965                                       time,
8966                                       FALSE);
8967     }
8968
8969   /* FIXME: handle errors when grabbing */
8970
8971   g_list_free (devices);
8972
8973   return res;
8974 }
8975
8976 /**
8977  * gdk_window_geometry_changed:
8978  * @window: an embedded offscreen #GdkWindow
8979  *
8980  * This function informs GDK that the geometry of an embedded
8981  * offscreen window has changed. This is necessary for GDK to keep
8982  * track of which offscreen window the pointer is in.
8983  *
8984  * Since: 2.18
8985  */
8986 void
8987 gdk_window_geometry_changed (GdkWindow *window)
8988 {
8989   _gdk_synthesize_crossing_events_for_geometry_change (window);
8990 }
8991
8992 static void
8993 source_events_device_added (GdkDeviceManager *device_manager,
8994                             GdkDevice        *device,
8995                             gpointer          user_data)
8996 {
8997   GdkWindow *window;
8998   GdkEventMask event_mask;
8999   GdkInputSource source;
9000
9001   if (gdk_device_get_device_type (device) != GDK_DEVICE_TYPE_FLOATING)
9002     return;
9003
9004   window = user_data;
9005   source = gdk_device_get_source (device);
9006
9007   event_mask = GPOINTER_TO_INT (g_hash_table_lookup (window->source_event_masks,
9008                                                      GINT_TO_POINTER (source)));
9009   if (event_mask)
9010     gdk_window_set_device_events (window, device, event_mask);
9011 }
9012
9013 static void
9014 source_events_device_changed (GdkDeviceManager *device_manager,
9015                               GdkDevice        *device,
9016                               gpointer          user_data)
9017 {
9018   GdkDeviceType type;
9019   GdkInputSource source;
9020   GdkEventMask event_mask;
9021   GdkWindow *window;
9022
9023   window = user_data;
9024   type = gdk_device_get_device_type (device);
9025   source = gdk_device_get_source (device);
9026
9027   event_mask = GPOINTER_TO_INT (g_hash_table_lookup (window->source_event_masks,
9028                                                      GINT_TO_POINTER (source)));
9029
9030   if (!event_mask)
9031     return;
9032
9033   if (type == GDK_DEVICE_TYPE_FLOATING)
9034     {
9035       /* The device was just floated, enable its event mask */
9036       gdk_window_set_device_events (window, device, event_mask);
9037     }
9038   else if (type == GDK_DEVICE_TYPE_SLAVE)
9039     gdk_window_set_device_events (window, device, 0);
9040 }
9041
9042 /**
9043  * gdk_window_set_source_events:
9044  * @window: a #GdkWindow
9045  * @source: a #GdkInputSource to define the source class.
9046  * @event_mask: event mask for @window
9047  *
9048  * Sets the event mask for any floating device (i.e. not attached to any
9049  * visible pointer) that has the source defined as @source. This event
9050  * mask will be applied both to currently existing, newly added devices
9051  * after this call, and devices being attached/detached.
9052  *
9053  * Since: 3.0
9054  **/
9055 void
9056 gdk_window_set_source_events (GdkWindow      *window,
9057                               GdkInputSource  source,
9058                               GdkEventMask    event_mask)
9059 {
9060   GdkDeviceManager *device_manager;
9061   GdkDisplay *display;
9062   GList *devices, *d;
9063   guint size;
9064
9065   g_return_if_fail (GDK_IS_WINDOW (window));
9066
9067   display = gdk_window_get_display (window);
9068   device_manager = gdk_display_get_device_manager (display);
9069
9070   devices = gdk_device_manager_list_devices (device_manager, GDK_DEVICE_TYPE_FLOATING);
9071
9072   /* Set event mask for existing devices */
9073   for (d = devices; d; d = d->next)
9074     {
9075       GdkDevice *device = d->data;
9076
9077       if (source == gdk_device_get_source (device))
9078         gdk_window_set_device_events (window, device, event_mask);
9079     }
9080
9081   g_list_free (devices);
9082
9083   /* Update accounting */
9084   if (G_UNLIKELY (!window->source_event_masks))
9085     window->source_event_masks = g_hash_table_new (NULL, NULL);
9086
9087   if (event_mask)
9088     g_hash_table_insert (window->source_event_masks,
9089                          GUINT_TO_POINTER (source),
9090                          GUINT_TO_POINTER (event_mask));
9091   else
9092     g_hash_table_remove (window->source_event_masks,
9093                          GUINT_TO_POINTER (source));
9094
9095   size = g_hash_table_size (window->source_event_masks);
9096
9097   /* Update handler if needed */
9098   if (!window->device_added_handler_id && size > 0)
9099     {
9100       window->device_added_handler_id =
9101         g_signal_connect (device_manager, "device-added",
9102                           G_CALLBACK (source_events_device_added), window);
9103       window->device_changed_handler_id =
9104         g_signal_connect (device_manager, "device-changed",
9105                           G_CALLBACK (source_events_device_changed), window);
9106     }
9107   else if (window->device_added_handler_id && size == 0)
9108     g_signal_handler_disconnect (device_manager, window->device_added_handler_id);
9109 }
9110
9111 /**
9112  * gdk_window_get_source_events:
9113  * @window: a #GdkWindow
9114  * @source: a #GdkInputSource to define the source class.
9115  *
9116  * Returns the event mask for @window corresponding to the device class specified
9117  * by @source.
9118  *
9119  * Returns: source event mask for @window
9120  **/
9121 GdkEventMask
9122 gdk_window_get_source_events (GdkWindow      *window,
9123                               GdkInputSource  source)
9124 {
9125   g_return_val_if_fail (GDK_IS_WINDOW (window), 0);
9126
9127   return GPOINTER_TO_UINT (g_hash_table_lookup (window->source_event_masks,
9128                                                 GUINT_TO_POINTER (source)));
9129 }
9130
9131 static gboolean
9132 do_synthesize_crossing_event (gpointer data)
9133 {
9134   GdkDisplay *display;
9135   GdkWindow *changed_toplevel;
9136   GHashTableIter iter;
9137   gpointer key, value;
9138   gulong serial;
9139
9140   changed_toplevel = data;
9141
9142   changed_toplevel->synthesize_crossing_event_queued = FALSE;
9143
9144   if (GDK_WINDOW_DESTROYED (changed_toplevel))
9145     return FALSE;
9146
9147   display = gdk_window_get_display (changed_toplevel);
9148   serial = _gdk_display_get_next_serial (display);
9149   g_hash_table_iter_init (&iter, display->pointers_info);
9150
9151   while (g_hash_table_iter_next (&iter, &key, &value))
9152     {
9153       GdkWindow *new_window_under_pointer;
9154       GdkPointerWindowInfo *pointer_info = value;
9155       GdkDevice *device = key;
9156
9157       if (changed_toplevel == pointer_info->toplevel_under_pointer)
9158         {
9159           new_window_under_pointer =
9160             get_pointer_window (display, changed_toplevel,
9161                                 device,
9162                                 pointer_info->toplevel_x,
9163                                 pointer_info->toplevel_y,
9164                                 serial);
9165           if (new_window_under_pointer != pointer_info->window_under_pointer)
9166             {
9167               _gdk_synthesize_crossing_events (display,
9168                                                pointer_info->window_under_pointer,
9169                                                new_window_under_pointer,
9170                                                device, pointer_info->last_slave,
9171                                                GDK_CROSSING_NORMAL,
9172                                                pointer_info->toplevel_x,
9173                                                pointer_info->toplevel_y,
9174                                                pointer_info->state,
9175                                                GDK_CURRENT_TIME,
9176                                                NULL,
9177                                                serial,
9178                                                FALSE);
9179               _gdk_display_set_window_under_pointer (display, device, new_window_under_pointer);
9180             }
9181         }
9182     }
9183
9184   return FALSE;
9185 }
9186
9187 void
9188 _gdk_synthesize_crossing_events_for_geometry_change (GdkWindow *changed_window)
9189 {
9190   GdkWindow *toplevel;
9191
9192   toplevel = get_event_toplevel (changed_window);
9193
9194   if (!toplevel->synthesize_crossing_event_queued)
9195     {
9196       toplevel->synthesize_crossing_event_queued = TRUE;
9197
9198       gdk_threads_add_idle_full (GDK_PRIORITY_EVENTS - 1,
9199                                  do_synthesize_crossing_event,
9200                                  g_object_ref (toplevel),
9201                                  g_object_unref);
9202     }
9203 }
9204
9205 /* Don't use for crossing events */
9206 static GdkWindow *
9207 get_event_window (GdkDisplay                 *display,
9208                   GdkDevice                  *device,
9209                   GdkEventSequence           *sequence,
9210                   GdkWindow                  *pointer_window,
9211                   GdkEventType                type,
9212                   GdkModifierType             mask,
9213                   guint                      *evmask_out,
9214                   gboolean                    pointer_emulated,
9215                   gulong                      serial)
9216 {
9217   guint evmask, emulated_mask = 0;
9218   GdkWindow *grab_window;
9219   GdkDeviceGrabInfo *grab;
9220   GdkTouchGrabInfo *touch_grab;
9221
9222   touch_grab = _gdk_display_has_touch_grab (display, device, sequence, serial);
9223   grab = _gdk_display_get_last_device_grab (display, device);
9224
9225   if (is_touch_type (type) && pointer_emulated)
9226     {
9227       switch (type)
9228         {
9229         case GDK_TOUCH_BEGIN:
9230           emulated_mask |= GDK_BUTTON_PRESS_MASK;
9231           break;
9232         case GDK_TOUCH_UPDATE:
9233           emulated_mask |= GDK_POINTER_MOTION_MASK;
9234           break;
9235         case GDK_TOUCH_END:
9236           emulated_mask |= GDK_BUTTON_RELEASE_MASK;
9237         default:
9238           break;
9239         }
9240     }
9241
9242   if (touch_grab != NULL &&
9243       (!grab || grab->implicit || touch_grab->serial >= grab->serial_start))
9244     {
9245       evmask = touch_grab->event_mask;
9246       evmask = update_evmask_for_button_motion (evmask, mask);
9247
9248       if (evmask & (type_masks[type] | emulated_mask))
9249         {
9250           if (evmask_out)
9251             *evmask_out = evmask;
9252           return touch_grab->window;
9253         }
9254       else
9255         return NULL;
9256     }
9257
9258   if (grab != NULL && !grab->owner_events)
9259     {
9260       evmask = grab->event_mask;
9261       evmask = update_evmask_for_button_motion (evmask, mask);
9262
9263       grab_window = grab->window;
9264
9265       if (evmask & (type_masks[type] | emulated_mask))
9266         {
9267           if (evmask_out)
9268             *evmask_out = evmask;
9269           return grab_window;
9270         }
9271       else
9272         return NULL;
9273     }
9274
9275   while (pointer_window != NULL)
9276     {
9277       evmask = pointer_window->event_mask;
9278       evmask = update_evmask_for_button_motion (evmask, mask);
9279
9280       if (evmask & (type_masks[type] | emulated_mask))
9281         {
9282           if (evmask_out)
9283             *evmask_out = evmask;
9284           return pointer_window;
9285         }
9286
9287       pointer_window = get_event_parent (pointer_window);
9288     }
9289
9290   if (grab != NULL &&
9291       grab->owner_events)
9292     {
9293       evmask = grab->event_mask;
9294       evmask = update_evmask_for_button_motion (evmask, mask);
9295
9296       if (evmask & (type_masks[type] | emulated_mask))
9297         {
9298           if (evmask_out)
9299             *evmask_out = evmask;
9300           return grab->window;
9301         }
9302       else
9303         return NULL;
9304     }
9305
9306   return NULL;
9307 }
9308
9309 static gboolean
9310 proxy_pointer_event (GdkDisplay                 *display,
9311                      GdkEvent                   *source_event,
9312                      gulong                      serial)
9313 {
9314   GdkWindow *toplevel_window, *event_window;
9315   GdkWindow *pointer_window;
9316   GdkPointerWindowInfo *pointer_info;
9317   GdkDevice *device, *source_device;
9318   GdkEvent *event;
9319   guint state;
9320   gdouble toplevel_x, toplevel_y;
9321   guint32 time_;
9322   gboolean non_linear, need_synthetic_enter = FALSE;
9323   gint event_type;
9324
9325   event_type = source_event->type;
9326   event_window = source_event->any.window;
9327   gdk_event_get_coords (source_event, &toplevel_x, &toplevel_y);
9328   gdk_event_get_state (source_event, &state);
9329   time_ = gdk_event_get_time (source_event);
9330   device = gdk_event_get_device (source_event);
9331   source_device = gdk_event_get_source_device (source_event);
9332   pointer_info = _gdk_display_get_pointer_info (display, device);
9333   toplevel_window = convert_native_coords_to_toplevel (event_window,
9334                                                        toplevel_x, toplevel_y,
9335                                                        &toplevel_x, &toplevel_y);
9336
9337   non_linear = FALSE;
9338   if ((source_event->type == GDK_LEAVE_NOTIFY ||
9339        source_event->type == GDK_ENTER_NOTIFY) &&
9340       (source_event->crossing.detail == GDK_NOTIFY_NONLINEAR ||
9341        source_event->crossing.detail == GDK_NOTIFY_NONLINEAR_VIRTUAL))
9342     non_linear = TRUE;
9343
9344   if (pointer_info->need_touch_press_enter &&
9345       gdk_device_get_source (pointer_info->last_slave) != GDK_SOURCE_TOUCHSCREEN &&
9346       (source_event->type != GDK_TOUCH_UPDATE ||
9347        _gdk_event_get_pointer_emulated (source_event)))
9348     {
9349       pointer_info->need_touch_press_enter = FALSE;
9350       need_synthetic_enter = TRUE;
9351     }
9352
9353   /* If we get crossing events with subwindow unexpectedly being NULL
9354      that means there is a native subwindow that gdk doesn't know about.
9355      We track these and forward them, with the correct virtual window
9356      events inbetween.
9357      This is important to get right, as metacity uses gdk for the frame
9358      windows, but gdk doesn't know about the client windows reparented
9359      into the frame. */
9360   if (((source_event->type == GDK_LEAVE_NOTIFY &&
9361         source_event->crossing.detail == GDK_NOTIFY_INFERIOR) ||
9362        (source_event->type == GDK_ENTER_NOTIFY &&
9363         (source_event->crossing.detail == GDK_NOTIFY_VIRTUAL ||
9364          source_event->crossing.detail == GDK_NOTIFY_NONLINEAR_VIRTUAL))) &&
9365       source_event->crossing.subwindow == NULL)
9366     {
9367       /* Left for an unknown (to gdk) subwindow */
9368
9369       /* Send leave events from window under pointer to event window
9370          that will get the subwindow == NULL window */
9371       _gdk_synthesize_crossing_events (display,
9372                                        pointer_info->window_under_pointer,
9373                                        event_window,
9374                                        device, source_device,
9375                                        source_event->crossing.mode,
9376                                        toplevel_x, toplevel_y,
9377                                        state, time_,
9378                                        source_event,
9379                                        serial,
9380                                        non_linear);
9381
9382       /* Send subwindow == NULL event */
9383       send_crossing_event (display,
9384                            toplevel_window,
9385                            event_window,
9386                            source_event->type,
9387                            source_event->crossing.mode,
9388                            source_event->crossing.detail,
9389                            NULL,
9390                            device, source_device,
9391                            toplevel_x, toplevel_y,
9392                            state, time_,
9393                            source_event,
9394                            serial);
9395
9396       _gdk_display_set_window_under_pointer (display, device, NULL);
9397       return TRUE;
9398     }
9399
9400   pointer_window = get_pointer_window (display, toplevel_window, device,
9401                                        toplevel_x, toplevel_y, serial);
9402
9403   if (((source_event->type == GDK_ENTER_NOTIFY &&
9404         source_event->crossing.detail == GDK_NOTIFY_INFERIOR) ||
9405        (source_event->type == GDK_LEAVE_NOTIFY &&
9406         (source_event->crossing.detail == GDK_NOTIFY_VIRTUAL ||
9407          source_event->crossing.detail == GDK_NOTIFY_NONLINEAR_VIRTUAL))) &&
9408       source_event->crossing.subwindow == NULL)
9409     {
9410       /* Entered from an unknown (to gdk) subwindow */
9411
9412       /* Send subwindow == NULL event */
9413       send_crossing_event (display,
9414                            toplevel_window,
9415                            event_window,
9416                            source_event->type,
9417                            source_event->crossing.mode,
9418                            source_event->crossing.detail,
9419                            NULL,
9420                            device, source_device,
9421                            toplevel_x, toplevel_y,
9422                            state, time_,
9423                            source_event,
9424                            serial);
9425
9426       /* Send enter events from event window to pointer_window */
9427       _gdk_synthesize_crossing_events (display,
9428                                        event_window,
9429                                        pointer_window,
9430                                        device, source_device,
9431                                        source_event->crossing.mode,
9432                                        toplevel_x, toplevel_y,
9433                                        state, time_,
9434                                        source_event,
9435                                        serial, non_linear);
9436       _gdk_display_set_window_under_pointer (display, device, pointer_window);
9437       return TRUE;
9438     }
9439
9440   if ((source_event->type != GDK_TOUCH_UPDATE ||
9441        _gdk_event_get_pointer_emulated (source_event)) &&
9442       pointer_info->window_under_pointer != pointer_window)
9443     {
9444       /* Either a toplevel crossing notify that ended up inside a child window,
9445          or a motion notify that got into another child window  */
9446
9447       /* Different than last time, send crossing events */
9448       _gdk_synthesize_crossing_events (display,
9449                                        pointer_info->window_under_pointer,
9450                                        pointer_window,
9451                                        device, source_device,
9452                                        GDK_CROSSING_NORMAL,
9453                                        toplevel_x, toplevel_y,
9454                                        state, time_,
9455                                        source_event,
9456                                        serial, non_linear);
9457       _gdk_display_set_window_under_pointer (display, device, pointer_window);
9458     }
9459   else if (source_event->type == GDK_MOTION_NOTIFY ||
9460            source_event->type == GDK_TOUCH_UPDATE)
9461     {
9462       GdkWindow *event_win;
9463       guint evmask;
9464       gboolean is_hint;
9465       GdkEventSequence *sequence;
9466
9467       sequence = gdk_event_get_event_sequence (source_event);
9468
9469       event_win = get_event_window (display,
9470                                     device,
9471                                     sequence,
9472                                     pointer_window,
9473                                     source_event->type,
9474                                     state,
9475                                     &evmask,
9476                                     _gdk_event_get_pointer_emulated (source_event),
9477                                     serial);
9478
9479       if (event_type == GDK_TOUCH_UPDATE)
9480         {
9481           if (_gdk_event_get_pointer_emulated (source_event))
9482             {
9483               /* Touch events emulating pointer events are transformed back
9484                * to pointer events if:
9485                * 1 - The event window doesn't select for touch events
9486                * 2 - There's no touch grab for this sequence, which means
9487                *     it was started as a pointer sequence, but a device
9488                *     grab added touch events afterwards, the sequence must
9489                *     not mutate in this case.
9490                */
9491               if ((evmask & GDK_TOUCH_MASK) == 0 ||
9492                   !_gdk_display_has_touch_grab (display, device, sequence, serial))
9493                 event_type = GDK_MOTION_NOTIFY;
9494             }
9495           else if ((evmask & GDK_TOUCH_MASK) == 0)
9496             return TRUE;
9497         }
9498
9499       if (is_touch_type (source_event->type) && !is_touch_type (event_type))
9500         state |= GDK_BUTTON1_MASK;
9501
9502       if (event_win &&
9503           gdk_device_get_device_type (device) != GDK_DEVICE_TYPE_MASTER &&
9504           gdk_window_get_device_events (event_win, device) == 0)
9505         return TRUE;
9506
9507       /* The last device to interact with the window was a touch device,
9508        * which synthesized a leave notify event, so synthesize another enter
9509        * notify to tell the pointer is on the window.
9510        */
9511       if (need_synthetic_enter)
9512         _gdk_synthesize_crossing_events (display,
9513                                          NULL, pointer_window,
9514                                          device, source_device,
9515                                          GDK_CROSSING_DEVICE_SWITCH,
9516                                          toplevel_x, toplevel_y,
9517                                          state, time_, NULL,
9518                                          serial, FALSE);
9519
9520       is_hint = FALSE;
9521
9522       if (event_win &&
9523           event_type == GDK_MOTION_NOTIFY &&
9524           (evmask & GDK_POINTER_MOTION_HINT_MASK))
9525         {
9526           gulong *device_serial;
9527
9528           device_serial = g_hash_table_lookup (display->motion_hint_info, device);
9529
9530           if (!device_serial ||
9531               (*device_serial != 0 &&
9532                serial < *device_serial))
9533             event_win = NULL; /* Ignore event */
9534           else
9535             {
9536               is_hint = TRUE;
9537               *device_serial = G_MAXULONG;
9538             }
9539         }
9540
9541       if (!event_win)
9542         return TRUE;
9543
9544       event = gdk_event_new (event_type);
9545       event->any.window = g_object_ref (event_win);
9546       event->any.send_event = source_event->any.send_event;
9547
9548       gdk_event_set_device (event, gdk_event_get_device (source_event));
9549       gdk_event_set_source_device (event, source_device);
9550
9551       if (event_type == GDK_TOUCH_UPDATE)
9552         {
9553           event->touch.time = time_;
9554           event->touch.state = state | GDK_BUTTON1_MASK;
9555           event->touch.sequence = source_event->touch.sequence;
9556           event->touch.emulating_pointer = source_event->touch.emulating_pointer;
9557           convert_toplevel_coords_to_window (event_win,
9558                                              toplevel_x, toplevel_y,
9559                                              &event->touch.x, &event->touch.y);
9560           gdk_event_get_root_coords (source_event,
9561                                      &event->touch.x_root,
9562                                      &event->touch.y_root);
9563
9564           event->touch.axes = g_memdup (source_event->touch.axes,
9565                                         sizeof (gdouble) * gdk_device_get_n_axes (source_event->touch.device));
9566         }
9567       else
9568         {
9569           event->motion.time = time_;
9570           event->motion.state = state;
9571           event->motion.is_hint = is_hint;
9572
9573           convert_toplevel_coords_to_window (event_win,
9574                                              toplevel_x, toplevel_y,
9575                                              &event->motion.x, &event->motion.y);
9576           gdk_event_get_root_coords (source_event,
9577                                      &event->motion.x_root,
9578                                      &event->motion.y_root);
9579
9580           if (is_touch_type (source_event->type))
9581             event->motion.axes = g_memdup (source_event->touch.axes,
9582                                            sizeof (gdouble) * gdk_device_get_n_axes (source_event->touch.device));
9583           else
9584             event->motion.axes = g_memdup (source_event->motion.axes,
9585                                            sizeof (gdouble) * gdk_device_get_n_axes (source_event->motion.device));
9586         }
9587
9588       /* Just insert the event */
9589       _gdk_event_queue_insert_after (gdk_window_get_display (event_win),
9590                                      source_event, event);
9591     }
9592
9593   /* unlink all move events from queue.
9594      We handle our own, including our emulated masks. */
9595   return TRUE;
9596 }
9597
9598 #define GDK_ANY_BUTTON_MASK (GDK_BUTTON1_MASK | \
9599                              GDK_BUTTON2_MASK | \
9600                              GDK_BUTTON3_MASK | \
9601                              GDK_BUTTON4_MASK | \
9602                              GDK_BUTTON5_MASK)
9603
9604 static gboolean
9605 proxy_button_event (GdkEvent *source_event,
9606                     gulong serial)
9607 {
9608   GdkWindow *toplevel_window, *event_window;
9609   GdkWindow *event_win;
9610   GdkWindow *pointer_window;
9611   GdkWindow *parent;
9612   GdkEvent *event;
9613   GdkPointerWindowInfo *pointer_info;
9614   GdkDeviceGrabInfo *pointer_grab;
9615   guint state;
9616   guint32 time_;
9617   GdkEventType type;
9618   gdouble toplevel_x, toplevel_y;
9619   GdkDisplay *display;
9620   GdkWindow *w;
9621   GdkDevice *device, *source_device;
9622   GdkEventMask evmask;
9623   GdkEventSequence *sequence;
9624
9625   type = source_event->any.type;
9626   event_window = source_event->any.window;
9627   gdk_event_get_coords (source_event, &toplevel_x, &toplevel_y);
9628   gdk_event_get_state (source_event, &state);
9629   time_ = gdk_event_get_time (source_event);
9630   device = gdk_event_get_device (source_event);
9631   source_device = gdk_event_get_source_device (source_event);
9632   display = gdk_window_get_display (source_event->any.window);
9633   toplevel_window = convert_native_coords_to_toplevel (event_window,
9634                                                        toplevel_x, toplevel_y,
9635                                                        &toplevel_x, &toplevel_y);
9636
9637   sequence = gdk_event_get_event_sequence (source_event);
9638
9639   pointer_info = _gdk_display_get_pointer_info (display, device);
9640   pointer_grab = _gdk_display_has_device_grab (display, device, serial);
9641
9642   if ((type == GDK_BUTTON_PRESS ||
9643        type == GDK_TOUCH_BEGIN) &&
9644       !source_event->any.send_event &&
9645       (!pointer_grab ||
9646        (type == GDK_TOUCH_BEGIN && pointer_grab->implicit &&
9647         !_gdk_event_get_pointer_emulated (source_event))))
9648     {
9649       pointer_window =
9650         _gdk_window_find_descendant_at (toplevel_window,
9651                                         toplevel_x, toplevel_y,
9652                                         NULL, NULL);
9653
9654       /* Find the event window, that gets the grab */
9655       w = pointer_window;
9656       while (w != NULL &&
9657              (parent = get_event_parent (w)) != NULL &&
9658              parent->window_type != GDK_WINDOW_ROOT)
9659         {
9660           if (w->event_mask & GDK_BUTTON_PRESS_MASK &&
9661               (type == GDK_BUTTON_PRESS ||
9662                _gdk_event_get_pointer_emulated (source_event)))
9663             break;
9664
9665           if (type == GDK_TOUCH_BEGIN &&
9666               w->event_mask & GDK_TOUCH_MASK)
9667             break;
9668
9669           w = parent;
9670         }
9671       pointer_window = w;
9672
9673       if (pointer_window)
9674         {
9675           if (type == GDK_TOUCH_BEGIN &&
9676               pointer_window->event_mask & GDK_TOUCH_MASK)
9677             {
9678               _gdk_display_add_touch_grab (display, device, sequence,
9679                                            pointer_window, event_window,
9680                                            gdk_window_get_events (pointer_window),
9681                                            serial, time_);
9682             }
9683           else if (type == GDK_BUTTON_PRESS ||
9684                    _gdk_event_get_pointer_emulated (source_event))
9685             {
9686               _gdk_display_add_device_grab  (display,
9687                                              device,
9688                                              pointer_window,
9689                                              event_window,
9690                                              GDK_OWNERSHIP_NONE,
9691                                              FALSE,
9692                                              gdk_window_get_events (pointer_window),
9693                                              serial,
9694                                              time_,
9695                                              TRUE);
9696               _gdk_display_device_grab_update (display, device,
9697                                                source_device, serial);
9698             }
9699         }
9700     }
9701
9702   pointer_window = get_pointer_window (display, toplevel_window, device,
9703                                        toplevel_x, toplevel_y,
9704                                        serial);
9705
9706   event_win = get_event_window (display,
9707                                 device,
9708                                 sequence,
9709                                 pointer_window,
9710                                 type, state,
9711                                 &evmask,
9712                                 _gdk_event_get_pointer_emulated (source_event),
9713                                 serial);
9714
9715   if (type == GDK_TOUCH_BEGIN || type == GDK_TOUCH_END)
9716     {
9717       if (_gdk_event_get_pointer_emulated (source_event))
9718         {
9719           if ((evmask & GDK_TOUCH_MASK) == 0 ||
9720               !_gdk_display_has_touch_grab (display, device, sequence, serial))
9721             {
9722               if (type == GDK_TOUCH_BEGIN)
9723                 type = GDK_BUTTON_PRESS;
9724               else if (type == GDK_TOUCH_END)
9725                 type = GDK_BUTTON_RELEASE;
9726             }
9727         }
9728       else if ((evmask & GDK_TOUCH_MASK) == 0)
9729         return TRUE;
9730     }
9731
9732   if (source_event->type == GDK_TOUCH_END && !is_touch_type (type))
9733     state |= GDK_BUTTON1_MASK;
9734
9735   if (event_win == NULL)
9736     return TRUE;
9737
9738   if (gdk_device_get_device_type (device) != GDK_DEVICE_TYPE_MASTER &&
9739       gdk_window_get_device_events (event_win, device) == 0)
9740     return TRUE;
9741
9742   if ((type == GDK_BUTTON_PRESS ||
9743        (type == GDK_TOUCH_BEGIN &&
9744         _gdk_event_get_pointer_emulated (source_event))) &&
9745       pointer_info->need_touch_press_enter)
9746     {
9747       GdkCrossingMode mode;
9748
9749       /* The last device to interact with the window was a touch device,
9750        * which synthesized a leave notify event, so synthesize another enter
9751        * notify to tell the pointer is on the window.
9752        */
9753       if (gdk_device_get_source (source_device) == GDK_SOURCE_TOUCHSCREEN)
9754         mode = GDK_CROSSING_TOUCH_BEGIN;
9755       else
9756         mode = GDK_CROSSING_DEVICE_SWITCH;
9757
9758       pointer_info->need_touch_press_enter = FALSE;
9759       _gdk_synthesize_crossing_events (display,
9760                                        NULL,
9761                                        pointer_info->window_under_pointer,
9762                                        device, source_device, mode,
9763                                        toplevel_x, toplevel_y,
9764                                        state, time_, source_event,
9765                                        serial, FALSE);
9766     }
9767   else if (type == GDK_SCROLL &&
9768            (((evmask & GDK_SMOOTH_SCROLL_MASK) == 0 &&
9769              source_event->scroll.direction == GDK_SCROLL_SMOOTH) ||
9770             ((evmask & GDK_SMOOTH_SCROLL_MASK) != 0 &&
9771              source_event->scroll.direction != GDK_SCROLL_SMOOTH &&
9772              _gdk_event_get_pointer_emulated (source_event))))
9773     return FALSE;
9774
9775   event = _gdk_make_event (event_win, type, source_event, FALSE);
9776
9777   switch (type)
9778     {
9779     case GDK_BUTTON_PRESS:
9780     case GDK_BUTTON_RELEASE:
9781       event->button.button = source_event->button.button;
9782       convert_toplevel_coords_to_window (event_win,
9783                                          toplevel_x, toplevel_y,
9784                                          &event->button.x, &event->button.y);
9785       gdk_event_get_root_coords (source_event,
9786                                  &event->button.x_root,
9787                                  &event->button.y_root);
9788       gdk_event_set_device (event, gdk_event_get_device (source_event));
9789       gdk_event_set_source_device (event, source_device);
9790
9791       if (is_touch_type (source_event->type))
9792         {
9793           if (type == GDK_BUTTON_RELEASE)
9794             event->button.state |= GDK_BUTTON1_MASK;
9795           event->button.button = 1;
9796           event->button.axes = g_memdup (source_event->touch.axes,
9797                                          sizeof (gdouble) * gdk_device_get_n_axes (source_event->touch.device));
9798         }
9799       else
9800         {
9801           event->button.button = source_event->button.button;
9802           event->button.axes = g_memdup (source_event->button.axes,
9803                                          sizeof (gdouble) * gdk_device_get_n_axes (source_event->button.device));
9804         }
9805
9806       if (type == GDK_BUTTON_PRESS)
9807         _gdk_event_button_generate (display, event);
9808       else if ((type == GDK_BUTTON_RELEASE ||
9809                 (type == GDK_TOUCH_END &&
9810                  _gdk_event_get_pointer_emulated (source_event))) &&
9811                pointer_window == pointer_info->window_under_pointer &&
9812                gdk_device_get_source (source_device) == GDK_SOURCE_TOUCHSCREEN)
9813         {
9814           /* Synthesize a leave notify event
9815            * whenever a touch device is released
9816            */
9817           pointer_info->need_touch_press_enter = TRUE;
9818           _gdk_synthesize_crossing_events (display,
9819                                            pointer_window, NULL,
9820                                            device, source_device,
9821                                            GDK_CROSSING_TOUCH_END,
9822                                            toplevel_x, toplevel_y,
9823                                            state, time_, NULL,
9824                                            serial, FALSE);
9825         }
9826       return TRUE;
9827
9828     case GDK_TOUCH_BEGIN:
9829     case GDK_TOUCH_END:
9830       convert_toplevel_coords_to_window (event_win,
9831                                          toplevel_x, toplevel_y,
9832                                          &event->button.x, &event->button.y);
9833       gdk_event_get_root_coords (source_event,
9834                                  &event->touch.x_root,
9835                                  &event->touch.y_root);
9836       event->touch.state = state;
9837       event->touch.device = source_event->touch.device;
9838       event->touch.axes = g_memdup (source_event->touch.axes,
9839                                      sizeof (gdouble) * gdk_device_get_n_axes (source_event->touch.device));
9840       event->touch.sequence = source_event->touch.sequence;
9841       event->touch.emulating_pointer = source_event->touch.emulating_pointer;
9842
9843       gdk_event_set_source_device (event, source_device);
9844
9845       if ((type == GDK_TOUCH_END &&
9846            _gdk_event_get_pointer_emulated (source_event)) &&
9847            pointer_window == pointer_info->window_under_pointer &&
9848            gdk_device_get_source (source_device) == GDK_SOURCE_TOUCHSCREEN)
9849         {
9850           /* Synthesize a leave notify event
9851            * whenever a touch device is released
9852            */
9853           pointer_info->need_touch_press_enter = TRUE;
9854           _gdk_synthesize_crossing_events (display,
9855                                            pointer_window, NULL,
9856                                            device, source_device,
9857                                            GDK_CROSSING_TOUCH_END,
9858                                            toplevel_x, toplevel_y,
9859                                            state, time_, NULL,
9860                                            serial, FALSE);
9861         }
9862       return TRUE;
9863
9864     case GDK_SCROLL:
9865       event->scroll.direction = source_event->scroll.direction;
9866       convert_toplevel_coords_to_window (event_win,
9867                                          toplevel_x, toplevel_y,
9868                                          &event->scroll.x, &event->scroll.y);
9869       event->scroll.x_root = source_event->scroll.x_root;
9870       event->scroll.y_root = source_event->scroll.y_root;
9871       event->scroll.state = state;
9872       event->scroll.device = source_event->scroll.device;
9873       event->scroll.delta_x = source_event->scroll.delta_x;
9874       event->scroll.delta_y = source_event->scroll.delta_y;
9875       gdk_event_set_source_device (event, source_device);
9876       return TRUE;
9877
9878     default:
9879       return FALSE;
9880     }
9881
9882   return TRUE; /* Always unlink original, we want to obey the emulated event mask */
9883 }
9884
9885 #ifdef DEBUG_WINDOW_PRINTING
9886
9887 #ifdef GDK_WINDOWING_X11
9888 #include "x11/gdkx.h"
9889 #endif
9890
9891 static void
9892 gdk_window_print (GdkWindow *window,
9893                   int indent)
9894 {
9895   char *s;
9896   const char *window_types[] = {
9897     "root",
9898     "toplevel",
9899     "child",
9900     "dialog",
9901     "temp",
9902     "foreign",
9903     "offscreen"
9904   };
9905
9906   g_print ("%*s%p: [%s] %d,%d %dx%d", indent, "", window,
9907            window->user_data ? g_type_name_from_instance (window->user_data) : "no widget",
9908            window->x, window->y,
9909            window->width, window->height
9910            );
9911
9912   if (gdk_window_has_impl (window))
9913     {
9914 #ifdef GDK_WINDOWING_X11
9915       g_print (" impl(0x%lx)", gdk_x11_window_get_xid (window));
9916 #endif
9917     }
9918
9919   if (window->window_type != GDK_WINDOW_CHILD)
9920     g_print (" %s", window_types[window->window_type]);
9921
9922   if (window->input_only)
9923     g_print (" input-only");
9924
9925   if (window->shaped)
9926     g_print (" shaped");
9927
9928   if (!gdk_window_is_visible ((GdkWindow *)window))
9929     g_print (" hidden");
9930
9931   g_print (" abs[%d,%d]",
9932            window->abs_x, window->abs_y);
9933
9934   s = print_region (window->clip_region);
9935   g_print (" clipbox[%s]", s);
9936
9937   g_print ("\n");
9938 }
9939
9940
9941 static void
9942 gdk_window_print_tree (GdkWindow *window,
9943                        int indent,
9944                        gboolean include_input_only)
9945 {
9946   GList *l;
9947
9948   if (window->input_only && !include_input_only)
9949     return;
9950
9951   gdk_window_print (window, indent);
9952
9953   for (l = window->children; l != NULL; l = l->next)
9954     gdk_window_print_tree (l->data, indent + 4, include_input_only);
9955 }
9956
9957 #endif /* DEBUG_WINDOW_PRINTING */
9958
9959 void
9960 _gdk_windowing_got_event (GdkDisplay *display,
9961                           GList      *event_link,
9962                           GdkEvent   *event,
9963                           gulong      serial)
9964 {
9965   GdkWindow *event_window;
9966   gdouble x, y;
9967   gboolean unlink_event;
9968   GdkDeviceGrabInfo *button_release_grab;
9969   GdkPointerWindowInfo *pointer_info = NULL;
9970   GdkDevice *device, *source_device;
9971   gboolean is_toplevel;
9972
9973   if (gdk_event_get_time (event) != GDK_CURRENT_TIME)
9974     display->last_event_time = gdk_event_get_time (event);
9975
9976   device = gdk_event_get_device (event);
9977   source_device = gdk_event_get_source_device (event);
9978
9979   if (device)
9980     {
9981       GdkInputMode mode;
9982
9983       if (gdk_device_get_source (device) != GDK_SOURCE_KEYBOARD)
9984         {
9985           pointer_info = _gdk_display_get_pointer_info (display, device);
9986
9987           if (source_device != pointer_info->last_slave &&
9988               gdk_device_get_device_type (source_device) == GDK_DEVICE_TYPE_SLAVE)
9989             pointer_info->last_slave = source_device;
9990           else if (pointer_info->last_slave)
9991             source_device = pointer_info->last_slave;
9992         }
9993
9994       g_object_get (device, "input-mode", &mode, NULL);
9995       _gdk_display_device_grab_update (display, device, source_device, serial);
9996
9997       if (mode == GDK_MODE_DISABLED ||
9998           !_gdk_display_check_grab_ownership (display, device, serial))
9999         {
10000           /* Device events are blocked by another
10001            * device grab, or the device is disabled
10002            */
10003           unlink_event = TRUE;
10004           goto out;
10005         }
10006     }
10007
10008   event_window = event->any.window;
10009   if (!event_window)
10010     return;
10011
10012 #ifdef DEBUG_WINDOW_PRINTING
10013   if (event->type == GDK_KEY_PRESS &&
10014       (event->key.keyval == 0xa7 ||
10015        event->key.keyval == 0xbd))
10016     {
10017       gdk_window_print_tree (event_window, 0, event->key.keyval == 0xbd);
10018     }
10019 #endif
10020
10021   if (event->type == GDK_VISIBILITY_NOTIFY)
10022     {
10023       event_window->native_visibility = event->visibility.state;
10024       gdk_window_update_visibility_recursively (event_window, event_window);
10025       return;
10026     }
10027
10028   if (!(is_button_type (event->type) ||
10029         is_motion_type (event->type)) ||
10030       event_window->window_type == GDK_WINDOW_ROOT)
10031     return;
10032
10033   is_toplevel = gdk_window_is_toplevel (event_window);
10034
10035   if ((event->type == GDK_ENTER_NOTIFY ||
10036        event->type == GDK_LEAVE_NOTIFY) &&
10037       (event->crossing.mode == GDK_CROSSING_GRAB ||
10038        event->crossing.mode == GDK_CROSSING_UNGRAB) &&
10039       (_gdk_display_has_device_grab (display, device, serial) ||
10040        event->crossing.detail == GDK_NOTIFY_INFERIOR))
10041     {
10042       /* We synthesize all crossing events due to grabs ourselves,
10043        * so we ignore the native ones caused by our native pointer_grab
10044        * calls. Otherwise we would proxy these crossing event and cause
10045        * multiple copies of crossing events for grabs.
10046        *
10047        * We do want to handle grabs from other clients though, as for
10048        * instance alt-tab in metacity causes grabs like these and
10049        * we want to handle those. Thus the has_pointer_grab check.
10050        *
10051        * Implicit grabs on child windows create some grabbing events
10052        * that are sent before the button press. This means we can't
10053        * detect these with the has_pointer_grab check (as the implicit
10054        * grab is only noticed when we get button press event), so we
10055        * detect these events by checking for INFERIOR enter or leave
10056        * events. These should never be a problem to filter out.
10057        */
10058
10059       /* We ended up in this window after some (perhaps other clients)
10060        * grab, so update the toplevel_under_window state
10061        */
10062       if (is_toplevel &&
10063           event->type == GDK_ENTER_NOTIFY &&
10064           event->crossing.mode == GDK_CROSSING_UNGRAB)
10065         {
10066           if (pointer_info->toplevel_under_pointer)
10067             g_object_unref (pointer_info->toplevel_under_pointer);
10068           pointer_info->toplevel_under_pointer = g_object_ref (event_window);
10069         }
10070
10071       unlink_event = TRUE;
10072       goto out;
10073     }
10074
10075   /* Track toplevel_under_pointer */
10076   if (is_toplevel)
10077     {
10078       if (event->type == GDK_ENTER_NOTIFY &&
10079           event->crossing.detail != GDK_NOTIFY_INFERIOR)
10080         {
10081           if (pointer_info->toplevel_under_pointer)
10082             g_object_unref (pointer_info->toplevel_under_pointer);
10083           pointer_info->toplevel_under_pointer = g_object_ref (event_window);
10084         }
10085       else if (event->type == GDK_LEAVE_NOTIFY &&
10086                event->crossing.detail != GDK_NOTIFY_INFERIOR &&
10087                pointer_info->toplevel_under_pointer == event_window)
10088         {
10089           if (pointer_info->toplevel_under_pointer)
10090             g_object_unref (pointer_info->toplevel_under_pointer);
10091           pointer_info->toplevel_under_pointer = NULL;
10092         }
10093     }
10094
10095   if (pointer_info &&
10096       (!is_touch_type (event->type) ||
10097        _gdk_event_get_pointer_emulated (event)))
10098     {
10099       guint old_state, old_button;
10100
10101       /* Store last pointer window and position/state */
10102       old_state = pointer_info->state;
10103       old_button = pointer_info->button;
10104
10105       gdk_event_get_coords (event, &x, &y);
10106       convert_native_coords_to_toplevel (event_window, x, y,  &x, &y);
10107       pointer_info->toplevel_x = x;
10108       pointer_info->toplevel_y = y;
10109       gdk_event_get_state (event, &pointer_info->state);
10110
10111       if (event->type == GDK_BUTTON_PRESS ||
10112           event->type == GDK_BUTTON_RELEASE)
10113         pointer_info->button = event->button.button;
10114       else if (event->type == GDK_TOUCH_BEGIN ||
10115                event->type == GDK_TOUCH_END)
10116         pointer_info->button = 1;
10117
10118       if (device &&
10119           (pointer_info->state != old_state ||
10120            pointer_info->button != old_button))
10121         _gdk_display_enable_motion_hints (display, device);
10122     }
10123
10124   unlink_event = FALSE;
10125   if (is_motion_type (event->type))
10126     unlink_event = proxy_pointer_event (display, event, serial);
10127   else if (is_button_type (event->type))
10128     unlink_event = proxy_button_event (event, serial);
10129
10130   if ((event->type == GDK_BUTTON_RELEASE ||
10131        event->type == GDK_TOUCH_END) &&
10132       !event->any.send_event)
10133     {
10134       GdkEventSequence *sequence;
10135
10136       sequence = gdk_event_get_event_sequence (event);
10137       if (event->type == GDK_TOUCH_END && sequence)
10138         {
10139           _gdk_display_end_touch_grab (display, device, sequence);
10140         }
10141
10142       if (event->type == GDK_BUTTON_RELEASE ||
10143           _gdk_event_get_pointer_emulated (event))
10144         {
10145           button_release_grab =
10146             _gdk_display_has_device_grab (display, device, serial);
10147
10148           if (button_release_grab &&
10149               button_release_grab->implicit &&
10150               (event->button.state & GDK_ANY_BUTTON_MASK & ~(GDK_BUTTON1_MASK << (event->button.button - 1))) == 0)
10151             {
10152               button_release_grab->serial_end = serial;
10153               button_release_grab->implicit_ungrab = FALSE;
10154               _gdk_display_device_grab_update (display, device, source_device, serial);
10155             }
10156         }
10157     }
10158
10159  out:
10160   if (unlink_event)
10161     {
10162       _gdk_event_queue_remove_link (display, event_link);
10163       g_list_free_1 (event_link);
10164       gdk_event_free (event);
10165     }
10166 }
10167
10168 /**
10169  * gdk_window_create_similar_surface:
10170  * @window: window to make new surface similar to
10171  * @content: the content for the new surface
10172  * @width: width of the new surface
10173  * @height: height of the new surface
10174  *
10175  * Create a new surface that is as compatible as possible with the
10176  * given @window. For example the new surface will have the same
10177  * fallback resolution and font options as @window. Generally, the new
10178  * surface will also use the same backend as @window, unless that is
10179  * not possible for some reason. The type of the returned surface may
10180  * be examined with cairo_surface_get_type().
10181  *
10182  * Initially the surface contents are all 0 (transparent if contents
10183  * have transparency, black otherwise.)
10184  *
10185  * Returns: a pointer to the newly allocated surface. The caller
10186  * owns the surface and should call cairo_surface_destroy() when done
10187  * with it.
10188  *
10189  * This function always returns a valid pointer, but it will return a
10190  * pointer to a "nil" surface if @other is already in an error state
10191  * or any other error occurs.
10192  *
10193  * Since: 2.22
10194  **/
10195 cairo_surface_t *
10196 gdk_window_create_similar_surface (GdkWindow *     window,
10197                                    cairo_content_t content,
10198                                    int             width,
10199                                    int             height)
10200 {
10201   cairo_surface_t *window_surface, *surface;
10202
10203   g_return_val_if_fail (GDK_IS_WINDOW (window), NULL);
10204   
10205   window_surface = gdk_window_ref_impl_surface (window);
10206
10207   switch (_gdk_rendering_mode)
10208   {
10209     case GDK_RENDERING_MODE_RECORDING:
10210       {
10211         cairo_rectangle_t rect = { 0, 0, width, height };
10212         surface = cairo_recording_surface_create (content, &rect);
10213       }
10214       break;
10215     case GDK_RENDERING_MODE_IMAGE:
10216       surface = cairo_image_surface_create (content == CAIRO_CONTENT_COLOR ? CAIRO_FORMAT_RGB24 :
10217                                             content == CAIRO_CONTENT_ALPHA ? CAIRO_FORMAT_A8 : CAIRO_FORMAT_ARGB32,
10218                                             width, height);
10219       break;
10220     case GDK_RENDERING_MODE_SIMILAR:
10221     default:
10222       surface = cairo_surface_create_similar (window_surface,
10223                                               content,
10224                                               width, height);
10225       break;
10226   }
10227
10228   cairo_surface_destroy (window_surface);
10229
10230   return surface;
10231 }
10232
10233 /**
10234  * gdk_window_focus:
10235  * @window: a #GdkWindow
10236  * @timestamp: timestamp of the event triggering the window focus
10237  *
10238  * Sets keyboard focus to @window. In most cases, gtk_window_present()
10239  * should be used on a #GtkWindow, rather than calling this function.
10240  *
10241  **/
10242 void
10243 gdk_window_focus (GdkWindow *window,
10244                   guint32    timestamp)
10245 {
10246   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->focus (window, timestamp);
10247 }
10248
10249 /**
10250  * gdk_window_set_type_hint:
10251  * @window: A toplevel #GdkWindow
10252  * @hint: A hint of the function this window will have
10253  *
10254  * The application can use this call to provide a hint to the window
10255  * manager about the functionality of a window. The window manager
10256  * can use this information when determining the decoration and behaviour
10257  * of the window.
10258  *
10259  * The hint must be set before the window is mapped.
10260  **/
10261 void
10262 gdk_window_set_type_hint (GdkWindow        *window,
10263                           GdkWindowTypeHint hint)
10264 {
10265   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_type_hint (window, hint);
10266 }
10267
10268 /**
10269  * gdk_window_get_type_hint:
10270  * @window: A toplevel #GdkWindow
10271  *
10272  * This function returns the type hint set for a window.
10273  *
10274  * Return value: The type hint set for @window
10275  *
10276  * Since: 2.10
10277  **/
10278 GdkWindowTypeHint
10279 gdk_window_get_type_hint (GdkWindow *window)
10280 {
10281   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)->get_type_hint (window);
10282 }
10283
10284 /**
10285  * gdk_window_set_modal_hint:
10286  * @window: A toplevel #GdkWindow
10287  * @modal: %TRUE if the window is modal, %FALSE otherwise.
10288  *
10289  * The application can use this hint to tell the window manager
10290  * that a certain window has modal behaviour. The window manager
10291  * can use this information to handle modal windows in a special
10292  * way.
10293  *
10294  * You should only use this on windows for which you have
10295  * previously called gdk_window_set_transient_for()
10296  **/
10297 void
10298 gdk_window_set_modal_hint (GdkWindow *window,
10299                            gboolean   modal)
10300 {
10301   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_modal_hint (window, modal);
10302 }
10303
10304 /**
10305  * gdk_window_set_skip_taskbar_hint:
10306  * @window: a toplevel #GdkWindow
10307  * @skips_taskbar: %TRUE to skip the taskbar
10308  *
10309  * Toggles whether a window should appear in a task list or window
10310  * list. If a window's semantic type as specified with
10311  * gdk_window_set_type_hint() already fully describes the window, this
10312  * function should <emphasis>not</emphasis> be called in addition,
10313  * instead you should allow the window to be treated according to
10314  * standard policy for its semantic type.
10315  *
10316  * Since: 2.2
10317  **/
10318 void
10319 gdk_window_set_skip_taskbar_hint (GdkWindow *window,
10320                                   gboolean   skips_taskbar)
10321 {
10322   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_skip_taskbar_hint (window, skips_taskbar);
10323 }
10324
10325 /**
10326  * gdk_window_set_skip_pager_hint:
10327  * @window: a toplevel #GdkWindow
10328  * @skips_pager: %TRUE to skip the pager
10329  *
10330  * Toggles whether a window should appear in a pager (workspace
10331  * switcher, or other desktop utility program that displays a small
10332  * thumbnail representation of the windows on the desktop). If a
10333  * window's semantic type as specified with gdk_window_set_type_hint()
10334  * already fully describes the window, this function should
10335  * <emphasis>not</emphasis> be called in addition, instead you should
10336  * allow the window to be treated according to standard policy for
10337  * its semantic type.
10338  *
10339  * Since: 2.2
10340  **/
10341 void
10342 gdk_window_set_skip_pager_hint (GdkWindow *window,
10343                                 gboolean   skips_pager)
10344 {
10345   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_skip_pager_hint (window, skips_pager);
10346 }
10347
10348 /**
10349  * gdk_window_set_urgency_hint:
10350  * @window: a toplevel #GdkWindow
10351  * @urgent: %TRUE if the window is urgent
10352  *
10353  * Toggles whether a window needs the user's
10354  * urgent attention.
10355  *
10356  * Since: 2.8
10357  **/
10358 void
10359 gdk_window_set_urgency_hint (GdkWindow *window,
10360                              gboolean   urgent)
10361 {
10362   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_urgency_hint (window, urgent);
10363 }
10364
10365 /**
10366  * gdk_window_set_geometry_hints:
10367  * @window: a toplevel #GdkWindow
10368  * @geometry: geometry hints
10369  * @geom_mask: bitmask indicating fields of @geometry to pay attention to
10370  *
10371  * Sets the geometry hints for @window. Hints flagged in @geom_mask
10372  * are set, hints not flagged in @geom_mask are unset.
10373  * To unset all hints, use a @geom_mask of 0 and a @geometry of %NULL.
10374  *
10375  * This function provides hints to the windowing system about
10376  * acceptable sizes for a toplevel window. The purpose of
10377  * this is to constrain user resizing, but the windowing system
10378  * will typically  (but is not required to) also constrain the
10379  * current size of the window to the provided values and
10380  * constrain programatic resizing via gdk_window_resize() or
10381  * gdk_window_move_resize().
10382  *
10383  * Note that on X11, this effect has no effect on windows
10384  * of type %GDK_WINDOW_TEMP or windows where override redirect
10385  * has been turned on via gdk_window_set_override_redirect()
10386  * since these windows are not resizable by the user.
10387  *
10388  * Since you can't count on the windowing system doing the
10389  * constraints for programmatic resizes, you should generally
10390  * call gdk_window_constrain_size() yourself to determine
10391  * appropriate sizes.
10392  *
10393  **/
10394 void
10395 gdk_window_set_geometry_hints (GdkWindow         *window,
10396                                const GdkGeometry *geometry,
10397                                GdkWindowHints     geom_mask)
10398 {
10399   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_geometry_hints (window, geometry, geom_mask);
10400 }
10401
10402 /**
10403  * gdk_window_set_title:
10404  * @window: a toplevel #GdkWindow
10405  * @title: title of @window
10406  *
10407  * Sets the title of a toplevel window, to be displayed in the titlebar.
10408  * If you haven't explicitly set the icon name for the window
10409  * (using gdk_window_set_icon_name()), the icon name will be set to
10410  * @title as well. @title must be in UTF-8 encoding (as with all
10411  * user-readable strings in GDK/GTK+). @title may not be %NULL.
10412  **/
10413 void
10414 gdk_window_set_title (GdkWindow   *window,
10415                       const gchar *title)
10416 {
10417   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_title (window, title);
10418 }
10419
10420 /**
10421  * gdk_window_set_role:
10422  * @window: a toplevel #GdkWindow
10423  * @role: a string indicating its role
10424  *
10425  * When using GTK+, typically you should use gtk_window_set_role() instead
10426  * of this low-level function.
10427  *
10428  * The window manager and session manager use a window's role to
10429  * distinguish it from other kinds of window in the same application.
10430  * When an application is restarted after being saved in a previous
10431  * session, all windows with the same title and role are treated as
10432  * interchangeable.  So if you have two windows with the same title
10433  * that should be distinguished for session management purposes, you
10434  * should set the role on those windows. It doesn't matter what string
10435  * you use for the role, as long as you have a different role for each
10436  * non-interchangeable kind of window.
10437  *
10438  **/
10439 void
10440 gdk_window_set_role (GdkWindow   *window,
10441                      const gchar *role)
10442 {
10443   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_role (window, role);
10444 }
10445
10446 /**
10447  * gdk_window_set_startup_id:
10448  * @window: a toplevel #GdkWindow
10449  * @startup_id: a string with startup-notification identifier
10450  *
10451  * When using GTK+, typically you should use gtk_window_set_startup_id()
10452  * instead of this low-level function.
10453  *
10454  * Since: 2.12
10455  *
10456  **/
10457 void
10458 gdk_window_set_startup_id (GdkWindow   *window,
10459                            const gchar *startup_id)
10460 {
10461   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_startup_id (window, startup_id);
10462 }
10463
10464 /**
10465  * gdk_window_set_transient_for:
10466  * @window: a toplevel #GdkWindow
10467  * @parent: another toplevel #GdkWindow
10468  *
10469  * Indicates to the window manager that @window is a transient dialog
10470  * associated with the application window @parent. This allows the
10471  * window manager to do things like center @window on @parent and
10472  * keep @window above @parent.
10473  *
10474  * See gtk_window_set_transient_for() if you're using #GtkWindow or
10475  * #GtkDialog.
10476  **/
10477 void
10478 gdk_window_set_transient_for (GdkWindow *window,
10479                               GdkWindow *parent)
10480 {
10481   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_transient_for (window, parent);
10482 }
10483
10484 /**
10485  * gdk_window_get_root_origin:
10486  * @window: a toplevel #GdkWindow
10487  * @x: (out): return location for X position of window frame
10488  * @y: (out): return location for Y position of window frame
10489  *
10490  * Obtains the top-left corner of the window manager frame in root
10491  * window coordinates.
10492  *
10493  **/
10494 void
10495 gdk_window_get_root_origin (GdkWindow *window,
10496                             gint      *x,
10497                             gint      *y)
10498 {
10499   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->get_root_origin (window, x, y);
10500 }
10501
10502 /**
10503  * gdk_window_get_frame_extents:
10504  * @window: a toplevel #GdkWindow
10505  * @rect: (out): rectangle to fill with bounding box of the window frame
10506  *
10507  * Obtains the bounding box of the window, including window manager
10508  * titlebar/borders if any. The frame position is given in root window
10509  * coordinates. To get the position of the window itself (rather than
10510  * the frame) in root window coordinates, use gdk_window_get_origin().
10511  *
10512  **/
10513 void
10514 gdk_window_get_frame_extents (GdkWindow    *window,
10515                               GdkRectangle *rect)
10516 {
10517   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->get_frame_extents (window, rect);
10518 }
10519
10520 /**
10521  * gdk_window_set_override_redirect:
10522  * @window: a toplevel #GdkWindow
10523  * @override_redirect: %TRUE if window should be override redirect
10524  *
10525  * An override redirect window is not under the control of the window manager.
10526  * This means it won't have a titlebar, won't be minimizable, etc. - it will
10527  * be entirely under the control of the application. The window manager
10528  * can't see the override redirect window at all.
10529  *
10530  * Override redirect should only be used for short-lived temporary
10531  * windows, such as popup menus. #GtkMenu uses an override redirect
10532  * window in its implementation, for example.
10533  *
10534  **/
10535 void
10536 gdk_window_set_override_redirect (GdkWindow *window,
10537                                   gboolean override_redirect)
10538 {
10539   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_override_redirect (window, override_redirect);
10540 }
10541
10542 /**
10543  * gdk_window_set_accept_focus:
10544  * @window: a toplevel #GdkWindow
10545  * @accept_focus: %TRUE if the window should receive input focus
10546  *
10547  * Setting @accept_focus to %FALSE hints the desktop environment that the
10548  * window doesn't want to receive input focus.
10549  *
10550  * On X, it is the responsibility of the window manager to interpret this
10551  * hint. ICCCM-compliant window manager usually respect it.
10552  *
10553  * Since: 2.4
10554  **/
10555 void
10556 gdk_window_set_accept_focus (GdkWindow *window,
10557                              gboolean accept_focus)
10558 {
10559   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_accept_focus (window, accept_focus);
10560 }
10561
10562 /**
10563  * gdk_window_set_focus_on_map:
10564  * @window: a toplevel #GdkWindow
10565  * @focus_on_map: %TRUE if the window should receive input focus when mapped
10566  *
10567  * Setting @focus_on_map to %FALSE hints the desktop environment that the
10568  * window doesn't want to receive input focus when it is mapped.
10569  * focus_on_map should be turned off for windows that aren't triggered
10570  * interactively (such as popups from network activity).
10571  *
10572  * On X, it is the responsibility of the window manager to interpret
10573  * this hint. Window managers following the freedesktop.org window
10574  * manager extension specification should respect it.
10575  *
10576  * Since: 2.6
10577  **/
10578 void
10579 gdk_window_set_focus_on_map (GdkWindow *window,
10580                              gboolean focus_on_map)
10581 {
10582   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_focus_on_map (window, focus_on_map);
10583 }
10584
10585 /**
10586  * gdk_window_set_icon_list:
10587  * @window: The #GdkWindow toplevel window to set the icon of.
10588  * @pixbufs: (transfer none) (element-type GdkPixbuf):
10589  *     A list of pixbufs, of different sizes.
10590  *
10591  * Sets a list of icons for the window. One of these will be used
10592  * to represent the window when it has been iconified. The icon is
10593  * usually shown in an icon box or some sort of task bar. Which icon
10594  * size is shown depends on the window manager. The window manager
10595  * can scale the icon  but setting several size icons can give better
10596  * image quality since the window manager may only need to scale the
10597  * icon by a small amount or not at all.
10598  *
10599  **/
10600 void
10601 gdk_window_set_icon_list (GdkWindow *window,
10602                           GList     *pixbufs)
10603 {
10604   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_icon_list (window, pixbufs);
10605 }
10606
10607 /**
10608  * gdk_window_set_icon_name:
10609  * @window: a toplevel #GdkWindow
10610  * @name: (allow-none): name of window while iconified (minimized)
10611  *
10612  * Windows may have a name used while minimized, distinct from the
10613  * name they display in their titlebar. Most of the time this is a bad
10614  * idea from a user interface standpoint. But you can set such a name
10615  * with this function, if you like.
10616  *
10617  * After calling this with a non-%NULL @name, calls to gdk_window_set_title()
10618  * will not update the icon title.
10619  *
10620  * Using %NULL for @name unsets the icon title; further calls to
10621  * gdk_window_set_title() will again update the icon title as well.
10622  **/
10623 void
10624 gdk_window_set_icon_name (GdkWindow   *window,
10625                           const gchar *name)
10626 {
10627   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_icon_name (window, name);
10628 }
10629
10630 /**
10631  * gdk_window_iconify:
10632  * @window: a toplevel #GdkWindow
10633  *
10634  * Asks to iconify (minimize) @window. The window manager may choose
10635  * to ignore the request, but normally will honor it. Using
10636  * gtk_window_iconify() is preferred, if you have a #GtkWindow widget.
10637  *
10638  * This function only makes sense when @window is a toplevel window.
10639  *
10640  **/
10641 void
10642 gdk_window_iconify (GdkWindow *window)
10643 {
10644   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->iconify (window);
10645 }
10646
10647 /**
10648  * gdk_window_deiconify:
10649  * @window: a toplevel #GdkWindow
10650  *
10651  * Attempt to deiconify (unminimize) @window. On X11 the window manager may
10652  * choose to ignore the request to deiconify. When using GTK+,
10653  * use gtk_window_deiconify() instead of the #GdkWindow variant. Or better yet,
10654  * you probably want to use gtk_window_present(), which raises the window, focuses it,
10655  * unminimizes it, and puts it on the current desktop.
10656  *
10657  **/
10658 void
10659 gdk_window_deiconify (GdkWindow *window)
10660 {
10661   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->deiconify (window);
10662 }
10663
10664 /**
10665  * gdk_window_stick:
10666  * @window: a toplevel #GdkWindow
10667  *
10668  * "Pins" a window such that it's on all workspaces and does not scroll
10669  * with viewports, for window managers that have scrollable viewports.
10670  * (When using #GtkWindow, gtk_window_stick() may be more useful.)
10671  *
10672  * On the X11 platform, this function depends on window manager
10673  * support, so may have no effect with many window managers. However,
10674  * GDK will do the best it can to convince the window manager to stick
10675  * the window. For window managers that don't support this operation,
10676  * there's nothing you can do to force it to happen.
10677  *
10678  **/
10679 void
10680 gdk_window_stick (GdkWindow *window)
10681 {
10682   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->stick (window);
10683 }
10684
10685 /**
10686  * gdk_window_unstick:
10687  * @window: a toplevel #GdkWindow
10688  *
10689  * Reverse operation for gdk_window_stick(); see gdk_window_stick(),
10690  * and gtk_window_unstick().
10691  *
10692  **/
10693 void
10694 gdk_window_unstick (GdkWindow *window)
10695 {
10696   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->unstick (window);
10697 }
10698
10699 /**
10700  * gdk_window_maximize:
10701  * @window: a toplevel #GdkWindow
10702  *
10703  * Maximizes the window. If the window was already maximized, then
10704  * this function does nothing.
10705  *
10706  * On X11, asks the window manager to maximize @window, if the window
10707  * manager supports this operation. Not all window managers support
10708  * this, and some deliberately ignore it or don't have a concept of
10709  * "maximized"; so you can't rely on the maximization actually
10710  * happening. But it will happen with most standard window managers,
10711  * and GDK makes a best effort to get it to happen.
10712  *
10713  * On Windows, reliably maximizes the window.
10714  *
10715  **/
10716 void
10717 gdk_window_maximize (GdkWindow *window)
10718 {
10719   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->maximize (window);
10720 }
10721
10722 /**
10723  * gdk_window_unmaximize:
10724  * @window: a toplevel #GdkWindow
10725  *
10726  * Unmaximizes the window. If the window wasn't maximized, then this
10727  * function does nothing.
10728  *
10729  * On X11, asks the window manager to unmaximize @window, if the
10730  * window manager supports this operation. Not all window managers
10731  * support this, and some deliberately ignore it or don't have a
10732  * concept of "maximized"; so you can't rely on the unmaximization
10733  * actually happening. But it will happen with most standard window
10734  * managers, and GDK makes a best effort to get it to happen.
10735  *
10736  * On Windows, reliably unmaximizes the window.
10737  *
10738  **/
10739 void
10740 gdk_window_unmaximize (GdkWindow *window)
10741 {
10742   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->unmaximize (window);
10743 }
10744
10745 /**
10746  * gdk_window_fullscreen:
10747  * @window: a toplevel #GdkWindow
10748  *
10749  * Moves the window into fullscreen mode. This means the
10750  * window covers the entire screen and is above any panels
10751  * or task bars.
10752  *
10753  * If the window was already fullscreen, then this function does nothing.
10754  *
10755  * On X11, asks the window manager to put @window in a fullscreen
10756  * state, if the window manager supports this operation. Not all
10757  * window managers support this, and some deliberately ignore it or
10758  * don't have a concept of "fullscreen"; so you can't rely on the
10759  * fullscreenification actually happening. But it will happen with
10760  * most standard window managers, and GDK makes a best effort to get
10761  * it to happen.
10762  *
10763  * Since: 2.2
10764  **/
10765 void
10766 gdk_window_fullscreen (GdkWindow *window)
10767 {
10768   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->fullscreen (window);
10769 }
10770
10771 /**
10772  * gdk_window_set_fullscreen_mode:
10773  * @window: a toplevel #GdkWindow
10774  * @mode: fullscreen mode
10775  *
10776  * Specifies whether the @window should span over all monitors (in a multi-head
10777  * setup) or only the current monitor when in fullscreen mode.
10778  *
10779  * The @mode argument is from the #GdkFullscreenMode enumeration.
10780  * If #GDK_FULLSCREEN_ON_ALL_MONITORS is specified, the fullscreen @window will
10781  * span over all monitors from the #GdkScreen.
10782  *
10783  * On X11, searches through the list of monitors from the #GdkScreen the ones
10784  * which delimit the 4 edges of the entire #GdkScreen and will ask the window
10785  * manager to span the @window over these monitors.
10786  *
10787  * If the XINERAMA extension is not available or not usable, this function
10788  * has no effect.
10789  *
10790  * Not all window managers support this, so you can't rely on the fullscreen
10791  * window to span over the multiple monitors when #GDK_FULLSCREEN_ON_ALL_MONITORS
10792  * is specified.
10793  *
10794  * Since: 3.8
10795  **/
10796 void
10797 gdk_window_set_fullscreen_mode (GdkWindow        *window,
10798                                 GdkFullscreenMode mode)
10799 {
10800   GdkWindowImplClass *impl_class;
10801
10802   g_return_if_fail (GDK_IS_WINDOW (window));
10803
10804   if (window->fullscreen_mode != mode)
10805     {
10806       window->fullscreen_mode = mode;
10807
10808       impl_class = GDK_WINDOW_IMPL_GET_CLASS (window->impl);
10809       if (impl_class->apply_fullscreen_mode != NULL)
10810         impl_class->apply_fullscreen_mode (window);
10811     }
10812 }
10813
10814 /**
10815  * gdk_window_get_fullscreen_mode:
10816  * @window: a toplevel #GdkWindow
10817  *
10818  * Obtains the #GdkFullscreenMode of the @window.
10819  *
10820  * Returns: The #GdkFullscreenMode applied to the window when fullscreen.
10821  *
10822  * Since: 3.8
10823  **/
10824 GdkFullscreenMode
10825 gdk_window_get_fullscreen_mode (GdkWindow *window)
10826 {
10827   g_return_val_if_fail (GDK_IS_WINDOW (window), GDK_FULLSCREEN_ON_CURRENT_MONITOR);
10828
10829   return window->fullscreen_mode;
10830 }
10831
10832 /**
10833  * gdk_window_unfullscreen:
10834  * @window: a toplevel #GdkWindow
10835  *
10836  * Moves the window out of fullscreen mode. If the window was not
10837  * fullscreen, does nothing.
10838  *
10839  * On X11, asks the window manager to move @window out of the fullscreen
10840  * state, if the window manager supports this operation. Not all
10841  * window managers support this, and some deliberately ignore it or
10842  * don't have a concept of "fullscreen"; so you can't rely on the
10843  * unfullscreenification actually happening. But it will happen with
10844  * most standard window managers, and GDK makes a best effort to get
10845  * it to happen.
10846  *
10847  * Since: 2.2
10848  **/
10849 void
10850 gdk_window_unfullscreen (GdkWindow *window)
10851 {
10852   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->unfullscreen (window);
10853 }
10854
10855 /**
10856  * gdk_window_set_keep_above:
10857  * @window: a toplevel #GdkWindow
10858  * @setting: whether to keep @window above other windows
10859  *
10860  * Set if @window must be kept above other windows. If the
10861  * window was already above, then this function does nothing.
10862  *
10863  * On X11, asks the window manager to keep @window above, if the window
10864  * manager supports this operation. Not all window managers support
10865  * this, and some deliberately ignore it or don't have a concept of
10866  * "keep above"; so you can't rely on the window being kept above.
10867  * But it will happen with most standard window managers,
10868  * and GDK makes a best effort to get it to happen.
10869  *
10870  * Since: 2.4
10871  **/
10872 void
10873 gdk_window_set_keep_above (GdkWindow *window,
10874                            gboolean   setting)
10875 {
10876   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_keep_above (window, setting);
10877 }
10878
10879 /**
10880  * gdk_window_set_keep_below:
10881  * @window: a toplevel #GdkWindow
10882  * @setting: whether to keep @window below other windows
10883  *
10884  * Set if @window must be kept below other windows. If the
10885  * window was already below, then this function does nothing.
10886  *
10887  * On X11, asks the window manager to keep @window below, if the window
10888  * manager supports this operation. Not all window managers support
10889  * this, and some deliberately ignore it or don't have a concept of
10890  * "keep below"; so you can't rely on the window being kept below.
10891  * But it will happen with most standard window managers,
10892  * and GDK makes a best effort to get it to happen.
10893  *
10894  * Since: 2.4
10895  **/
10896 void
10897 gdk_window_set_keep_below (GdkWindow *window, gboolean setting)
10898 {
10899   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_keep_below (window, setting);
10900 }
10901
10902 /**
10903  * gdk_window_get_group:
10904  * @window: a toplevel #GdkWindow
10905  *
10906  * Returns the group leader window for @window. See gdk_window_set_group().
10907  *
10908  * Return value: (transfer none): the group leader window for @window
10909  *
10910  * Since: 2.4
10911  **/
10912 GdkWindow *
10913 gdk_window_get_group (GdkWindow *window)
10914 {
10915   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)->get_group (window);
10916 }
10917
10918 /**
10919  * gdk_window_set_group:
10920  * @window: a toplevel #GdkWindow
10921  * @leader: (allow-none): group leader window, or %NULL to restore the default group leader window
10922  *
10923  * Sets the group leader window for @window. By default,
10924  * GDK sets the group leader for all toplevel windows
10925  * to a global window implicitly created by GDK. With this function
10926  * you can override this default.
10927  *
10928  * The group leader window allows the window manager to distinguish
10929  * all windows that belong to a single application. It may for example
10930  * allow users to minimize/unminimize all windows belonging to an
10931  * application at once. You should only set a non-default group window
10932  * if your application pretends to be multiple applications.
10933  **/
10934 void
10935 gdk_window_set_group (GdkWindow *window,
10936                       GdkWindow *leader)
10937 {
10938   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_group (window, leader);
10939 }
10940
10941 /**
10942  * gdk_window_set_decorations:
10943  * @window: a toplevel #GdkWindow
10944  * @decorations: decoration hint mask
10945  *
10946  * "Decorations" are the features the window manager adds to a toplevel #GdkWindow.
10947  * This function sets the traditional Motif window manager hints that tell the
10948  * window manager which decorations you would like your window to have.
10949  * Usually you should use gtk_window_set_decorated() on a #GtkWindow instead of
10950  * using the GDK function directly.
10951  *
10952  * The @decorations argument is the logical OR of the fields in
10953  * the #GdkWMDecoration enumeration. If #GDK_DECOR_ALL is included in the
10954  * mask, the other bits indicate which decorations should be turned off.
10955  * If #GDK_DECOR_ALL is not included, then the other bits indicate
10956  * which decorations should be turned on.
10957  *
10958  * Most window managers honor a decorations hint of 0 to disable all decorations,
10959  * but very few honor all possible combinations of bits.
10960  *
10961  **/
10962 void
10963 gdk_window_set_decorations (GdkWindow      *window,
10964                             GdkWMDecoration decorations)
10965 {
10966   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_decorations (window, decorations);
10967 }
10968
10969 /**
10970  * gdk_window_get_decorations:
10971  * @window: The toplevel #GdkWindow to get the decorations from
10972  * @decorations: (out): The window decorations will be written here
10973  *
10974  * Returns the decorations set on the GdkWindow with
10975  * gdk_window_set_decorations().
10976  *
10977  * Returns: %TRUE if the window has decorations set, %FALSE otherwise.
10978  **/
10979 gboolean
10980 gdk_window_get_decorations(GdkWindow       *window,
10981                            GdkWMDecoration *decorations)
10982 {
10983   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)->get_decorations (window, decorations);
10984 }
10985
10986 /**
10987  * gdk_window_set_functions:
10988  * @window: a toplevel #GdkWindow
10989  * @functions: bitmask of operations to allow on @window
10990  *
10991  * Sets hints about the window management functions to make available
10992  * via buttons on the window frame.
10993  *
10994  * On the X backend, this function sets the traditional Motif window
10995  * manager hint for this purpose. However, few window managers do
10996  * anything reliable or interesting with this hint. Many ignore it
10997  * entirely.
10998  *
10999  * The @functions argument is the logical OR of values from the
11000  * #GdkWMFunction enumeration. If the bitmask includes #GDK_FUNC_ALL,
11001  * then the other bits indicate which functions to disable; if
11002  * it doesn't include #GDK_FUNC_ALL, it indicates which functions to
11003  * enable.
11004  *
11005  **/
11006 void
11007 gdk_window_set_functions (GdkWindow    *window,
11008                           GdkWMFunction functions)
11009 {
11010   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_functions (window, functions);
11011 }
11012
11013 /**
11014  * gdk_window_begin_resize_drag_for_device:
11015  * @window: a toplevel #GdkWindow
11016  * @edge: the edge or corner from which the drag is started
11017  * @device: the device used for the operation
11018  * @button: the button being used to drag
11019  * @root_x: root window X coordinate of mouse click that began the drag
11020  * @root_y: root window Y coordinate of mouse click that began the drag
11021  * @timestamp: timestamp of mouse click that began the drag (use gdk_event_get_time())
11022  *
11023  * Begins a window resize operation (for a toplevel window).
11024  * You might use this function to implement a "window resize grip," for
11025  * example; in fact #GtkStatusbar uses it. The function works best
11026  * with window managers that support the <ulink url="http://www.freedesktop.org/Standards/wm-spec">Extended Window Manager Hints</ulink>, but has a
11027  * fallback implementation for other window managers.
11028  *
11029  * Since: 3.4
11030  */
11031 void
11032 gdk_window_begin_resize_drag_for_device (GdkWindow     *window,
11033                                          GdkWindowEdge  edge,
11034                                          GdkDevice     *device,
11035                                          gint           button,
11036                                          gint           root_x,
11037                                          gint           root_y,
11038                                          guint32        timestamp)
11039 {
11040   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->begin_resize_drag (window, edge, device, button, root_x, root_y, timestamp);
11041 }
11042
11043 /**
11044  * gdk_window_begin_resize_drag:
11045  * @window: a toplevel #GdkWindow
11046  * @edge: the edge or corner from which the drag is started
11047  * @button: the button being used to drag
11048  * @root_x: root window X coordinate of mouse click that began the drag
11049  * @root_y: root window Y coordinate of mouse click that began the drag
11050  * @timestamp: timestamp of mouse click that began the drag (use gdk_event_get_time())
11051  *
11052  * Begins a window resize operation (for a toplevel window).
11053  *
11054  * This function assumes that the drag is controlled by the
11055  * client pointer device, use gdk_window_begin_resize_drag_for_device()
11056  * to begin a drag with a different device.
11057  */
11058 void
11059 gdk_window_begin_resize_drag (GdkWindow     *window,
11060                               GdkWindowEdge  edge,
11061                               gint           button,
11062                               gint           root_x,
11063                               gint           root_y,
11064                               guint32        timestamp)
11065 {
11066   GdkDeviceManager *device_manager;
11067   GdkDevice *device;
11068
11069   device_manager = gdk_display_get_device_manager (gdk_window_get_display (window));
11070   device = gdk_device_manager_get_client_pointer (device_manager);
11071   gdk_window_begin_resize_drag_for_device (window, edge,
11072                                            device, button, root_x, root_y, timestamp);
11073 }
11074
11075 /**
11076  * gdk_window_begin_move_drag_for_device:
11077  * @window: a toplevel #GdkWindow
11078  * @device: the device used for the operation
11079  * @button: the button being used to drag
11080  * @root_x: root window X coordinate of mouse click that began the drag
11081  * @root_y: root window Y coordinate of mouse click that began the drag
11082  * @timestamp: timestamp of mouse click that began the drag
11083  *
11084  * Begins a window move operation (for a toplevel window).
11085  * You might use this function to implement a "window move grip," for
11086  * example. The function works best with window managers that support
11087  * the <ulink url="http://www.freedesktop.org/Standards/wm-spec">Extended
11088  * Window Manager Hints</ulink>, but has a fallback implementation for
11089  * other window managers.
11090  *
11091  * Since: 3.4
11092  */
11093 void
11094 gdk_window_begin_move_drag_for_device (GdkWindow *window,
11095                                        GdkDevice *device,
11096                                        gint       button,
11097                                        gint       root_x,
11098                                        gint       root_y,
11099                                        guint32    timestamp)
11100 {
11101   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->begin_move_drag (window,
11102                                                              device, button, root_x, root_y, timestamp);
11103 }
11104
11105 /**
11106  * gdk_window_begin_move_drag:
11107  * @window: a toplevel #GdkWindow
11108  * @button: the button being used to drag
11109  * @root_x: root window X coordinate of mouse click that began the drag
11110  * @root_y: root window Y coordinate of mouse click that began the drag
11111  * @timestamp: timestamp of mouse click that began the drag
11112  *
11113  * Begins a window move operation (for a toplevel window).
11114  *
11115  * This function assumes that the drag is controlled by the
11116  * client pointer device, use gdk_window_begin_move_drag_for_device()
11117  * to begin a drag with a different device.
11118  */
11119 void
11120 gdk_window_begin_move_drag (GdkWindow *window,
11121                             gint       button,
11122                             gint       root_x,
11123                             gint       root_y,
11124                             guint32    timestamp)
11125 {
11126   GdkDeviceManager *device_manager;
11127   GdkDevice *device;
11128
11129   device_manager = gdk_display_get_device_manager (gdk_window_get_display (window));
11130   device = gdk_device_manager_get_client_pointer (device_manager);
11131   gdk_window_begin_move_drag_for_device (window, device, button, root_x, root_y, timestamp);
11132 }
11133
11134 /**
11135  * gdk_window_enable_synchronized_configure:
11136  * @window: a toplevel #GdkWindow
11137  *
11138  * Indicates that the application will cooperate with the window
11139  * system in synchronizing the window repaint with the window
11140  * manager during resizing operations. After an application calls
11141  * this function, it must call gdk_window_configure_finished() every
11142  * time it has finished all processing associated with a set of
11143  * Configure events. Toplevel GTK+ windows automatically use this
11144  * protocol.
11145  *
11146  * On X, calling this function makes @window participate in the
11147  * _NET_WM_SYNC_REQUEST window manager protocol.
11148  *
11149  * Since: 2.6
11150  **/
11151 void
11152 gdk_window_enable_synchronized_configure (GdkWindow *window)
11153 {
11154   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->enable_synchronized_configure (window);
11155 }
11156
11157 /**
11158  * gdk_window_configure_finished:
11159  * @window: a toplevel #GdkWindow
11160  * 
11161  * Signal to the window system that the application has finished
11162  * handling Configure events it has received. Window Managers can
11163  * use this to better synchronize the frame repaint with the
11164  * application. GTK+ applications will automatically call this
11165  * function when appropriate.
11166  *
11167  * This function can only be called if gdk_window_enable_synchronized_configure()
11168  * was called previously.
11169  *
11170  * Since: 2.6
11171  **/
11172 void
11173 gdk_window_configure_finished (GdkWindow *window)
11174 {
11175   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->configure_finished (window);
11176 }
11177
11178 /**
11179  * gdk_window_set_opacity:
11180  * @window: a top-level or non-native #GdkWindow
11181  * @opacity: opacity
11182  *
11183  * Set @window to render as partially transparent,
11184  * with opacity 0 being fully transparent and 1 fully opaque. (Values
11185  * of the opacity parameter are clamped to the [0,1] range.) 
11186  *
11187  * For toplevel windows this depends on support from the windowing system
11188  * that may not always be there. For instance, On X11, this works only on
11189  * X screens with a compositing manager running.
11190  *
11191  * For child windows this function only works for non-native windows.
11192  *
11193  * For setting up per-pixel alpha topelevels, see gdk_screen_get_rgba_visual(),
11194  * and for non-toplevels, see gdk_window_set_composited().
11195  *
11196  * Support for non-toplevel windows was added in 3.8.
11197  *
11198  * Since: 2.12
11199  */
11200 void
11201 gdk_window_set_opacity (GdkWindow *window,
11202                         gdouble    opacity)
11203 {
11204   if (opacity < 0)
11205     opacity = 0;
11206   else if (opacity > 1)
11207     opacity = 1;
11208
11209   window->alpha = round (opacity * 255);
11210
11211   if (window->destroyed)
11212     return;
11213
11214   if (gdk_window_has_impl (window))
11215     GDK_WINDOW_IMPL_GET_CLASS (window->impl)->set_opacity (window, opacity);
11216   else
11217     {
11218       recompute_visible_regions (window, TRUE, FALSE);
11219       gdk_window_invalidate_rect_full (window, NULL, TRUE, CLEAR_BG_ALL);
11220     }
11221 }
11222
11223 /* This function is called when the XWindow is really gone.
11224  */
11225 void
11226 gdk_window_destroy_notify (GdkWindow *window)
11227 {
11228   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->destroy_notify (window);
11229 }
11230
11231 /**
11232  * gdk_window_register_dnd:
11233  * @window: a #GdkWindow.
11234  *
11235  * Registers a window as a potential drop destination.
11236  */
11237 void
11238 gdk_window_register_dnd (GdkWindow *window)
11239 {
11240   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->register_dnd (window);
11241 }
11242
11243 /**
11244  * gdk_window_get_drag_protocol:
11245  * @window: the destination window
11246  * @target: (out) (allow-none) (transfer full): location of the window
11247  *    where the drop should happen. This may be @window or a proxy window,
11248  *    or %NULL if @window does not support Drag and Drop.
11249  *
11250  * Finds out the DND protocol supported by a window.
11251  *
11252  * Returns: the supported DND protocol.
11253  *
11254  * Since: 3.0
11255  */
11256 GdkDragProtocol
11257 gdk_window_get_drag_protocol (GdkWindow  *window,
11258                               GdkWindow **target)
11259 {
11260   g_return_val_if_fail (GDK_IS_WINDOW (window), GDK_DRAG_PROTO_NONE);
11261
11262   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)->get_drag_protocol (window, target);
11263 }
11264
11265 /**
11266  * gdk_drag_begin:
11267  * @window: the source window for this drag.
11268  * @targets: (transfer none) (element-type GdkAtom): the offered targets,
11269  *     as list of #GdkAtoms
11270  *
11271  * Starts a drag and creates a new drag context for it.
11272  * This function assumes that the drag is controlled by the
11273  * client pointer device, use gdk_drag_begin_for_device() to
11274  * begin a drag with a different device.
11275  *
11276  * This function is called by the drag source.
11277  *
11278  * Return value: (transfer full): a newly created #GdkDragContext
11279  */
11280 GdkDragContext *
11281 gdk_drag_begin (GdkWindow     *window,
11282                 GList         *targets)
11283 {
11284   GdkDeviceManager *device_manager;
11285   GdkDevice *device;
11286
11287   device_manager = gdk_display_get_device_manager (gdk_window_get_display (window));
11288   device = gdk_device_manager_get_client_pointer (device_manager);
11289
11290   return gdk_drag_begin_for_device (window, device, targets);
11291 }
11292
11293 /**
11294  * gdk_drag_begin_for_device:
11295  * @window: the source window for this drag
11296  * @device: the device that controls this drag
11297  * @targets: (transfer none) (element-type GdkAtom): the offered targets,
11298  *     as list of #GdkAtoms
11299  *
11300  * Starts a drag and creates a new drag context for it.
11301  *
11302  * This function is called by the drag source.
11303  *
11304  * Return value: (transfer full): a newly created #GdkDragContext
11305  */
11306 GdkDragContext *
11307 gdk_drag_begin_for_device (GdkWindow     *window,
11308                            GdkDevice     *device,
11309                            GList         *targets)
11310 {
11311   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)->drag_begin (window, device, targets);
11312 }
11313
11314 /**
11315  * gdk_test_render_sync:
11316  * @window: a mapped #GdkWindow
11317  *
11318  * Retrieves a pixel from @window to force the windowing
11319  * system to carry out any pending rendering commands.
11320  *
11321  * This function is intended to be used to synchronize with rendering
11322  * pipelines, to benchmark windowing system rendering operations.
11323  *
11324  * Since: 2.14
11325  **/
11326 void
11327 gdk_test_render_sync (GdkWindow *window)
11328 {
11329   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->sync_rendering (window);
11330 }
11331
11332 /**
11333  * gdk_test_simulate_key:
11334  * @window: a #GdkWindow to simulate a key event for
11335  * @x:      x coordinate within @window for the key event
11336  * @y:      y coordinate within @window for the key event
11337  * @keyval: A GDK keyboard value
11338  * @modifiers: Keyboard modifiers the event is setup with
11339  * @key_pressrelease: either %GDK_KEY_PRESS or %GDK_KEY_RELEASE
11340  *
11341  * This function is intended to be used in GTK+ test programs.
11342  * If (@x,@y) are > (-1,-1), it will warp the mouse pointer to
11343  * the given (@x,@y) coordinates within @window and simulate a
11344  * key press or release event.
11345  *
11346  * When the mouse pointer is warped to the target location, use
11347  * of this function outside of test programs that run in their
11348  * own virtual windowing system (e.g. Xvfb) is not recommended.
11349  * If (@x,@y) are passed as (-1,-1), the mouse pointer will not
11350  * be warped and @window origin will be used as mouse pointer
11351  * location for the event.
11352  *
11353  * Also, gdk_test_simulate_key() is a fairly low level function,
11354  * for most testing purposes, gtk_test_widget_send_key() is the
11355  * right function to call which will generate a key press event
11356  * followed by its accompanying key release event.
11357  *
11358  * Returns: whether all actions necessary for a key event simulation
11359  *     were carried out successfully
11360  *
11361  * Since: 2.14
11362  */
11363 gboolean
11364 gdk_test_simulate_key (GdkWindow      *window,
11365                        gint            x,
11366                        gint            y,
11367                        guint           keyval,
11368                        GdkModifierType modifiers,
11369                        GdkEventType    key_pressrelease)
11370 {
11371   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)
11372     ->simulate_key (window, x, y, keyval, modifiers, key_pressrelease);
11373 }
11374
11375 /**
11376  * gdk_test_simulate_button:
11377  * @window: a #GdkWindow to simulate a button event for
11378  * @x:      x coordinate within @window for the button event
11379  * @y:      y coordinate within @window for the button event
11380  * @button: Number of the pointer button for the event, usually 1, 2 or 3
11381  * @modifiers: Keyboard modifiers the event is setup with
11382  * @button_pressrelease: either %GDK_BUTTON_PRESS or %GDK_BUTTON_RELEASE
11383  *
11384  * This function is intended to be used in GTK+ test programs.
11385  * It will warp the mouse pointer to the given (@x,@y) coordinates
11386  * within @window and simulate a button press or release event.
11387  * Because the mouse pointer needs to be warped to the target
11388  * location, use of this function outside of test programs that
11389  * run in their own virtual windowing system (e.g. Xvfb) is not
11390  * recommended.
11391  *
11392 * Also, gdk_test_simulate_button() is a fairly low level function,
11393  * for most testing purposes, gtk_test_widget_click() is the right
11394  * function to call which will generate a button press event followed
11395  * by its accompanying button release event.
11396  *
11397  * Returns: whether all actions necessary for a button event simulation
11398  *     were carried out successfully
11399  *
11400  * Since: 2.14
11401  */
11402 gboolean
11403 gdk_test_simulate_button (GdkWindow      *window,
11404                           gint            x,
11405                           gint            y,
11406                           guint           button, /*1..3*/
11407                           GdkModifierType modifiers,
11408                           GdkEventType    button_pressrelease)
11409 {
11410   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)
11411     ->simulate_button (window, x, y, button, modifiers, button_pressrelease);
11412 }
11413
11414 /**
11415  * gdk_property_get:
11416  * @window: a #GdkWindow
11417  * @property: the property to retrieve
11418  * @type: the desired property type, or %GDK_NONE, if any type of data
11419  *   is acceptable. If this does not match the actual
11420  *   type, then @actual_format and @actual_length will
11421  *   be filled in, a warning will be printed to stderr
11422  *   and no data will be returned.
11423  * @offset: the offset into the property at which to begin
11424  *   retrieving data, in 4 byte units.
11425  * @length: the length of the data to retrieve in bytes.  Data is
11426  *   considered to be retrieved in 4 byte chunks, so @length
11427  *   will be rounded up to the next highest 4 byte boundary
11428  *   (so be careful not to pass a value that might overflow
11429  *   when rounded up).
11430  * @pdelete: if %TRUE, delete the property after retrieving the
11431  *   data.
11432  * @actual_property_type: (out) (transfer none): location to store the
11433  *   actual type of the property.
11434  * @actual_format: (out): location to store the actual return format of the
11435  *   data; either 8, 16 or 32 bits.
11436  * @actual_length: location to store the length of the retrieved data, in
11437  *   bytes.  Data returned in the 32 bit format is stored
11438  *   in a long variable, so the actual number of 32 bit
11439  *   elements should be be calculated via
11440  *   @actual_length / sizeof(glong) to ensure portability to
11441  *   64 bit systems.
11442  * @data: (out) (array length=actual_length) (transfer full): location
11443  *   to store a pointer to the data. The retrieved data should be
11444  *   freed with g_free() when you are finished using it.
11445  *
11446  * Retrieves a portion of the contents of a property. If the
11447  * property does not exist, then the function returns %FALSE,
11448  * and %GDK_NONE will be stored in @actual_property_type.
11449  *
11450  * <note>
11451  * <para>
11452  * The XGetWindowProperty() function that gdk_property_get()
11453  * uses has a very confusing and complicated set of semantics.
11454  * Unfortunately, gdk_property_get() makes the situation
11455  * worse instead of better (the semantics should be considered
11456  * undefined), and also prints warnings to stderr in cases where it
11457  * should return a useful error to the program. You are advised to use
11458  * XGetWindowProperty() directly until a replacement function for
11459  * gdk_property_get()
11460  * is provided.
11461  * </para>
11462  * </note>
11463  *
11464  * Returns: %TRUE if data was successfully received and stored
11465  *   in @data, otherwise %FALSE.
11466  */
11467 gboolean
11468 gdk_property_get (GdkWindow  *window,
11469                   GdkAtom     property,
11470                   GdkAtom     type,
11471                   gulong      offset,
11472                   gulong      length,
11473                   gint        pdelete,
11474                   GdkAtom    *actual_property_type,
11475                   gint       *actual_format_type,
11476                   gint       *actual_length,
11477                   guchar    **data)
11478 {
11479   return GDK_WINDOW_IMPL_GET_CLASS (window->impl)
11480     ->get_property (window, property, type, offset, length, pdelete,
11481                     actual_property_type, actual_format_type,
11482                     actual_length, data);
11483 }
11484
11485 /**
11486  * gdk_property_change: (skip)
11487  * @window: a #GdkWindow
11488  * @property: the property to change
11489  * @type: the new type for the property. If @mode is
11490  *   %GDK_PROP_MODE_PREPEND or %GDK_PROP_MODE_APPEND, then this
11491  *   must match the existing type or an error will occur.
11492  * @format: the new format for the property. If @mode is
11493  *   %GDK_PROP_MODE_PREPEND or %GDK_PROP_MODE_APPEND, then this
11494  *   must match the existing format or an error will occur.
11495  * @mode: a value describing how the new data is to be combined
11496  *   with the current data.
11497  * @data: the data (a <literal>guchar *</literal>
11498  *   <literal>gushort *</literal>, or <literal>gulong *</literal>,
11499  *   depending on @format), cast to a <literal>guchar *</literal>.
11500  * @nelements: the number of elements of size determined by the format,
11501  *   contained in @data.
11502  *
11503  * Changes the contents of a property on a window.
11504  */
11505 void
11506 gdk_property_change (GdkWindow    *window,
11507                      GdkAtom       property,
11508                      GdkAtom       type,
11509                      gint          format,
11510                      GdkPropMode   mode,
11511                      const guchar *data,
11512                      gint          nelements)
11513 {
11514   GDK_WINDOW_IMPL_GET_CLASS (window->impl)
11515     ->change_property (window, property, type, format, mode, data, nelements);
11516 }
11517
11518 /**
11519  * gdk_property_delete:
11520  * @window: a #GdkWindow
11521  * @property: the property to delete
11522  *
11523  * Deletes a property from a window.
11524  */
11525 void
11526 gdk_property_delete (GdkWindow *window,
11527                      GdkAtom    property)
11528 {
11529   GDK_WINDOW_IMPL_GET_CLASS (window->impl)->delete_property (window, property);
11530 }