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