summaryrefslogtreecommitdiff
path: root/src/core/stack-tracker.c
blob: 6e7960a11b1c4d8d119de7a95a0fd64a2776c24c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */

/*
 * Copyright (C) 2009 Red Hat, Inc.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as
 * published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */

#include "config.h"

#include <string.h>

#include "errors.h"
#include "frame-private.h"
#include "meta-compositor.h"
#include "screen-private.h"
#include "stack-tracker.h"
#include "util.h"

/* The complexity here comes from resolving two competing factors:
 *
 *  - We need to have a view of the stacking order that takes into
 *    account everything we have done without waiting for events
 *    back from the X server; we don't want to draw intermediate
 *    partially-stacked stack states just because we haven't received
 *    some notification yet.
 *
 *  - Only the X server has an accurate view of the complete stacking;
 *    when we make a request to restack windows, we don't know how
 *    it will affect override-redirect windows, because at any point
 *    applications may restack these windows without our involvement.
 *
 * The technique we use is that we keep three sets of information:
 *
 *  - The stacking order on the server as known from the last
 *    event we received.
 *  - A queue of stacking requests that *we* made subsequent to
 *    that last event.
 *  - A predicted stacking order, derived from applying the queued
 *    requests to the last state from the server.
 *
 * When we receive a new event: a) we compare the serial in the event to
 * the serial of the queued requests and remove any that are now
 * no longer pending b) if necessary, drop the predicted stacking
 * order to recompute it at the next opportunity.
 *
 * Possible optimizations:
 *  Keep the stacks as an array + reverse-mapping hash table to avoid
 *    linear lookups.
 *  Keep the stacks as a GList + reverse-mapping hash table to avoid
 *    linear lookups and to make restacking constant-time.
 */

typedef union _MetaStackOp MetaStackOp;

typedef enum {
  STACK_OP_ADD,
  STACK_OP_REMOVE,
  STACK_OP_RAISE_ABOVE,
  STACK_OP_LOWER_BELOW
} MetaStackOpType;

typedef enum {
  APPLY_DEFAULT = 0,
  /* Only do restacking that we can do locally without changing
   * the order of X windows. After we've received any stack
   * events from the X server, we apply the locally cached
   * ops in this mode to handle the non-X parts */
  NO_RESTACK_X_WINDOWS = 1 << 0,
  /* If the stacking operation wouldn't change the order of X
   * windows, ignore it. We use this when applying events received
   * from X so that a spontaneous ConfigureNotify (for a move, say)
   * doesn't change the stacking of X windows. */
  IGNORE_NOOP_X_RESTACK = 1 << 1
} ApplyFlags;

/* MetaStackOp represents a "stacking operation" - a change to
 * apply to a window stack. Depending on the context, it could
 * either reflect a request we have sent to the server, or a
 * notification event we received from the X server.
 */
union _MetaStackOp
{
  struct {
    MetaStackOpType type;
    gulong serial;
  } any;
  struct {
    MetaStackOpType type;
    gulong serial;
    Window window;
  } add;
  struct {
    MetaStackOpType type;
    gulong serial;
    Window window;
  } remove;
  struct {
    MetaStackOpType type;
    gulong serial;
    Window window;
    Window sibling;
  } raise_above;
  struct {
    MetaStackOpType type;
    gulong serial;
    Window window;
    Window sibling;
  } lower_below;
};

struct _MetaStackTracker
{
  MetaScreen *screen;

  /* This is the serial of the last request we made that was reflected
   * in xserver_stack.
   */
  gulong xserver_serial;

  /* A stack without any unverified operations applied.
   */
  GArray *verified_stack;

  /* This is a queue of requests we've made to change the stacking order,
   * where we haven't yet gotten a reply back from the server.
   */
  GQueue *unverified_predictions;

  /* This is how we think the stack is, based on verified_stack, and
   * on the unverified_predictions we've made subsequent to
   * verified_stack.
   */
  GArray *predicted_stack;

  /* Idle function used to sync the compositor's view of the window
   * stack up with our best guess before a frame is drawn.
   */
  guint sync_stack_idle;
};

static void
meta_stack_tracker_keep_override_redirect_on_top (MetaStackTracker *tracker);

