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