summaryrefslogtreecommitdiff
path: root/src/core/workspace.c
blob: b638177a880674fa68eb6a250916f06a39055b57 (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
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */

/*
 * Copyright (C) 2001 Havoc Pennington
 * Copyright (C) 2003 Rob Adams
 * Copyright (C) 2004, 2005 Elijah Newren
 *
 * 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/>.
 */

/**
 * SECTION:workspace
 * @title:MetaWorkspace
 * @short_description:Workspaces
 *
 * A workspace is a set of windows which all live on the same
 * screen.  (You may also see the name "desktop" around the place,
 * which is the EWMH's name for the same thing.)  Only one workspace
 * of a screen may be active at once; all windows on all other workspaces
 * are unmapped.
 */

#include "config.h"

#include "meta/workspace.h"

#include <X11/Xatom.h>
#include <string.h>

#include "backends/meta-backend-private.h"
#include "backends/meta-cursor-tracker-private.h"
#include "backends/meta-logical-monitor.h"
#include "cogl/cogl.h"
#include "compositor/compositor-private.h"
#include "core/boxes-private.h"
#include "core/meta-workspace-manager-private.h"
#include "core/workspace-private.h"
#include "meta/meta-x11-errors.h"
#include "meta/prefs.h"
#include "x11/meta-x11-display-private.h"

void meta_workspace_queue_calc_showing   (MetaWorkspace *workspace);
static void focus_ancestor_or_mru_window (MetaWorkspace *workspace,
                                          MetaWindow    *not_this_one,
                                          guint32        timestamp);
static MetaWindow * get_pointer_window (MetaWorkspace *workspace,
                                        MetaWindow    *not_this_one);

G_DEFINE_TYPE (MetaWorkspace, meta_workspace, G_TYPE_OBJECT);

enum
{
  PROP_0,

  PROP_N_WINDOWS,
  PROP_WORKSPACE_INDEX,
  PROP_ACTIVE,

  PROP_LAST,
};

static GParamSpec *obj_props[PROP_LAST];

enum
{
  WINDOW_ADDED,
  WINDOW_REMOVED,

  LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

typedef struct _MetaWorkspaceLogicalMonitorData
{
  GList *logical_monitor_region;
  MetaRectangle logical_monitor_work_area;
} MetaWorkspaceLogicalMonitorData;

typedef struct _MetaWorkspaceFocusableAncestorData
{
  MetaWorkspace *workspace;
  MetaWindow *out_window;
} MetaWorkspaceFocusableAncestorData;

static MetaWorkspaceLogicalMonitorData *
meta_workspace_get_logical_monitor_data (MetaWorkspace      *workspace,
                                         MetaLogicalMonitor *logical_monitor)
{
  if (!workspace->logical_monitor_data)
    return NULL;
  return g_hash_table_lookup (workspace->logical_monitor_data, logical_monitor);
}

static void
workspace_logical_monitor_data_free (MetaWorkspaceLogicalMonitorData *data)
{
  g_clear_pointer (&data->logical_monitor_region,
                   meta_rectangle_free_list_and_elements);
  g_free (data);
}

static MetaWorkspaceLogicalMonitorData *
meta_workspace_ensure_logical_monitor_data (MetaWorkspace      *workspace,
                                            MetaLogicalMonitor *logical_monitor)
{
  MetaWorkspaceLogicalMonitorData *data;

  data = meta_workspace_get_logical_monitor_data (workspace, logical_monitor);
  if (data)
    return data;

  if (!workspace->logical_monitor_data)
    {
      workspace->logical_monitor_data =
        g_hash_table_new_full (g_direct_hash,
                               g_direct_equal,
                               NULL,
                               (GDestroyNotify) workspace_logical_monitor_data_free);
    }

  data = g_new0 (MetaWorkspaceLogicalMonitorData, 1);
  g_hash_table_insert (workspace->logical_monitor_data, logical_monitor, data);

  return data;
}

static void
meta_workspace_clear_logical_monitor_data (MetaWorkspace *workspace)
{
  g_clear_pointer (&workspace->logical_monitor_data, g_hash_table_destroy);
}

static void
meta_workspace_finalize (GObject *object)
{
  /* Actual freeing done in meta_workspace_remove() for now */
  G_OBJECT_CLASS (meta_workspace_parent_class)->finalize (object);
}

static void
meta_workspace_set_property (GObject      *object,
                             guint         prop_id,
                             const GValue *value,
                             GParamSpec   *pspec)
{
  switch (prop_id)
    {
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
meta_workspace_get_property (GObject      *object,
                             guint         prop_id,
                             GValue       *value,
                             GParamSpec   *pspec)
{
  MetaWorkspace *ws = META_WORKSPACE (object);

  switch (prop_id)
    {
    case PROP_N_WINDOWS:
      /*
       * This is reliable, but not very efficient; should we store
       * the list length ?
       */
      g_value_set_uint (value, g_list_length (ws->windows));
      break;
    case PROP_WORKSPACE_INDEX:
      g_value_set_uint (value, meta_workspace_index (ws));
      break;
    case PROP_ACTIVE:
      g_value_set_boolean (value, ws->manager->active_workspace == ws);
      break;
    default:
      G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
      break;
    }
}

static void
meta_workspace_class_init (MetaWorkspaceClass *klass)
{
  GObjectClass *object_class = G_OBJECT_CLASS (klass);
  object_class->finalize     = meta_workspace_finalize;
  object_class->get_property = meta_workspace_get_property;
  object_class->set_property = meta_workspace_set_property;

  signals[WINDOW_ADDED] = g_signal_new ("window-added",
                                        G_TYPE_FROM_CLASS (klass),
                                        G_SIGNAL_RUN_LAST,
                                        0,
                                        NULL, NULL, NULL,
                                        G_TYPE_NONE, 1,
                                        META_TYPE_WINDOW);
  signals[WINDOW_REMOVED] = g_signal_new ("window-removed",
                                          G_TYPE_FROM_CLASS (klass),
                                          G_SIGNAL_RUN_LAST,
                                          0,
                                          NULL, NULL, NULL,
                                          G_TYPE_NONE, 1,
                                          META_TYPE_WINDOW);

  obj_props[PROP_N_WINDOWS] = g_param_spec_uint ("n-windows",
                                                 "N Windows",
                                                 "Number of windows",
                                                 0, G_MAXUINT, 0,
                                                 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  obj_props[PROP_WORKSPACE_INDEX] = g_param_spec_uint ("workspace-index",
                                                       "Workspace index",
                                                       "The workspace's index",
                                                       0, G_MAXUINT, 0,
                                                       G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);
  obj_props[PROP_ACTIVE] = g_param_spec_boolean ("active",
                                                 "Active",
                                                 "Whether the workspace is currently active",
                                                 FALSE,
                                                 G_PARAM_READABLE | G_PARAM_STATIC_STRINGS);

  g_object_class_install_properties (object_class, PROP_LAST, obj_props);
}

static void
meta_workspace_init (MetaWorkspace *workspace)
{
}

MetaWorkspace *
meta_workspace_new (MetaWorkspaceManager *workspace_manager)
{
  MetaDisplay *display = workspace_manager->display;
  MetaWorkspace *workspace;
  GSList *windows, *l;

  workspace = g_object_new (META_TYPE_WORKSPACE, NULL);

  workspace->display = display;
  workspace->manager = workspace_manager;

  workspace_manager->workspaces =
    g_list_append (workspace_manager->workspaces, workspace);
  workspace->windows = NULL;
  workspace->mru_list = NULL;

  workspace->work_areas_invalid = TRUE;
  workspace->work_area_screen.x = 0;
  workspace->work_area_screen.y = 0;
  workspace->work_area_screen.width = 0;
  workspace->work_area_screen.height = 0;

  workspace->screen_region = NULL;
  workspace->screen_edges = NULL;
  workspace->monitor_edges = NULL;
  workspace->list_containing_self = g_list_prepend (NULL, workspace);

  workspace->builtin_struts = NULL;
  workspace->all_struts = NULL;

  workspace->showing_desktop = FALSE;

  /* make sure sticky windows are in our mru_list */
  windows = meta_display_list_windows (display, META_LIST_SORTED);
  for (l = windows; l; l = l->next)
    if (meta_window_located_on_workspace (l->data, workspace))
      meta_workspace_add_window (workspace, l->data);
  g_slist_free (windows);

  return workspace;
}

/**
 * workspace_free_all_struts:
 * @workspace: The workspace.
 *
 * Frees the combined struts list of a workspace.
 */
static void
workspace_free_all_struts (MetaWorkspace *workspace)
{
  if (workspace->all_struts == NULL)
    return;

  g_slist_free_full (workspace->all_struts, g_free);
  workspace->all_struts = NULL;
}

/**
 * workspace_free_builtin_struts:
 * @workspace: The workspace.
 *
 * Frees the struts list set with meta_workspace_set_builtin_struts
 */
static void
workspace_free_builtin_struts (MetaWorkspace *workspace)
{
  if (workspace->builtin_struts == NULL)
    return;

  g_slist_free_full (workspace->builtin_struts, g_free);
  workspace->builtin_struts = NULL;
}

/* Ensure that the workspace is empty by making sure that
 * all of our windows are on-all-workspaces. */
static void
assert_workspace_empty (MetaWorkspace *workspace)
{
  GList *l;
  for (l = workspace->windows; l != NULL; l = l->next)
    {
      MetaWindow *window = l->data;
      g_assert (window->on_all_workspaces);
    }
}

void
meta_workspace_remove (MetaWorkspace *workspace)
{
  MetaWorkspaceManager *manager = workspace->display->workspace_manager;

  g_return_if_fail (workspace != manager->active_workspace);

  assert_workspace_empty (workspace);

  manager->workspaces =
    g_list_remove (manager->workspaces, workspace);

  meta_workspace_clear_logical_monitor_data (workspace);

  g_list_free (workspace->mru_list);
  g_list_free (workspace->list_containing_self);

  workspace_free_builtin_struts (workspace);

  /* screen.c:update_num_workspaces(), which calls us, removes windows from
   * workspaces first, which can cause the workareas on the workspace to be
   * invalidated (and hence for struts/regions/edges to be freed).
   * So, no point trying to double free it; that causes a crash
   * anyway.  #361804.
   */

  if (!workspace->work_areas_invalid)
    {
      workspace_free_all_struts (workspace);
      meta_rectangle_free_list_and_elements (workspace->screen_region);
      meta_rectangle_free_list_and_elements (workspace->screen_edges);
      meta_rectangle_free_list_and_elements (workspace->monitor_edges);
    }

  g_object_unref (workspace);

  /* don't bother to reset names, pagers can just ignore
   * extra ones
   */
}

static void
update_workspace_default_focus (MetaWorkspace *workspace,
                                MetaWindow    *not_this_one)
{
  g_autoptr (GSList) windows = NULL;
  GSList *l;

  windows = meta_display_list_windows (workspace->display, META_LIST_DEFAULT);
  for (l = windows; l; l = l->next)
    {
      MetaWindow *window = META_WINDOW (l->data);

      if (meta_window_located_on_workspace (window, workspace) &&
          window != not_this_one)
        meta_window_update_appears_focused (window);
    }
}

void
meta_workspace_add_window (MetaWorkspace *workspace,
                           MetaWindow    *window)
{
  MetaWorkspaceManager *workspace_manager;

  g_return_if_fail (g_list_find (workspace->mru_list, window) == NULL);

  COGL_TRACE_BEGIN_SCOPED (MetaWorkspaceAddWindow,
                           "Workspace (add window)");

  workspace_manager = workspace->display->workspace_manager;

  workspace->mru_list = g_list_prepend (workspace->mru_list, window);

  workspace->windows = g_list_prepend (workspace->windows, window);

  if (window->struts)
    {
      meta_topic (META_DEBUG_WORKAREA,
                  "Invalidating work area of workspace %d since we're adding window %s to it",
                  meta_workspace_index (workspace), window->desc);
      meta_workspace_invalidate_work_area (workspace);
    }

  if (workspace != workspace_manager->active_workspace)
    update_workspace_default_focus (workspace, window);

  g_signal_emit (workspace, signals[WINDOW_ADDED], 0, window);
  g_object_notify_by_pspec (G_OBJECT (workspace), obj_props[PROP_N_WINDOWS]);
}

void
meta_workspace_remove_window (MetaWorkspace *workspace,
                              MetaWindow    *window)
{
  MetaWorkspaceManager *workspace_manager = workspace->display->workspace_manager;

  COGL_TRACE_BEGIN_SCOPED (MetaWorkspaceRemoveWindow,
                           "Workspace (remove window)");

  workspace->windows = g_list_remove (workspace->windows, window);

  workspace->mru_list = g_list_remove (workspace->mru_list, window);
  g_assert (g_list_find (workspace->mru_list, window) == NULL);

  if (window->struts)
    {
      meta_topic (META_DEBUG_WORKAREA,
                  "Invalidating work area of workspace %d since we're removing window %s from it",
                  meta_workspace_index (workspace), window->desc);
      meta_workspace_invalidate_work_area (workspace);
    }

  if (workspace != workspace_manager->active_workspace)
    update_workspace_default_focus (workspace, window);

  g_signal_emit (workspace, signals[WINDOW_REMOVED], 0, window);
  g_object_notify (G_OBJECT (workspace), "n-windows");
}

void
meta_workspace_relocate_windows (MetaWorkspace *workspace,
                                 MetaWorkspace *new_home)
{
  GList *copy, *l;

  g_return_if_fail (workspace != new_home);

  /* can't modify list we're iterating over */
  copy = g_list_copy (workspace->windows);

  for (l = copy; l != NULL; l = l->next)
    {
      MetaWindow *window = l->data;

      if (!window->on_all_workspaces)
        meta_window_change_workspace (window, new_home);
    }

  g_list_free (copy);

  assert_workspace_empty (workspace);
}

void
meta_workspace_queue_calc_showing  (MetaWorkspace *workspace)
{
  GList *l;

  for (l = workspace->windows; l != NULL; l = l->next)
    meta_window_queue (l->data, META_QUEUE_CALC_SHOWING);
}

static void
workspace_switch_sound (MetaWorkspace *from,
                        MetaWorkspace *to)
{
  MetaSoundPlayer *player;
  MetaWorkspaceLayout layout;
  int n_workspaces;
  int from_idx, to_idx;
  int i;
  int x, y;
  const char *sound_name;

  n_workspaces = meta_workspace_manager_get_n_workspaces (from->manager);
  from_idx = meta_workspace_index(from);
  to_idx = meta_workspace_index(to);

  meta_workspace_manager_calc_workspace_layout (from->manager,
                                                n_workspaces,
                                                from_idx,
                                                &layout);

  for (i = 0; i < n_workspaces; i++)
    {
      if (layout.grid[i] == to_idx)
        break;
    }

  if (i >= n_workspaces)
    {
      g_warning ("Failed to find destination workspace in layout");
      goto finish;
    }

  y = i / layout.cols;
  x = i % layout.cols;

  /* We priorize horizontal over vertical movements here. The
     rationale for this is that horizontal movements are probably more
     interesting for sound effects because speakers are usually
     positioned on a horizontal and not a vertical axis. i.e. your
     spatial "Woosh!" effects will easily be able to encode horizontal
     movement but not such much vertical movement. */

  if (x < layout.current_col)
    sound_name = "desktop-switch-left";
  else if (x > layout.current_col)
    sound_name = "desktop-switch-right";
  else if (y < layout.current_row)
    sound_name = "desktop-switch-up";
  else if (y > layout.current_row)
    sound_name = "desktop-switch-down";
  else
    {
      g_warn_if_reached ();
      goto finish;
    }

  player = meta_display_get_sound_player (from->display);
  meta_sound_player_play_from_theme (player,
                                     sound_name, _("Workspace switched"),
                                     NULL);

 finish:
  meta_workspace_manager_free_workspace_layout (&layout);
}

/**
 * meta_workspace_activate_with_focus:
 * @workspace: a #MetaWorkspace
 * @focus_this: the #MetaWindow to be focused, or %NULL
 * @timestamp: timestamp for @focus_this
 *
 * Switches to @workspace and possibly activates the window @focus_this.
 *
 * The window @focus_this is activated by calling meta_window_activate()
 * which will unminimize it and transient parents, raise it and give it
 * the focus.
 *
 * If a window is currently being moved by the user, it will be
 * moved to @workspace.
 *
 * The advantage of calling this function instead of meta_workspace_activate()
 * followed by meta_window_activate() is that it happens as a unit, so
 * no other window gets focused first before @focus_this.
 */
void
meta_workspace_activate_with_focus (MetaWorkspace *workspace,
                                    MetaWindow    *focus_this,
                                    guint32        timestamp)
{
  MetaWorkspace  *old;
  MetaWindow     *move_window;
  MetaCompositor *comp;
  MetaWorkspaceLayout layout1, layout2;
  gint num_workspaces, current_space, new_space;
  MetaMotionDirection direction;

  g_return_if_fail (META_IS_WORKSPACE (workspace));
  g_return_if_fail (meta_workspace_index (workspace) != -1);

  meta_verbose ("Activating workspace %d",
                meta_workspace_index (workspace));

  if (workspace->manager->active_workspace == workspace)
    {
      if (focus_this)
        meta_window_activate (focus_this, timestamp);
      return;
    }

  /* Free any cached pointers to the workspaces's edges from
   * a current resize or move operation */
  meta_display_cleanup_edges (workspace->display);

  if (workspace->manager->active_workspace)
    workspace_switch_sound (workspace->manager->active_workspace, workspace);

  /* Note that old can be NULL; e.g. when starting up */
  old = workspace->manager->active_workspace;

  workspace->manager->active_workspace = workspace;

  g_signal_emit_by_name (workspace->manager, "active-workspace-changed");

  g_object_notify_by_pspec (G_OBJECT (workspace), obj_props[PROP_ACTIVE]);

  if (old == NULL)
    return;

  g_object_notify_by_pspec (G_OBJECT (old), obj_props[PROP_ACTIVE]);

  /* If the "show desktop" mode is active for either the old workspace
   * or the new one *but not both*, then update the
   * _net_showing_desktop hint
   */
  if (old->showing_desktop != workspace->showing_desktop)
    g_signal_emit_by_name (workspace->manager, "showing-desktop-changed");

  move_window = NULL;
  if (meta_grab_op_is_moving (workspace->display->grab_op))
    move_window = workspace->display->grab_window;

  if (move_window != NULL)
    {
      /* We put the window on the new workspace, flip spaces,
       * then remove from old workspace, so the window
       * never gets unmapped and we maintain the button grab
       * on it.
       *
       * \bug  This comment appears to be the reverse of what happens
       */
      if (!meta_window_located_on_workspace (move_window, workspace))
        meta_window_change_workspace (move_window, workspace);
    }

  meta_workspace_queue_calc_showing (old);
  meta_workspace_queue_calc_showing (workspace);

   /*
    * Notify the compositor that the active workspace is changing.
    */
   comp = meta_display_get_compositor (workspace->display);
   direction = 0;

   current_space = meta_workspace_index (old);
   new_space     = meta_workspace_index (workspace);
   num_workspaces = meta_workspace_manager_get_n_workspaces (workspace->manager);
   meta_workspace_manager_calc_workspace_layout (workspace->manager, num_workspaces,
                                                 current_space, &layout1);

   meta_workspace_manager_calc_workspace_layout (workspace->manager, num_workspaces,
                                                 new_space, &layout2);

   if (meta_get_locale_direction () == META_LOCALE_DIRECTION_RTL)
     {
       if (layout1.current_col > layout2.current_col)
         direction = META_MOTION_RIGHT;
       else if (layout1.current_col < layout2.current_col)
         direction = META_MOTION_LEFT;
     }
   else
    {
       if (layout1.current_col < layout2.current_col)
         direction = META_MOTION_RIGHT;
       else if (layout1.current_col > layout2.current_col)
         direction = META_MOTION_LEFT;
    }

   if (layout1.current_row < layout2.current_row)
     {
       if (!direction)
         direction = META_MOTION_DOWN;
       else if (direction == META_MOTION_RIGHT)
         direction = META_MOTION_DOWN_RIGHT;
       else
         direction = META_MOTION_DOWN_LEFT;
     }

   if (layout1.current_row > layout2.current_row)
     {
       if (!direction)
         direction = META_MOTION_UP;
       else if (direction == META_MOTION_RIGHT)
         direction = META_MOTION_UP_RIGHT;
       else
         direction = META_MOTION_UP_LEFT;
     }

   meta_workspace_manager_free_workspace_layout (&layout1);
   meta_workspace_manager_free_workspace_layout (&layout2);

   meta_compositor_switch_workspace (comp, old, workspace, direction);

  /* This needs to be done after telling the compositor we are switching
   * workspaces since focusing a window will cause it to be immediately
   * shown and that would confuse the compositor if it didn't know we
   * were in a workspace switch.
   */
  if (focus_this)
    {
      meta_window_activate (focus_this, timestamp);
      update_workspace_default_focus (workspace, focus_this);
    }
  else if (move_window)
    {
      meta_window_raise (move_window);
    }
  else
    {
      meta_topic (META_DEBUG_FOCUS, "Focusing default window on new workspace");
      meta_workspace_focus_default_window (workspace, NULL, timestamp);
    }

   meta_workspace_manager_workspace_switched (workspace->manager, current_space,
                                              new_space, direction);
}

void
meta_workspace_activate (MetaWorkspace *workspace,
                         guint32        timestamp)
{
  meta_workspace_activate_with_focus (workspace, NULL, timestamp);
}

int
meta_workspace_index (MetaWorkspace *workspace)
{
  int ret;

  ret = g_list_index (workspace->manager->workspaces, workspace);
  g_return_val_if_fail (ret >= 0, -1);

  return ret;
}

void
meta_workspace_index_changed (MetaWorkspace *workspace)
{
  GList *l;
  for (l = workspace->windows; l != NULL; l = l->next)
    {
      MetaWindow *win = l->data;
      meta_window_current_workspace_changed (win);
    }

  g_object_notify_by_pspec (G_OBJECT (workspace), obj_props[PROP_WORKSPACE_INDEX]);
}

/**
 * meta_workspace_list_windows:
 * @workspace: a #MetaWorkspace
 *
 * Gets windows contained on the workspace, including workspace->windows
 * and also sticky windows. Override-redirect windows are not included.
 *
 * Return value: (transfer container) (element-type MetaWindow): the list of windows.
 */
GList*
meta_workspace_list_windows (MetaWorkspace *workspace)
{
  GSList *display_windows, *l;
  GList *workspace_windows;

  display_windows = meta_display_list_windows (workspace->display,
                                               META_LIST_DEFAULT);

  workspace_windows = NULL;
  for (l = display_windows; l != NULL; l = l->next)
    {
      MetaWindow *window = l->data;

      if (meta_window_located_on_workspace (window, workspace))
        workspace_windows = g_list_prepend (workspace_windows,
                                            window);
    }

  g_slist_free (display_windows);

  return workspace_windows;
}

void
meta_workspace_invalidate_work_area (MetaWorkspace *workspace)
{
  GList *windows, *l;

  if (workspace->work_areas_invalid)
    {
      meta_topic (META_DEBUG_WORKAREA,
                  "Work area for workspace %d is already invalid",
                  meta_workspace_index (workspace));
      return;
    }

  meta_topic (META_DEBUG_WORKAREA,
              "Invalidating work area for workspace %d",
              meta_workspace_index (workspace));

  /* If we are in the middle of a resize or move operation, we
   * might have cached pointers to the workspace's edges */
  if (workspace == workspace->manager->active_workspace)
    meta_display_cleanup_edges (workspace->display);

  meta_workspace_clear_logical_monitor_data (workspace);

  workspace_free_all_struts (workspace);

  meta_rectangle_free_list_and_elements (workspace->screen_region);
  meta_rectangle_free_list_and_elements (workspace->screen_edges);
  meta_rectangle_free_list_and_elements (workspace->monitor_edges);
  workspace->screen_region = NULL;
  workspace->screen_edges = NULL;
  workspace->monitor_edges = NULL;

  workspace->work_areas_invalid = TRUE;

  /* redo the size/position constraints on all windows */
  windows = meta_workspace_list_windows (workspace);

  for (l = windows; l != NULL; l = l->next)
    {
      MetaWindow *w = l->data;
      meta_window_queue (w, META_QUEUE_MOVE_RESIZE);
    }

  g_list_free (windows);

  meta_display_queue_workarea_recalc (workspace->display);
}

static MetaStrut *
copy_strut(MetaStrut *original)
{
  return g_memdup2 (original, sizeof (MetaStrut));
}

static GSList *
copy_strut_list(GSList *original)
{
  GSList *result = NULL;

  for (; original != NULL; original = original->next)
    result = g_slist_prepend (result, copy_strut (original->data));

  return g_slist_reverse (result);
}

static void
ensure_work_areas_validated (MetaWorkspace *workspace)
{
  MetaContext *context = meta_display_get_context (workspace->display);
  MetaBackend *backend = meta_context_get_backend (context);
  MetaMonitorManager *monitor_manager =
    meta_backend_get_monitor_manager (backend);
  GList *windows;
  GList *tmp;
  GList *logical_monitors, *l;
  MetaRectangle display_rect = { 0 };
  MetaRectangle work_area;

  if (!workspace->work_areas_invalid)
    return;

  g_assert (workspace->all_struts == NULL);
  g_assert (workspace->screen_region == NULL);
  g_assert (workspace->screen_edges == NULL);
  g_assert (workspace->monitor_edges == NULL);

  meta_display_get_size (workspace->display,
                         &display_rect.width,
                         &display_rect.height);

  /* STEP 1: Get the list of struts */

  workspace->all_struts = copy_strut_list (workspace->builtin_struts);

  windows = meta_workspace_list_windows (workspace);
  for (tmp = windows; tmp != NULL; tmp = tmp->next)
    {
      MetaWindow *win = tmp->data;
      GSList *s_iter;

      for (s_iter = win->struts; s_iter != NULL; s_iter = s_iter->next) {
        workspace->all_struts = g_slist_prepend (workspace->all_struts,
                                                 copy_strut(s_iter->data));
      }
    }
  g_list_free (windows);

  /* STEP 2: Get the maximal/spanning rects for the onscreen and
   *         on-single-monitor regions
   */
  g_assert (workspace->screen_region   == NULL);

  logical_monitors =
    meta_monitor_manager_get_logical_monitors (monitor_manager);
  for (l = logical_monitors; l; l = l->next)
    {
      MetaLogicalMonitor *logical_monitor = l->data;
      MetaWorkspaceLogicalMonitorData *data;

      g_assert (!meta_workspace_get_logical_monitor_data (workspace,
                                                          logical_monitor));

      data = meta_workspace_ensure_logical_monitor_data (workspace,
                                                         logical_monitor);
      data->logical_monitor_region =
        meta_rectangle_get_minimal_spanning_set_for_region (
          &logical_monitor->rect,
          workspace->all_struts);
    }

  workspace->screen_region =
    meta_rectangle_get_minimal_spanning_set_for_region (
      &display_rect,
      workspace->all_struts);

  /* STEP 3: Get the work areas (region-to-maximize-to) for the screen and
   *         monitors.
   */
  work_area = display_rect;  /* start with the screen */
  if (workspace->screen_region == NULL)
    work_area = meta_rect (0, 0, -1, -1);
  else
    meta_rectangle_clip_to_region (workspace->screen_region,
                                   FIXED_DIRECTION_NONE,
                                   &work_area);

  /* Lots of paranoia checks, forcing work_area_screen to be sane */
#define MIN_SANE_AREA 100
  if (work_area.width < MIN_SANE_AREA &&
      work_area.width != display_rect.width)
    {
      meta_warning ("struts occupy an unusually large percentage of the screen; "
                    "available remaining width = %d < %d",
                    work_area.width, MIN_SANE_AREA);
      if (work_area.width < 1)
        {
          work_area.x = (display_rect.width - MIN_SANE_AREA)/2;
          work_area.width = MIN_SANE_AREA;
        }
      else
        {
          int amount = (MIN_SANE_AREA - work_area.width)/2;
          work_area.x     -=   amount;
          work_area.width += 2*amount;
        }
    }
  if (work_area.height < MIN_SANE_AREA &&
      work_area.height != display_rect.height)
    {
      meta_warning ("struts occupy an unusually large percentage of the screen; "
                    "available remaining height = %d < %d",
                    work_area.height, MIN_SANE_AREA);
      if (work_area.height < 1)
        {
          work_area.y = (display_rect.height - MIN_SANE_AREA)/2;
          work_area.height = MIN_SANE_AREA;
        }
      else
        {
          int amount = (MIN_SANE_AREA - work_area.height)/2;
          work_area.y      -=   amount;
          work_area.height += 2*amount;
        }
    }
  workspace->work_area_screen = work_area;
  meta_topic (META_DEBUG_WORKAREA,
              "Computed work area for workspace %d: %d,%d %d x %d",
              meta_workspace_index (workspace),
              workspace->work_area_screen.x,
              workspace->work_area_screen.y,
              workspace->work_area_screen.width,
              workspace->work_area_screen.height);

  /* Now find the work areas for each monitor */
  for (l = logical_monitors; l; l = l->next)
    {
      MetaLogicalMonitor *logical_monitor = l->data;
      MetaWorkspaceLogicalMonitorData *data;

      data = meta_workspace_get_logical_monitor_data (workspace,
                                                      logical_monitor);
      work_area = logical_monitor->rect;

      if (!data->logical_monitor_region)
        /* FIXME: constraints.c untested with this, but it might be nice for
         * a screen reader or magnifier.
         */
        work_area = meta_rect (work_area.x, work_area.y, -1, -1);
      else
        meta_rectangle_clip_to_region (data->logical_monitor_region,
                                       FIXED_DIRECTION_NONE,
                                       &work_area);

      data->logical_monitor_work_area = work_area;

      meta_topic (META_DEBUG_WORKAREA,
                  "Computed work area for workspace %d "
                  "monitor %d: %d,%d %d x %d",
                  meta_workspace_index (workspace),
                  logical_monitor->number,
                  data->logical_monitor_work_area.x,
                  data->logical_monitor_work_area.y,
                  data->logical_monitor_work_area.width,
                  data->logical_monitor_work_area.height);
    }

  /* STEP 4: Make sure the screen_region is nonempty (separate from step 2
   *         since it relies on step 3).
   */
  if (workspace->screen_region == NULL)
    {
      MetaRectangle *nonempty_region;
      nonempty_region = g_new (MetaRectangle, 1);
      *nonempty_region = workspace->work_area_screen;
      workspace->screen_region = g_list_prepend (NULL, nonempty_region);
    }

  /* STEP 5: Cache screen and monitor edges for edge resistance and snapping */
  g_assert (workspace->screen_edges    == NULL);
  g_assert (workspace->monitor_edges  == NULL);
  workspace->screen_edges =
    meta_rectangle_find_onscreen_edges (&display_rect,
                                        workspace->all_struts);
  tmp = NULL;
  for (l = logical_monitors; l; l = l->next)
    {
      MetaLogicalMonitor *logical_monitor = l->data;

      tmp = g_list_prepend (tmp, &logical_monitor->rect);
    }
  workspace->monitor_edges =
    meta_rectangle_find_nonintersected_monitor_edges (tmp,
                                                       workspace->all_struts);
  g_list_free (tmp);

  /* We're all done, YAAY!  Record that everything has been validated. */
  workspace->work_areas_invalid = FALSE;
}

static gboolean
strut_lists_equal (GSList *l,
                   GSList *m)
{
  for (; l && m; l = l->next, m = m->next)
    {
      MetaStrut *a = l->data;
      MetaStrut *b = m->data;

      if (a->side != b->side ||
          !meta_rectangle_equal (&a->rect, &b->rect))
        return FALSE;
    }

  return l == NULL && m == NULL;
}

/**
 * meta_workspace_set_builtin_struts:
 * @workspace: a #MetaWorkspace
 * @struts: (element-type Meta.Strut) (transfer none): list of #MetaStrut
 *
 * Sets a list of struts that will be used in addition to the struts
 * of the windows in the workspace when computing the work area of
 * the workspace.
 */
void
meta_workspace_set_builtin_struts (MetaWorkspace *workspace,
                                   GSList        *struts)
{
  MetaContext *context = meta_display_get_context (workspace->display);
  MetaBackend *backend = meta_context_get_backend (context);
  MetaMonitorManager *monitor_manager =
    meta_backend_get_monitor_manager (backend);
  MetaDisplay *display = workspace->display;
  MetaRectangle display_rect = { 0 };
  GSList *l;

  meta_display_get_size (display, &display_rect.width, &display_rect.height);

  for (l = struts; l; l = l->next)
    {
      MetaStrut *strut = l->data;
      MetaLogicalMonitor *logical_monitor;

      logical_monitor =
        meta_monitor_manager_get_logical_monitor_from_rect (monitor_manager,
                                                            &strut->rect);

      switch (strut->side)
        {
        case META_SIDE_TOP:
          if (meta_monitor_manager_get_logical_monitor_neighbor (monitor_manager,
                                                                 logical_monitor,
                                                                 META_DISPLAY_UP))
            continue;

          strut->rect.height += strut->rect.y;
          strut->rect.y = 0;
          break;
        case META_SIDE_BOTTOM:
          if (meta_monitor_manager_get_logical_monitor_neighbor (monitor_manager,
                                                                 logical_monitor,
                                                                 META_DISPLAY_DOWN))
            continue;

          strut->rect.height = display_rect.height - strut->rect.y;
          break;
        case META_SIDE_LEFT:
          if (meta_monitor_manager_get_logical_monitor_neighbor (monitor_manager,
                                                                 logical_monitor,
                                                                 META_DISPLAY_LEFT))
            continue;

          strut->rect.width += strut->rect.x;
          strut->rect.x = 0;
          break;
        case META_SIDE_RIGHT:
          if (meta_monitor_manager_get_logical_monitor_neighbor (monitor_manager,
                                                                 logical_monitor,
                                                                 META_DISPLAY_RIGHT))
            continue;

          strut->rect.width = display_rect.width - strut->rect.x;
          break;
        }
    }

  /* Reordering doesn't actually matter, so we don't catch all
   * no-impact changes, but this is just a (possibly unnecessary
   * anyways) optimization */
  if (strut_lists_equal (struts, workspace->builtin_struts))
    return;

  workspace_free_builtin_struts (workspace);
  workspace->builtin_struts = copy_strut_list (struts);

  meta_workspace_invalidate_work_area (workspace);
}

void
meta_workspace_get_work_area_for_logical_monitor (MetaWorkspace      *workspace,
                                                  MetaLogicalMonitor *logical_monitor,
                                                  MetaRectangle      *area)
{
  meta_workspace_get_work_area_for_monitor (workspace,
                                            logical_monitor->number,
                                            area);
}

/**
 * meta_workspace_get_work_area_for_monitor:
 * @workspace: a #MetaWorkspace
 * @which_monitor: a monitor index
 * @area: (out): location to store the work area
 *
 * Stores the work area for @which_monitor on @workspace
 * in @area.
 */
void
meta_workspace_get_work_area_for_monitor (MetaWorkspace *workspace,
                                          int            which_monitor,
                                          MetaRectangle *area)
{
  MetaContext *context = meta_display_get_context (workspace->display);
  MetaBackend *backend = meta_context_get_backend (context);
  MetaMonitorManager *monitor_manager =
    meta_backend_get_monitor_manager (backend);
  MetaLogicalMonitor *logical_monitor;
  MetaWorkspaceLogicalMonitorData *data;

  logical_monitor =
    meta_monitor_manager_get_logical_monitor_from_number (monitor_manager,
                                                          which_monitor);
  g_return_if_fail (logical_monitor != NULL);

  ensure_work_areas_validated (workspace);
  data = meta_workspace_get_logical_monitor_data (workspace, logical_monitor);

  g_return_if_fail (data != NULL);

  *area = data->logical_monitor_work_area;
}

/**
 * meta_workspace_get_work_area_all_monitors:
 * @workspace: a #MetaWorkspace
 * @area: (out): location to store the work area
 *
 * Stores the work area in @area.
 */
void
meta_workspace_get_work_area_all_monitors (MetaWorkspace *workspace,
                                           MetaRectangle *area)
{
  ensure_work_areas_validated (workspace);

  *area = workspace->work_area_screen;
}

GList*
meta_workspace_get_onscreen_region (MetaWorkspace *workspace)
{
  ensure_work_areas_validated (workspace);

  return workspace->screen_region;
}

GList *
meta_workspace_get_onmonitor_region (MetaWorkspace      *workspace,
                                     MetaLogicalMonitor *logical_monitor)
{
  MetaWorkspaceLogicalMonitorData *data;

  ensure_work_areas_validated (workspace);

  data = meta_workspace_get_logical_monitor_data (workspace, logical_monitor);

  return data->logical_monitor_region;
}

#ifdef WITH_VERBOSE_MODE
static const char *
meta_motion_direction_to_string (MetaMotionDirection direction)
{
  switch (direction)
    {
    case META_MOTION_UP:
      return "Up";
    case META_MOTION_DOWN:
      return "Down";
    case META_MOTION_LEFT:
      return "Left";
    case META_MOTION_RIGHT:
      return "Right";
    case META_MOTION_UP_RIGHT:
      return "Up-Right";
    case META_MOTION_DOWN_RIGHT:
      return "Down-Right";
    case META_MOTION_UP_LEFT:
      return "Up-Left";
    case META_MOTION_DOWN_LEFT:
      return "Down-Left";
    }

  return "Unknown";
}
#endif /* WITH_VERBOSE_MODE */

/**
 * meta_workspace_get_neighbor:
 * @workspace: a #MetaWorkspace
 * @direction: a #MetaMotionDirection, relative to @workspace
 *
 * Calculate and retrieve the workspace that is next to @workspace,
 * according to @direction and the current workspace layout, as set
 * by meta_screen_override_workspace_layout().
 *
 * Returns: (transfer none): the workspace next to @workspace, or
 *   @workspace itself if the neighbor would be outside the layout
 */
MetaWorkspace*
meta_workspace_get_neighbor (MetaWorkspace      *workspace,
                             MetaMotionDirection direction)
{
  MetaWorkspaceLayout layout;
  int i, current_space, num_workspaces;
  gboolean ltr;

  current_space = meta_workspace_index (workspace);
  num_workspaces = meta_workspace_manager_get_n_workspaces (workspace->manager);
  meta_workspace_manager_calc_workspace_layout (workspace->manager, num_workspaces,
                                                current_space, &layout);

  meta_verbose ("Getting neighbor of %d in direction %s",
                current_space, meta_motion_direction_to_string (direction));

  ltr = (meta_get_locale_direction () == META_LOCALE_DIRECTION_LTR);

  switch (direction)
    {
    case META_MOTION_LEFT:
      layout.current_col -= ltr ? 1 : -1;
      break;
    case META_MOTION_RIGHT:
      layout.current_col += ltr ? 1 : -1;
      break;
    case META_MOTION_UP:
      layout.current_row -= 1;
      break;
    case META_MOTION_DOWN:
      layout.current_row += 1;
      break;
    default:;
    }

  if (layout.current_col < 0)
    layout.current_col = 0;
  if (layout.current_col >= layout.cols)
    layout.current_col = layout.cols - 1;
  if (layout.current_row < 0)
    layout.current_row = 0;
  if (layout.current_row >= layout.rows)
    layout.current_row = layout.rows - 1;

  i = layout.grid[layout.current_row * layout.cols + layout.current_col];

  if (i < 0)
    i = current_space;

  if (i >= num_workspaces)
    meta_bug ("calc_workspace_layout left an invalid (too-high) workspace number %d in the grid",
              i);

  meta_verbose ("Neighbor workspace is %d at row %d col %d",
                i, layout.current_row, layout.current_col);

  meta_workspace_manager_free_workspace_layout (&layout);

  return meta_workspace_manager_get_workspace_by_index (workspace->manager, i);
}

const char*
meta_workspace_get_name (MetaWorkspace *workspace)
{
  return meta_prefs_get_workspace_name (meta_workspace_index (workspace));
}

static MetaWindow *
get_focused_workspace_window (MetaWorkspace *workspace)
{
  g_autoptr (GList) windows = NULL;
  GList *l;

  windows = meta_workspace_list_windows (workspace);

  for (l = windows; l != NULL; l = l->next)
    {
      MetaWindow *window = l->data;

      if (meta_window_has_focus (window))
        return window;
    }

  return NULL;
}

void
meta_workspace_focus_default_window (MetaWorkspace *workspace,
                                     MetaWindow    *not_this_one,
                                     guint32        timestamp)
{
  MetaWindow *focus;

  if (timestamp == META_CURRENT_TIME)
    meta_warning ("META_CURRENT_TIME used to choose focus window; "
                  "focus window may not be correct.");

  focus = get_focused_workspace_window (workspace);
  if (focus != NULL && focus != not_this_one)
    return;

  if (meta_prefs_get_focus_mode () == G_DESKTOP_FOCUS_MODE_CLICK ||
      !workspace->display->mouse_mode)
    {
      focus_ancestor_or_mru_window (workspace, not_this_one, timestamp);
    }
  else
    {
      MetaWindow * window;

      window = get_pointer_window (workspace, not_this_one);
      if (window &&
          window->type != META_WINDOW_DOCK &&
          window->type != META_WINDOW_DESKTOP)
        {
          if (timestamp == META_CURRENT_TIME)
            {

              /* We would like for this to never happen.  However, if
               * it does happen then we kludge since using META_CURRENT_TIME
               * can mean ugly race conditions--and we can avoid these
               * by allowing EnterNotify events (which come with
               * timestamps) to handle focus.
               */

              meta_topic (META_DEBUG_FOCUS,
                          "Not focusing mouse window %s because EnterNotify events should handle that",
                          window->desc);
            }
          else
            {
              meta_topic (META_DEBUG_FOCUS,
                          "Focusing mouse window %s", window->desc);
              meta_window_focus (window, timestamp);
            }

          if (workspace->display->autoraise_window != window &&
              meta_prefs_get_auto_raise ())
            {
              meta_display_queue_autoraise_callback (workspace->display, window);
            }
        }
      else if (meta_prefs_get_focus_mode () == G_DESKTOP_FOCUS_MODE_SLOPPY)
        {
          focus_ancestor_or_mru_window (workspace, not_this_one, timestamp);
        }
      else if (meta_prefs_get_focus_mode () == G_DESKTOP_FOCUS_MODE_MOUSE)
        {
          meta_topic (META_DEBUG_FOCUS,
                      "Setting focus to no_focus_window, since no valid "
                      "window to focus found.");
          meta_display_unset_input_focus (workspace->display, timestamp);
        }
    }
}

static gboolean
is_focusable (MetaWindow    *window,
              MetaWorkspace *workspace)
{
  return !window->unmanaging &&
         window->unmaps_pending == 0 &&
         window->type != META_WINDOW_DOCK &&
         meta_window_is_focusable (window) &&
         meta_window_located_on_workspace (window, workspace) &&
         meta_window_showing_on_its_workspace (window);
}

static gboolean
find_focusable_ancestor (MetaWindow *window,
                         gpointer    user_data)
{
  MetaWorkspaceFocusableAncestorData *data = user_data;

  if (is_focusable (window, data->workspace) && !window->hidden)
    {
      data->out_window = window;
      return FALSE;
    }

  return TRUE;
}

GList *
meta_workspace_get_default_focus_candidates (MetaWorkspace *workspace)
{
  GList *l;
  GList *candidates = NULL;

  for (l = workspace->mru_list; l; l = l->next)
    {
      MetaWindow *window = l->data;

      g_assert (window);

      if (!is_focusable (window, workspace))
        continue;

      candidates = g_list_prepend (candidates, window);
    }

  return candidates;
}

static gboolean
window_contains_point (MetaWindow *window,
                       int         root_x,
                       int         root_y)
{
  MetaRectangle rect;

  meta_window_get_frame_rect (window, &rect);

  return META_POINT_IN_RECT (root_x, root_y, rect);
}

MetaWindow *
meta_workspace_get_default_focus_window_at_point (MetaWorkspace *workspace,
                                                  MetaWindow    *not_this_one,
                                                  int            root_x,
                                                  int            root_y)
{
  g_autoptr (GList) sorted = NULL;
  GList *l;
  MetaStack *stack;

  g_return_val_if_fail (META_IS_WORKSPACE (workspace), NULL);
  g_return_val_if_fail (!not_this_one || META_IS_WINDOW (not_this_one), NULL);

  stack = workspace->display->stack;

  g_return_val_if_fail (META_IS_STACK (stack), NULL);

  /* Find the topmost, focusable, mapped, window.
   * not_this_one is being unfocused or going away, so exclude it.
   */
  sorted = g_list_reverse (meta_stack_list_windows (stack, workspace));

  /* top of this layer is at the front of the list */
  for (l = sorted; l != NULL; l = l->next)
    {
      MetaWindow *window = l->data;

      g_assert (window);

      if (window == not_this_one)
        continue;

      if (!is_focusable (window, workspace))
        continue;

      if (!window_contains_point (window, root_x, root_y))
        continue;

      return window;
    }

  return NULL;
}

MetaWindow *
meta_workspace_get_default_focus_window (MetaWorkspace *workspace,
                                         MetaWindow    *not_this_one)
{
  GList *l;

  g_return_val_if_fail (META_IS_WORKSPACE (workspace), NULL);
  g_return_val_if_fail (!not_this_one || META_IS_WINDOW (not_this_one), NULL);

  for (l = workspace->mru_list; l; l = l->next)
    {
      MetaWindow *window = l->data;

      g_assert (window);

      if (window == not_this_one)
        continue;

      if (!is_focusable (window, workspace))
        continue;

      return window;
    }

  return NULL;
}

static MetaWindow *
get_pointer_window (MetaWorkspace *workspace,
                    MetaWindow    *not_this_one)
{
  MetaContext *context = meta_display_get_context (workspace->display);
  MetaBackend *backend = meta_context_get_backend (context);
  MetaCursorTracker *cursor_tracker = meta_backend_get_cursor_tracker (backend);
  graphene_point_t point;

  if (not_this_one)
    meta_topic (META_DEBUG_FOCUS,
                "Focusing mouse window excluding %s", not_this_one->desc);

  meta_cursor_tracker_get_pointer (cursor_tracker, &point, NULL);

  return meta_workspace_get_default_focus_window_at_point (workspace,
                                                           not_this_one,
                                                           point.x, point.y);
}

static gboolean
try_to_set_focus_and_check (MetaWindow *window,
                            MetaWindow *not_this_one,
                            uint32_t    timestamp)
{
  meta_window_focus (window, timestamp);

  /* meta_focus_window() will not change focus for clients using the
   * "globally active input" model of input handling, hence defeating
   * the assumption that focus should be changed for such windows.
   * See https://tronche.com/gui/x/icccm/sec-4.html#s-4.1.7
   */
  if (meta_window_is_focus_async (window))
    return TRUE;

  /* meta_window_focus() does not guarantee that focus will end up
   * where we expect, it can fail for various reasons, better check
   * it did not actually changed or even left focus to the window we
   * explicitly want to avoid.
   */
  if (not_this_one &&
      meta_display_get_focus_window (window->display) == not_this_one)
    {
      meta_warning ("Failed to focus window %s while avoiding %s",
                    window->desc, not_this_one->desc);

      return FALSE;
    }

  return TRUE;
}

/* Focus ancestor of not_this_one if there is one */
static void
focus_ancestor_or_mru_window (MetaWorkspace *workspace,
                              MetaWindow    *not_this_one,
                              guint32        timestamp)
{
  MetaWindow *window = NULL;

  if (not_this_one)
    meta_topic (META_DEBUG_FOCUS,
                "Focusing MRU window excluding %s", not_this_one->desc);
  else
    meta_topic (META_DEBUG_FOCUS,
                "Focusing MRU window");

  /* First, check to see if we need to focus an ancestor of a window */
  if (not_this_one)
    {
      MetaWindow *ancestor;
      MetaWorkspaceFocusableAncestorData data;

      data = (MetaWorkspaceFocusableAncestorData) {
        .workspace = workspace,
      };
      meta_window_foreach_ancestor (not_this_one, find_focusable_ancestor, &data);
      ancestor = data.out_window;

      if (ancestor)
        {
          meta_topic (META_DEBUG_FOCUS,
                      "Focusing %s, ancestor of %s",
                      ancestor->desc, not_this_one->desc);

          if (try_to_set_focus_and_check (ancestor, not_this_one, timestamp))
            {
              /* Also raise the window if in click-to-focus */
              if (meta_prefs_get_focus_mode () == G_DESKTOP_FOCUS_MODE_CLICK)
                meta_window_raise (ancestor);

              return;
            }
        }
    }

  window = meta_workspace_get_default_focus_window (workspace, not_this_one);

  if (window)
    {
      meta_topic (META_DEBUG_FOCUS,
                  "Focusing workspace MRU window %s", window->desc);
      if (try_to_set_focus_and_check (window, not_this_one, timestamp))
        {
          /* Also raise the window if in click-to-focus */
          if (meta_prefs_get_focus_mode () == G_DESKTOP_FOCUS_MODE_CLICK)
            meta_window_raise (window);

          return;
        }
    }

  meta_topic (META_DEBUG_FOCUS,
             "No MRU window to focus found; focusing no_focus_window.");
  meta_display_unset_input_focus (workspace->display, timestamp);
}

/**
 * meta_workspace_get_display:
 * @workspace: a #MetaWorkspace
 *
 * Gets the #MetaDisplay that the workspace is part of.
 *
 * Return value: (transfer none): the #MetaDisplay for the workspace
 */
MetaDisplay *
meta_workspace_get_display (MetaWorkspace *workspace)
{
  return workspace->display;
}