static void
meta_stack_op_dump (MetaStackOp *op,
                    const char  *prefix,
                    const char  *suffix)
{
  switch (op->any.type)
    {
    case STACK_OP_ADD:
      meta_topic (META_DEBUG_STACK, "%sADD(%#lx; %ld)%s",
                  prefix, op->add.window, op->any.serial, suffix);
      break;
    case STACK_OP_REMOVE:
      meta_topic (META_DEBUG_STACK, "%sREMOVE(%#lx; %ld)%s",
                  prefix, op->add.window, op->any.serial, suffix);
      break;
    case STACK_OP_RAISE_ABOVE:
      meta_topic (META_DEBUG_STACK, "%sRAISE_ABOVE(%#lx, %#lx; %ld)%s",
                  prefix,
                  op->raise_above.window, op->raise_above.sibling,
                  op->any.serial,
                  suffix);
      break;
    case STACK_OP_LOWER_BELOW:
      meta_topic (META_DEBUG_STACK, "%sLOWER_BELOW(%#lx, %#lx; %ld)%s",
                  prefix,
                  op->lower_below.window, op->lower_below.sibling,
                  op->any.serial,
                  suffix);
      break;
    default:
      break;
    }
}

static void
stack_dump (GArray *stack)
{
  guint i;

  meta_push_no_msg_prefix ();
  for (i = 0; i < stack->len; i++)
    {
      meta_topic (META_DEBUG_STACK, " %#lx", g_array_index (stack, Window, i));
    }
  meta_topic (META_DEBUG_STACK, "\n");
  meta_pop_no_msg_prefix ();
}

static void
meta_stack_tracker_dump (MetaStackTracker *tracker)
{
  GList *l;

  meta_topic (META_DEBUG_STACK, "MetaStackTracker state (screen=%d)\n", tracker->screen->number);
  meta_push_no_msg_prefix ();
  meta_topic (META_DEBUG_STACK, "  xserver_serial: %ld\n", tracker->xserver_serial);
  meta_topic (META_DEBUG_STACK, "  verified_stack: ");
  stack_dump (tracker->verified_stack);
  meta_topic (META_DEBUG_STACK, "  unverified_predictions: [");
  for (l = tracker->unverified_predictions->head; l; l = l->next)
    {
      MetaStackOp *op = l->data;
      meta_stack_op_dump (op, "", l->next ? ", " : "");
    }
  meta_topic (META_DEBUG_STACK, "]\n");
  if (tracker->predicted_stack)
    {
      meta_topic (META_DEBUG_STACK, "\n  predicted_stack: ");
      stack_dump (tracker->predicted_stack);
    }
  meta_pop_no_msg_prefix ();
}

static void
meta_stack_op_free (MetaStackOp *op)
{
  g_free (op);
}

static int
find_window (GArray *window_stack,
             Window  window)
{
  guint i;

  for (i = 0; i < window_stack->len; i++)
    {
      if (g_array_index (window_stack, Window, i) == window)
        return i;
    }

  return -1;
}

/* Returns TRUE if stack was changed */
static gboolean
move_window_above (GArray     *stack,
                   Window      window,
                   int         old_pos,
                   int         above_pos,
                   ApplyFlags  apply_flags)
{
  int i;
  gboolean can_restack_this_window = (apply_flags & NO_RESTACK_X_WINDOWS) == 0;

  if (old_pos < above_pos)
    {
      if ((apply_flags & IGNORE_NOOP_X_RESTACK) != 0)
        {
        }

      for (i = old_pos; i < above_pos; i++)
        {
          if (!can_restack_this_window)
            break;

          g_array_index (stack, Window, i) = g_array_index (stack, Window, i + 1);
        }

      g_array_index (stack, Window, i) = window;

      return i != old_pos;
    }
  else if (old_pos > above_pos + 1)
    {
      if ((apply_flags & IGNORE_NOOP_X_RESTACK) != 0)
        {
        }

      for (i = old_pos; i > above_pos + 1; i--)
        {
          if (!can_restack_this_window)
            break;

          g_array_index (stack, Window, i) = g_array_index (stack, Window, i - 1);
        }

      g_array_index (stack, Window, i) = window;

      return i != old_pos;
    }
  else
    return FALSE;
}

/* Returns TRUE if stack was changed */
static gboolean
meta_stack_op_apply (MetaStackOp *op,
                     GArray      *stack,
                     ApplyFlags   apply_flags)
{
  switch (op->any.type)
    {
    case STACK_OP_ADD:
      {
        int old_pos;

        if ((apply_flags & NO_RESTACK_X_WINDOWS) != 0)
          return FALSE;

        old_pos = find_window (stack, op->add.window);

        if (old_pos >= 0)
          {
            meta_topic (META_DEBUG_STACK,
                        "STACK_OP_ADD: window %#lx already in stack",
                        op->add.window);
            return FALSE;
          }

        g_array_append_val (stack, op->add.window);
        return TRUE;
      }
      break;
    case STACK_OP_REMOVE:
      {
        int old_pos;

        if ((apply_flags & NO_RESTACK_X_WINDOWS) != 0)
          return FALSE;

        old_pos = find_window (stack, op->remove.window);

        if (old_pos < 0)
          {
            meta_topic (META_DEBUG_STACK,
                        "STACK_OP_REMOVE: window %#lx not in stack",
                        op->remove.window);
            return FALSE;
          }

        g_array_remove_index (stack, old_pos);
        return TRUE;
      }
      break;
    case STACK_OP_RAISE_ABOVE:
      {
        int old_pos = find_window (stack, op->raise_above.window);
        int above_pos;
        if (old_pos < 0)
          {
            meta_topic (META_DEBUG_STACK,
                        "STACK_OP_RAISE_ABOVE: window %#lx not in stack",
                        op->raise_above.window);
            return FALSE;
          }

        if (op->raise_above.sibling != None)
          {
            above_pos = find_window (stack, op->raise_above.sibling);
            if (above_pos < 0)
              {
                meta_topic (META_DEBUG_STACK,
                            "STACK_OP_RAISE_ABOVE: sibling window %#lx not in stack",
                            op->raise_above.sibling);
                return FALSE;
              }
          }
        else
          {
            above_pos = -1;
          }

        return move_window_above (stack, op->raise_above.window, old_pos,
                                  above_pos, apply_flags);
      }
      break;
    case STACK_OP_LOWER_BELOW:
      {
        int old_pos = find_window (stack, op->lower_below.window);
        int above_pos;
        if (old_pos < 0)
          {
            meta_topic (META_DEBUG_STACK,
                        "STACK_OP_LOWER_BELOW: window %#lx not in stack",
                        op->lower_below.window);
            return FALSE;
          }

        if (op->lower_below.sibling != None)
          {
            int below_pos = find_window (stack, op->lower_below.sibling);
            if (below_pos < 0)
              {
                meta_topic (META_DEBUG_STACK,
                            "STACK_OP_LOWER_BELOW: sibling window %#lx not in stack",
                            op->lower_below.sibling);
                return FALSE;
              }

            above_pos = below_pos - 1;
          }
        else
          {
            above_pos = stack->len - 1;
          }

        return move_window_above (stack, op->lower_below.window, old_pos,
                                  above_pos, apply_flags);
      }
      break;
    default:
      break;
    }

  g_assert_not_reached ();
  return FALSE;
}

static GArray *
copy_stack (GArray *stack)
{
  GArray *copy = g_array_sized_new (FALSE, FALSE, sizeof (Window), stack->len);

  g_array_set_size (copy, stack->len);

  memcpy (copy->data, stack->data, sizeof (Window) * stack->len);

  return copy;
}

static void
query_xserver_stack (MetaStackTracker *tracker)
{
  MetaScreen *screen = tracker->screen;
  Window ignored1, ignored2;
  Window *children;
  guint n_children;
  guint i;

  tracker->xserver_serial = XNextRequest (screen->display->xdisplay);

  XQueryTree (screen->display->xdisplay,
              screen->xroot,
              &ignored1, &ignored2, &children, &n_children);

  tracker->verified_stack = g_array_sized_new (FALSE, FALSE, sizeof (Window), n_children);
  g_array_set_size (tracker->verified_stack, n_children);

  for (i = 0; i < n_children; i++)
    g_array_index (tracker->verified_stack, Window, i) = children[i];

  XFree (children);
}

MetaStackTracker *
meta_stack_tracker_new (MetaScreen *screen)
{
  MetaStackTracker *tracker;

  tracker = g_new0 (MetaStackTracker, 1);
  tracker->screen = screen;

  query_xserver_stack (tracker);

  tracker->unverified_predictions = g_queue_new ();

  meta_stack_tracker_dump (tracker);

  return tracker;
}

void
meta_stack_tracker_free (MetaStackTracker *tracker)
{
  if (tracker->sync_stack_idle)
    g_source_remove (tracker->sync_stack_idle);

  g_array_free (tracker->verified_stack, TRUE);
  if (tracker->predicted_stack)
    g_array_free (tracker->predicted_stack, TRUE);

  g_queue_free_full (tracker->unverified_predictions, (GDestroyNotify) meta_stack_op_free);
  tracker->unverified_predictions = NULL;

  g_free (tracker);
}

static void
stack_tracker_apply_prediction (MetaStackTracker *tracker,
                                MetaStackOp      *op)
{
  meta_stack_op_dump (op, "Predicting: ", "\n");
  g_queue_push_tail (tracker->unverified_predictions, op);

  if (!tracker->predicted_stack ||
      meta_stack_op_apply (op, tracker->predicted_stack, APPLY_DEFAULT))
    meta_stack_tracker_queue_sync_stack (tracker);

  meta_stack_tracker_dump (tracker);
}

void
meta_stack_tracker_record_add (MetaStackTracker *tracker,
                               Window            window,
                               gulong            serial)
{
  MetaStackOp *op = g_new0 (MetaStackOp, 1);

  op->any.type = STACK_OP_ADD;
  op->any.serial = serial;
  op->add.window = window;

  stack_tracker_apply_prediction (tracker, op);
}

void
meta_stack_tracker_record_remove (MetaStackTracker *tracker,
                                  Window            window,
                                  gulong            serial)
{
  MetaStackOp *op = g_new0 (MetaStackOp, 1);

  op->any.type = STACK_OP_REMOVE;
  op->any.serial = serial;
  op->remove.window = window;

  stack_tracker_apply_prediction (tracker, op);
}

static void
meta_stack_tracker_record_raise_above (MetaStackTracker *tracker,
                                       Window            window,
                                       Window            sibling,
                                       gulong            serial)
{
  MetaStackOp *op = g_new0 (MetaStackOp, 1);

  op->any.type = STACK_OP_RAISE_ABOVE;
  op->any.serial = serial;
  op->raise_above.window = window;
  op->raise_above.sibling = sibling;

  stack_tracker_apply_prediction (tracker, op);
}

static void
meta_stack_tracker_record_lower_below (MetaStackTracker *tracker,
                                       Window            window,
                                       Window            sibling,
                                       gulong            serial)
{
  MetaStackOp *op = g_new0 (MetaStackOp, 1);

  op->any.type = STACK_OP_LOWER_BELOW;
  op->any.serial = serial;
  op->lower_below.window = window;
  op->lower_below.sibling = sibling;

  stack_tracker_apply_prediction (tracker, op);
}

static void
stack_tracker_event_received (MetaStackTracker *tracker,
                              MetaStackOp      *op)
{
  gboolean need_sync = FALSE;

  /* If the event is older than our initial query, then it's
   * already included in our tree. Just ignore it.
   */
  if (op->any.serial < tracker->xserver_serial)
    return;

  meta_stack_op_dump (op, "Stack op event received: ", "\n");

  /* First we apply any operations that we have queued up that depended
   * on X operations *older* than what we received .. those operations
   * must have been ignored by the X server, so we just apply the
   * operations we have as best as possible while not moving windows.
   */
  while (tracker->unverified_predictions->head)
    {
      MetaStackOp *queued_op = tracker->unverified_predictions->head->data;

      if (queued_op->any.serial >= op->any.serial)
        break;

      meta_stack_op_apply (queued_op, tracker->verified_stack,
                           NO_RESTACK_X_WINDOWS);

      g_queue_pop_head (tracker->unverified_predictions);
      meta_stack_op_free (queued_op);
      need_sync = TRUE;
    }

  /* Then we apply the received event. If it's a spontaneous event
   * based on stacking we didn't trigger, this is the only handling. If we
   * triggered it, we do the X restacking here.
   */
  if (meta_stack_op_apply (op, tracker->verified_stack, IGNORE_NOOP_X_RESTACK))
    need_sync = TRUE;

  /* What is left to process is the prediction corresponding to the event
   * (if any).
   */
  while (tracker->unverified_predictions->head)
    {
      MetaStackOp *queued_op = tracker->unverified_predictions->head->data;

      if (queued_op->any.serial > op->any.serial)
        break;

      meta_stack_op_apply (queued_op, tracker->verified_stack,
                           NO_RESTACK_X_WINDOWS);

      g_queue_pop_head (tracker->unverified_predictions);
      meta_stack_op_free (queued_op);
      need_sync = TRUE;
    }

  if (need_sync)
    {
      if (tracker->predicted_stack)
        {
          g_array_free (tracker->predicted_stack, TRUE);
          tracker->predicted_stack = NULL;
        }

      meta_stack_tracker_queue_sync_stack (tracker);
    }

  meta_stack_tracker_dump (tracker);
}

void
meta_stack_tracker_create_event (MetaStackTracker    *tracker,
                                 XCreateWindowEvent  *event)
{
  MetaStackOp op;

  op.any.type = STACK_OP_ADD;
  op.any.serial = event->serial;
  op.add.window = event->window;

  stack_tracker_event_received (tracker, &op);
}

void
meta_stack_tracker_destroy_event (MetaStackTracker    *tracker,
                                  XDestroyWindowEvent *event)
{
  MetaStackOp op;

  op.any.type = STACK_OP_REMOVE;
  op.any.serial = event->serial;
  op.remove.window = event->window;

  stack_tracker_event_received (tracker, &op);
}

void
meta_stack_tracker_reparent_event (MetaStackTracker    *tracker,
                                   XReparentEvent      *event)
{
  if (event->parent == event->event)
    {
      MetaStackOp op;

      op.any.type = STACK_OP_ADD;
      op.any.serial = event->serial;
      op.add.window = event->window;

      stack_tracker_event_received (tracker, &op);
    }
  else
    {
      MetaStackOp op;

      op.any.type = STACK_OP_REMOVE;
      op.any.serial = event->serial;
      op.remove.window = event->window;

      stack_tracker_event_received (tracker, &op);
    }
}

void
meta_stack_tracker_configure_event (MetaStackTracker    *tracker,
                                    XConfigureEvent     *event)
{
  MetaStackOp op;

  op.any.type = STACK_OP_RAISE_ABOVE;
  op.any.serial = event->serial;
  op.raise_above.window = event->window;
  op.raise_above.sibling = event->above;

  stack_tracker_event_received (tracker, &op);
}

/**
 * meta_stack_tracker_get_stack:
 * @tracker: a #MetaStackTracker
 * @windows: location to store list of windows, or %NULL
 * @n_windows: location to store count of windows, or %NULL
 *
 * Returns the most current view we have of the stacking order
 * of the children of the root window. The returned array contains
 * everything: InputOnly windows, override-redirect windows,
 * hidden windows, etc. Some of these will correspond to MetaWindow
 * objects, others won't.
 *
 * Assuming that no other clients have made requests that change
 * the stacking order since we last received a notification, the
 * returned list of windows is exactly that you'd get as the
 * children when calling XQueryTree() on the root window.
 */
void
meta_stack_tracker_get_stack (MetaStackTracker *tracker,
                              Window          **windows,
                              int              *n_windows)
{
  GArray *stack;

  if (tracker->unverified_predictions->length == 0)
    {
      stack = tracker->verified_stack;
    }
  else
    {
      if (tracker->predicted_stack == NULL)
        {
          GList *l;

          tracker->predicted_stack = copy_stack (tracker->verified_stack);
          for (l = tracker->unverified_predictions->head; l; l = l->next)
            {
              MetaStackOp *op = l->data;
              meta_stack_op_apply (op, tracker->predicted_stack, APPLY_DEFAULT);
            }
        }

      stack = tracker->predicted_stack;
    }

  if (windows)
    *windows = (Window *)stack->data;
  if (n_windows)
    *n_windows = stack->len;
}

/**
 * meta_stack_tracker_sync_stack:
 * @tracker: a #MetaStackTracker
 *
 * Informs the compositor of the current stacking order of windows,
 * based on the predicted view maintained by the #MetaStackTracker.
 */
void
meta_stack_tracker_sync_stack (MetaStackTracker *tracker)
{
  GList *meta_windows;
  Window *windows;
  int n_windows;
  int i;

  if (tracker->sync_stack_idle)
    {
      g_source_remove (tracker->sync_stack_idle);
      tracker->sync_stack_idle = 0;
    }

  meta_stack_tracker_keep_override_redirect_on_top (tracker);

  meta_stack_tracker_get_stack (tracker, &windows, &n_windows);

  meta_windows = NULL;
  for (i = 0; i < n_windows; i++)
    {
      MetaWindow *meta_window;
      MetaFrame *frame;

      meta_window = meta_display_lookup_x_window (tracker->screen->display,
                                                  windows[i]);

      if (meta_window == NULL)
        continue;

      frame = meta_window->frame;

      /* When mapping back from xwindow to MetaWindow we have to be a bit careful;
       * children of the root could include unmapped windows created by toolkits
       * for internal purposes, including ones that we have registered in our
       * XID => window table. (Wine uses a toplevel for _NET_WM_USER_TIME_WINDOW;
       * see window-prop.c:reload_net_wm_user_time_window() for registration.)
       */
      if (windows[i] == meta_window->xwindow || (frame && windows[i] == frame->xwindow))
        {
          meta_windows = g_list_prepend (meta_windows, meta_window);
        }
    }

  meta_compositor_sync_stack (tracker->screen->display->compositor, meta_windows);
  g_list_free (meta_windows);
}

static gboolean
stack_tracker_sync_stack_idle (gpointer data)
{
  meta_stack_tracker_sync_stack (data);

  return FALSE;
}

/**
 * meta_stack_tracker_queue_sync_stack:
 * @tracker: a #MetaStackTracker
 *
 * Queue informing the compositor of the new stacking order before the
 * next redraw. (See meta_stack_tracker_sync_stack()). This is called
 * internally when the stack of X windows changes, but also needs be
 * called directly when we an undecorated window is first shown or
 * withdrawn since the compositor's stacking order (which contains only
 * the windows that have a corresponding MetaWindow) will change without
 * any change to the stacking order of the X windows, if we are creating
 * or destroying MetaWindows.
 */
void
meta_stack_tracker_queue_sync_stack (MetaStackTracker *tracker)
{
  if (tracker->sync_stack_idle == 0)
    {
      tracker->sync_stack_idle = g_idle_add_full (META_PRIORITY_BEFORE_REDRAW,
                                                  stack_tracker_sync_stack_idle,
                                                  tracker, NULL);
    }
}

static void
meta_stack_tracker_lower_below (MetaStackTracker *tracker,
                                Window            window,
                                Window            sibling)
{
  MetaDisplay *display;
  XWindowChanges changes;
  guint changes_mask;
  gulong serial;

  display = tracker->screen->display;

  meta_error_trap_push (display);

  changes.sibling = sibling;
  changes.stack_mode = changes.sibling ? Below : Above;
  changes_mask = (changes.sibling ? CWSibling : 0) | CWStackMode;

  serial = XNextRequest (display->xdisplay);
  XConfigureWindow (display->xdisplay, window, changes_mask, &changes);

  meta_error_trap_pop (tracker->screen->display);

  meta_stack_tracker_record_lower_below (tracker, window, sibling, serial);
}

static void
meta_stack_tracker_raise_above (MetaStackTracker *tracker,
                                Window            window,
                                Window            sibling)
{
  MetaDisplay *display;
  XWindowChanges changes;
  guint changes_mask;
  gulong serial;

  display = tracker->screen->display;

  meta_error_trap_push (display);

  changes.sibling = sibling;
  changes.stack_mode = changes.sibling ? Above : Below;
  changes_mask = (changes.sibling ? CWSibling : 0) | CWStackMode;

  serial = XNextRequest (display->xdisplay);
  XConfigureWindow (display->xdisplay, window, changes_mask, &changes);

  meta_error_trap_pop (tracker->screen->display);

  meta_stack_tracker_record_raise_above (tracker, window, sibling, serial);
}

void
meta_stack_tracker_lower (MetaStackTracker *tracker,
                          Window            window)
{
  meta_stack_tracker_raise_above (tracker, window, None);
}

static void
meta_stack_tracker_keep_override_redirect_on_top (MetaStackTracker *tracker)
{
  MetaWindow *window;
  Window *stack;
  int n_windows, i;
  int topmost_non_or;

  meta_stack_tracker_get_stack (tracker, &stack, &n_windows);

  for (i = n_windows - 1; i >= 0; i--)
    {
      window = meta_display_lookup_x_window (tracker->screen->display, stack[i]);
      if (window && window->layer != META_LAYER_OVERRIDE_REDIRECT)
        break;
    }

  topmost_non_or = i;

  for (i -= 1; i >= 0; i--)
    {
      window = meta_display_lookup_x_window (tracker->screen->display, stack[i]);
      if (window && window->layer == META_LAYER_OVERRIDE_REDIRECT)
        {
          meta_stack_tracker_raise_above (tracker, stack[i], stack[topmost_non_or]);
          meta_stack_tracker_get_stack (tracker, &stack, &n_windows);
          topmost_non_or -= 1;
        }
    }
}


void
meta_stack_tracker_restack_managed (MetaStackTracker *tracker,
                                    const Window     *managed,
                                    int               n_managed)
{
  MetaDisplay *display;
  Window *windows;
  int n_windows;
  int old_pos;
  int new_pos;

  if (n_managed == 0)
    return;

  display = tracker->screen->display;

  meta_stack_tracker_get_stack (tracker, &windows, &n_windows);

  /* If the top window has to be restacked, we don't want to move it to the very
   * top of the stack, since apps expect override-redirect windows to stay near
   * the top of the X stack; we instead move it above all managed windows (or
   * above the guard window if there are no non-hidden managed windows.)
   */
  old_pos = n_windows - 1;
  for (old_pos = n_windows - 1; old_pos >= 0; old_pos--)
    {
      MetaWindow *old_window;

      old_window = meta_display_lookup_x_window (display, windows[old_pos]);

      if (old_window && !old_window->override_redirect && !old_window->unmanaging)
        break;
    }

  g_assert (old_pos >= 0);

  new_pos = n_managed - 1;
  if (managed[new_pos] != windows[old_pos])
    {
      /* Move the first managed window in the new stack above
       * all managed windows
       */
      meta_stack_tracker_raise_above (tracker, managed[new_pos], windows[old_pos]);
      meta_stack_tracker_get_stack (tracker, &windows, &n_windows);
      /* Moving managed[new_pos] above windows[old_pos], moves
       * the window at old_pos down by one
       */
    }

  old_pos--;
  new_pos--;

  while (old_pos >= 0 && new_pos >= 0)
    {
      MetaWindow *old_window;

      if (windows[old_pos] == managed[new_pos])
        {
          old_pos--;
          new_pos--;
          continue;
        }

      old_window = meta_display_lookup_x_window (display, windows[old_pos]);
      if (!old_window || old_window->override_redirect || old_window->unmanaging)
        {
          old_pos--;
          continue;
        }

      meta_stack_tracker_lower_below (tracker, managed[new_pos], managed[new_pos + 1]);
      meta_stack_tracker_get_stack (tracker, &windows, &n_windows);
      /* Moving managed[new_pos] above windows[old_pos] moves the window
       * at old_pos down by one, we'll examine it again to see if it
       * matches the next new window
       */
      old_pos--;
      new_pos--;
    }

  while (new_pos > 0)
    {
      meta_stack_tracker_lower_below (tracker, managed[new_pos], managed[new_pos - 1]);
      new_pos--;
    }
}

void
meta_stack_tracker_restack_at_bottom (MetaStackTracker *tracker,
                                      const Window     *new_order,
                                      int               n_new_order)
{
  Window *windows;
  int n_windows;
  int pos;

  meta_stack_tracker_get_stack (tracker, &windows, &n_windows);

  for (pos = 0; pos < n_new_order; pos++)
    {
      if (pos >= n_windows || windows[pos] != new_order[pos])
        {
          if (pos == 0)
            meta_stack_tracker_lower (tracker, new_order[pos]);
          else
            meta_stack_tracker_raise_above (tracker, new_order[pos], new_order[pos - 1]);

          meta_stack_tracker_get_stack (tracker, &windows, &n_windows);
        }
    }
}