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
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
/* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */

/* Croma Session Management */

/*
 * Copyright (C) 2001 Havoc Pennington (some code in here from
 * libcafeui, (C) Tom Tromey, Carsten Schaar)
 * 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, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
 * 02110-1301, USA.
 */

#include <config.h>

#include "session.h"
#include <X11/Xatom.h>

#include <time.h>
#include <sys/wait.h>

#ifndef HAVE_SM
void
meta_session_init (const char *client_id,
                   const char *save_file)
{
  meta_topic (META_DEBUG_SM, "Compiled without session management support\n");
}

void
meta_session_shutdown (void)
{
  /* nothing */
}

const MetaWindowSessionInfo*
meta_window_lookup_saved_state (MetaWindow *window)
{
  return NULL;
}

void
meta_window_release_saved_state (const MetaWindowSessionInfo *info)
{
  ;
}
#else /* HAVE_SM */

#include <X11/ICE/ICElib.h>
#include <X11/SM/SMlib.h>
#include <unistd.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>
#include <errno.h>
#include <glib.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include "main.h"
#include "util.h"
#include "display-private.h"
#include "workspace.h"

static void ice_io_error_handler (IceConn connection);

static void new_ice_connection (IceConn connection, IcePointer client_data,
				Bool opening, IcePointer *watch_data);

static void        save_state         (void);
static char*       load_state         (const char *previous_save_file);
static void        regenerate_save_file (void);
static const char* full_save_file       (void);
static void        warn_about_lame_clients_and_finish_interact (gboolean shutdown);
static void        disconnect         (void);

/* This is called when data is available on an ICE connection.  */
static gboolean
process_ice_messages (GIOChannel *channel,
                      GIOCondition condition,
                      gpointer client_data)
{
  IceConn connection = (IceConn) client_data;
  IceProcessMessagesStatus status;

  /* This blocks infinitely sometimes. I don't know what
   * to do about it. Checking "condition" just breaks
   * session management.
   */
  status = IceProcessMessages (connection, NULL, NULL);

  if (status == IceProcessMessagesIOError)
    {
#if 0
      IcePointer context = IceGetConnectionContext (connection);
#endif

      /* We were disconnected; close our connection to the
       * session manager, this will result in the ICE connection
       * being cleaned up, since it is owned by libSM.
       */
      disconnect ();
      meta_quit (META_EXIT_SUCCESS);

      return FALSE;
    }

  return TRUE;
}

/* This is called when a new ICE connection is made.  It arranges for
   the ICE connection to be handled via the event loop.  */
static void
new_ice_connection (IceConn connection, IcePointer client_data, Bool opening,
		    IcePointer *watch_data)
{
  guint input_id;

  if (opening)
    {
      /* Make sure we don't pass on these file descriptors to any
       * exec'ed children
       */
      GIOChannel *channel;

      fcntl (IceConnectionNumber (connection), F_SETFD,
             fcntl (IceConnectionNumber (connection), F_GETFD, 0) | FD_CLOEXEC);

      channel = g_io_channel_unix_new (IceConnectionNumber (connection));

      input_id = g_io_add_watch (channel,
                                 G_IO_IN | G_IO_ERR,
                                 process_ice_messages,
                                 connection);

      g_io_channel_unref (channel);

      *watch_data = (IcePointer) GUINT_TO_POINTER (input_id);
    }
  else
    {
      input_id = GPOINTER_TO_UINT ((gpointer) *watch_data);

      g_source_remove (input_id);
    }
}

static IceIOErrorHandler ice_installed_handler;

/* We call any handler installed before (or after) cafe_ice_init but
   avoid calling the default libICE handler which does an exit() */
static void
ice_io_error_handler (IceConn connection)
{
    if (ice_installed_handler)
      (*ice_installed_handler) (connection);
}

static void
ice_init (void)
{
  static gboolean ice_initted = FALSE;

  if (! ice_initted)
    {
      IceIOErrorHandler default_handler;

      ice_installed_handler = IceSetIOErrorHandler (NULL);
      default_handler = IceSetIOErrorHandler (ice_io_error_handler);

      if (ice_installed_handler == default_handler)
	ice_installed_handler = NULL;

      IceAddConnectionWatch (new_ice_connection, NULL);

      ice_initted = TRUE;
    }
}

typedef enum
{
  STATE_DISCONNECTED,
  STATE_IDLE,
  STATE_SAVING_PHASE_1,
  STATE_WAITING_FOR_PHASE_2,
  STATE_SAVING_PHASE_2,
  STATE_WAITING_FOR_INTERACT,
  STATE_DONE_WITH_INTERACT,
  STATE_SKIPPING_GLOBAL_SAVE,
  STATE_FROZEN,
  STATE_REGISTERING
} ClientState;

static void save_phase_2_callback       (SmcConn   smc_conn,
                                         SmPointer client_data);
static void interact_callback           (SmcConn   smc_conn,
                                         SmPointer client_data);
static void shutdown_cancelled_callback (SmcConn   smc_conn,
                                         SmPointer client_data);
static void save_complete_callback      (SmcConn   smc_conn,
                                         SmPointer client_data);
static void die_callback                (SmcConn   smc_conn,
                                         SmPointer client_data);
static void save_yourself_callback      (SmcConn   smc_conn,
                                         SmPointer client_data,
                                         int       save_style,
                                         Bool      shutdown,
                                         int       interact_style,
                                         Bool      fast);
static void set_clone_restart_commands  (void);

static char *client_id = NULL;
static gpointer session_connection = NULL;
static ClientState current_state = STATE_DISCONNECTED;
static gboolean interaction_allowed = FALSE;

void
meta_session_init (const char *previous_client_id,
                   const char *previous_save_file)
{
  /* Some code here from twm */
  char buf[256];
  unsigned long mask;
  SmcCallbacks callbacks;
  char *saved_client_id;

  meta_topic (META_DEBUG_SM, "Initializing session with save file '%s'\n",
              previous_save_file ? previous_save_file : "(none)");

  if (previous_save_file)
    {
      saved_client_id = load_state (previous_save_file);
      previous_client_id = saved_client_id;
    }
  else if (previous_client_id)
    {
      char *save_file = g_strconcat (previous_client_id, ".ms", NULL);
      saved_client_id = load_state (save_file);
      g_free (save_file);
    }
  else
    {
      saved_client_id = NULL;
    }

  ice_init ();

  mask = SmcSaveYourselfProcMask | SmcDieProcMask |
    SmcSaveCompleteProcMask | SmcShutdownCancelledProcMask;

  callbacks.save_yourself.callback = save_yourself_callback;
  callbacks.save_yourself.client_data = NULL;

  callbacks.die.callback = die_callback;
  callbacks.die.client_data = NULL;

  callbacks.save_complete.callback = save_complete_callback;
  callbacks.save_complete.client_data = NULL;

  callbacks.shutdown_cancelled.callback = shutdown_cancelled_callback;
  callbacks.shutdown_cancelled.client_data = NULL;

  session_connection =
    SmcOpenConnection (NULL, /* use SESSION_MANAGER env */
                       NULL, /* means use existing ICE connection */
                       SmProtoMajor,
                       SmProtoMinor,
                       mask,
                       &callbacks,
                       (char*) previous_client_id,
                       &client_id,
                       255, buf);

  if (session_connection == NULL)
    {
      meta_topic (META_DEBUG_SM,
                  "Failed to a open connection to a session manager, so window positions will not be saved: %s\n",
                  buf);

      goto out;
    }
  else
    {
      if (client_id == NULL)
        meta_bug ("Session manager gave us a NULL client ID?");
      meta_topic (META_DEBUG_SM, "Obtained session ID '%s'\n", client_id);
    }

  if (previous_client_id && strcmp (previous_client_id, client_id) == 0)
    current_state = STATE_IDLE;
  else
    current_state = STATE_REGISTERING;

  {
    SmProp prop1, prop2, prop3, prop4, prop5, prop6, *props[6];
    SmPropValue prop1val, prop2val, prop3val, prop4val, prop5val, prop6val;
    char pid[32];
    char hint = SmRestartImmediately;
    char priority = 20; /* low to run before other apps */

    prop1.name = SmProgram;
    prop1.type = SmARRAY8;
    prop1.num_vals = 1;
    prop1.vals = &prop1val;
    prop1val.value = "croma";
    prop1val.length = strlen ("croma");

    /* twm sets getuid() for this, but the SM spec plainly
     * says pw_name, twm is on crack
     */
    prop2.name = SmUserID;
    prop2.type = SmARRAY8;
    prop2.num_vals = 1;
    prop2.vals = &prop2val;
    prop2val.value = (char*) g_get_user_name ();
    prop2val.length = strlen (prop2val.value);

    prop3.name = SmRestartStyleHint;
    prop3.type = SmCARD8;
    prop3.num_vals = 1;
    prop3.vals = &prop3val;
    prop3val.value = &hint;
    prop3val.length = 1;

    sprintf (pid, "%d", getpid ());
    prop4.name = SmProcessID;
    prop4.type = SmARRAY8;
    prop4.num_vals = 1;
    prop4.vals = &prop4val;
    prop4val.value = pid;
    prop4val.length = strlen (prop4val.value);

    /* Always start in home directory */
    prop5.name = SmCurrentDirectory;
    prop5.type = SmARRAY8;
    prop5.num_vals = 1;
    prop5.vals = &prop5val;
    prop5val.value = (char*) g_get_home_dir ();
    prop5val.length = strlen (prop5val.value);

    prop6.name = "_GSM_Priority";
    prop6.type = SmCARD8;
    prop6.num_vals = 1;
    prop6.vals = &prop6val;
    prop6val.value = &priority;
    prop6val.length = 1;

    props[0] = &prop1;
    props[1] = &prop2;
    props[2] = &prop3;
    props[3] = &prop4;
    props[4] = &prop5;
    props[5] = &prop6;

    SmcSetProperties (session_connection, 6, props);
  }

 out:
  g_free (saved_client_id);
}

void
meta_session_shutdown (void)
{
  /* Change our restart mode to IfRunning */

  SmProp prop1;
  SmPropValue prop1val;
  SmProp *props[1];
  char hint = SmRestartIfRunning;

  if (session_connection == NULL)
    return;

  prop1.name = SmRestartStyleHint;
  prop1.type = SmCARD8;
  prop1.num_vals = 1;
  prop1.vals = &prop1val;
  prop1val.value = &hint;
  prop1val.length = 1;

  props[0] = &prop1;

  SmcSetProperties (session_connection, 1, props);
}

static void
disconnect (void)
{
  SmcCloseConnection (session_connection, 0, NULL);
  session_connection = NULL;
  current_state = STATE_DISCONNECTED;
}

static void
save_yourself_possibly_done (gboolean shutdown,
                             gboolean successful)
{
  meta_topic (META_DEBUG_SM,
              "save possibly done shutdown = %d success = %d\n",
              shutdown, successful);

  if (current_state == STATE_SAVING_PHASE_1)
    {
      Status status;

      status = SmcRequestSaveYourselfPhase2 (session_connection,
                                             save_phase_2_callback,
                                             GINT_TO_POINTER (shutdown));

      if (status)
        current_state = STATE_WAITING_FOR_PHASE_2;

      meta_topic (META_DEBUG_SM,
                  "Requested phase 2, status = %d\n", status);
    }

  if (current_state == STATE_SAVING_PHASE_2 &&
      interaction_allowed)
    {
      Status status;

      status = SmcInteractRequest (session_connection,
                                   /* ignore this feature of the protocol by always
                                    * claiming normal
                                    */
                                   SmDialogNormal,
                                   interact_callback,
                                   GINT_TO_POINTER (shutdown));

      if (status)
        current_state = STATE_WAITING_FOR_INTERACT;

      meta_topic (META_DEBUG_SM,
                  "Requested interact, status = %d\n", status);
    }

  if (current_state == STATE_SAVING_PHASE_1 ||
      current_state == STATE_SAVING_PHASE_2 ||
      current_state == STATE_DONE_WITH_INTERACT ||
      current_state == STATE_SKIPPING_GLOBAL_SAVE)
    {
      meta_topic (META_DEBUG_SM, "Sending SaveYourselfDone\n");

      SmcSaveYourselfDone (session_connection,
                           successful);

      if (shutdown)
        current_state = STATE_FROZEN;
      else
        current_state = STATE_IDLE;
    }
}

static void
save_phase_2_callback (SmcConn smc_conn, SmPointer client_data)
{
  gboolean shutdown;

  meta_topic (META_DEBUG_SM, "Phase 2 save");

  shutdown = GPOINTER_TO_INT (client_data);

  current_state = STATE_SAVING_PHASE_2;

  save_state ();

  save_yourself_possibly_done (shutdown, TRUE);
}

static void
save_yourself_callback (SmcConn   smc_conn,
                        SmPointer client_data,
                        int       save_style,
                        Bool      shutdown,
                        int       interact_style,
                        Bool      fast)
{
  gboolean successful;

  meta_topic (META_DEBUG_SM, "SaveYourself received");

  successful = TRUE;

  /* The first SaveYourself after registering for the first time
   * is a special case (SM specs 7.2).
   */

#if 0 /* I think the CafeClient rationale for this doesn't apply */
  if (current_state == STATE_REGISTERING)
    {
      current_state = STATE_IDLE;
      /* Double check that this is a section 7.2 SaveYourself: */

      if (save_style == SmSaveLocal &&
	  interact_style == SmInteractStyleNone &&
	  !shutdown && !fast)
	{
	  /* The protocol requires this even if xsm ignores it. */
	  SmcSaveYourselfDone (session_connection, successful);
	  return;
	}
    }
#endif

  /* ignore Global style saves
   *
   * This interpretaion of the Local/Global/Both styles
   * was discussed extensively on the xdg-list. See:
   *
   * https://listman.redhat.com/pipermail/xdg-list/2002-July/000615.html
   */
  if (save_style == SmSaveGlobal)
    {
      current_state = STATE_SKIPPING_GLOBAL_SAVE;
      save_yourself_possibly_done (shutdown, successful);
      return;
    }

  interaction_allowed = interact_style != SmInteractStyleNone;

  current_state = STATE_SAVING_PHASE_1;

  regenerate_save_file ();

  set_clone_restart_commands ();

  save_yourself_possibly_done (shutdown, successful);
}


static void
die_callback (SmcConn smc_conn, SmPointer client_data)
{
  meta_topic (META_DEBUG_SM, "Exiting at request of session manager\n");
  disconnect ();
  meta_quit (META_EXIT_SUCCESS);
}

static void
save_complete_callback (SmcConn smc_conn, SmPointer client_data)
{
  /* nothing */
  meta_topic (META_DEBUG_SM, "SaveComplete received\n");
}

static void
shutdown_cancelled_callback (SmcConn smc_conn, SmPointer client_data)
{
  meta_topic (META_DEBUG_SM, "Shutdown cancelled received\n");

  if (session_connection != NULL &&
      (current_state != STATE_IDLE && current_state != STATE_FROZEN))
    {
      SmcSaveYourselfDone (session_connection, True);
      current_state = STATE_IDLE;
    }
}

static void
interact_callback (SmcConn smc_conn, SmPointer client_data)
{
  /* nothing */
  gboolean shutdown;

  meta_topic (META_DEBUG_SM, "Interaction permission received\n");

  shutdown = GPOINTER_TO_INT (client_data);

  current_state = STATE_DONE_WITH_INTERACT;

  warn_about_lame_clients_and_finish_interact (shutdown);
}

static void
set_clone_restart_commands (void)
{
  char *restartv[10];
  char *clonev[10];
  char *discardv[10];
  int i;
  SmProp prop1, prop2, prop3, *props[3];

  /* Restart (use same client ID) */

  prop1.name = SmRestartCommand;
  prop1.type = SmLISTofARRAY8;

  g_return_if_fail (client_id);

  i = 0;
  restartv[i] = "croma";
  ++i;
  restartv[i] = "--sm-client-id";
  ++i;
  restartv[i] = client_id;
  ++i;
  restartv[i] = NULL;

  prop1.vals = g_new (SmPropValue, i);
  i = 0;
  while (restartv[i])
    {
      prop1.vals[i].value = restartv[i];
      prop1.vals[i].length = strlen (restartv[i]);
      ++i;
    }
  prop1.num_vals = i;

  /* Clone (no client ID) */

  i = 0;
  clonev[i] = "croma";
  ++i;
  clonev[i] = NULL;

  prop2.name = SmCloneCommand;
  prop2.type = SmLISTofARRAY8;

  prop2.vals = g_new (SmPropValue, i);
  i = 0;
  while (clonev[i])
    {
      prop2.vals[i].value = clonev[i];
      prop2.vals[i].length = strlen (clonev[i]);
      ++i;
    }
  prop2.num_vals = i;

  /* Discard */

  i = 0;
  discardv[i] = "rm";
  ++i;
  discardv[i] = "-f";
  ++i;
  discardv[i] = (char*) full_save_file ();
  ++i;
  discardv[i] = NULL;

  prop3.name = SmDiscardCommand;
  prop3.type = SmLISTofARRAY8;

  prop3.vals = g_new (SmPropValue, i);
  i = 0;
  while (discardv[i])
    {
      prop3.vals[i].value = discardv[i];
      prop3.vals[i].length = strlen (discardv[i]);
      ++i;
    }
  prop3.num_vals = i;


  props[0] = &prop1;
  props[1] = &prop2;
  props[2] = &prop3;

  SmcSetProperties (session_connection, 3, props);

  g_free (prop1.vals);
  g_free (prop2.vals);
  g_free (prop3.vals);
}

/* The remaining code in this file actually loads/saves the session,
 * while the code above this comment handles chatting with the
 * session manager.
 */

static const char*
window_type_to_string (MetaWindowType type)
{
  switch (type)
    {
    case META_WINDOW_NORMAL:
      return "normal";
    case META_WINDOW_DESKTOP:
      return "desktop";
    case META_WINDOW_DOCK:
      return "dock";
    case META_WINDOW_DIALOG:
      return "dialog";
    case META_WINDOW_MODAL_DIALOG:
      return "modal_dialog";
    case META_WINDOW_TOOLBAR:
      return "toolbar";
    case META_WINDOW_MENU:
      return "menu";
    case META_WINDOW_SPLASHSCREEN:
      return "splashscreen";
    case META_WINDOW_UTILITY:
      return "utility";
    }

  return "";
}

static MetaWindowType
window_type_from_string (const char *str)
{
  if (strcmp (str, "normal") == 0)
    return META_WINDOW_NORMAL;
  else if (strcmp (str, "desktop") == 0)
    return META_WINDOW_DESKTOP;
  else if (strcmp (str, "dock") == 0)
    return META_WINDOW_DOCK;
  else if (strcmp (str, "dialog") == 0)
    return META_WINDOW_DIALOG;
  else if (strcmp (str, "modal_dialog") == 0)
    return META_WINDOW_MODAL_DIALOG;
  else if (strcmp (str, "toolbar") == 0)
    return META_WINDOW_TOOLBAR;
  else if (strcmp (str, "menu") == 0)
    return META_WINDOW_MENU;
  else if (strcmp (str, "utility") == 0)
    return META_WINDOW_UTILITY;
  else if (strcmp (str, "splashscreen") == 0)
    return META_WINDOW_SPLASHSCREEN;
  else
    return META_WINDOW_NORMAL;
}

static int
window_gravity_from_string (const char *str)
{
  if (strcmp (str, "NorthWestGravity") == 0)
    return NorthWestGravity;
  else if (strcmp (str, "NorthGravity") == 0)
    return NorthGravity;
  else if (strcmp (str, "NorthEastGravity") == 0)
    return NorthEastGravity;
  else if (strcmp (str, "WestGravity") == 0)
    return WestGravity;
  else if (strcmp (str, "CenterGravity") == 0)
    return CenterGravity;
  else if (strcmp (str, "EastGravity") == 0)
    return EastGravity;
  else if (strcmp (str, "SouthWestGravity") == 0)
    return SouthWestGravity;
  else if (strcmp (str, "SouthGravity") == 0)
    return SouthGravity;
  else if (strcmp (str, "SouthEastGravity") == 0)
    return SouthEastGravity;
  else if (strcmp (str, "StaticGravity") == 0)
    return StaticGravity;
  else
    return NorthWestGravity;
}

static char*
encode_text_as_utf8_markup (const char *text)
{
  /* text can be any encoding, and is nul-terminated.
   * we pretend it's Latin-1 and encode as UTF-8
   */
  GString *str;
  const char *p;
  char *escaped;

  str = g_string_new ("");

  p = text;
  while (*p)
    {
      g_string_append_unichar (str, *p);
      ++p;
    }

  escaped = g_markup_escape_text (str->str, str->len);
  g_string_free (str, TRUE);

  return escaped;
}

static char*
decode_text_from_utf8 (const char *text)
{
  /* Convert back from the encoded (but not escaped) UTF-8 */
  GString *str;
  const char *p;

  str = g_string_new ("");

  p = text;
  while (*p)
    {
      /* obviously this barfs if the UTF-8 contains chars > 255 */
      g_string_append_c (str, g_utf8_get_char (p));

      p = g_utf8_next_char (p);
    }

  return g_string_free (str, FALSE);
}

static void
save_state (void)
{
  char *croma_dir;
  char *session_dir;
  FILE *outfile;
  GSList *windows;
  GSList *tmp;
  int stack_position;

  g_assert (client_id);

  outfile = NULL;

  /*
   * g_get_user_config_dir() is guaranteed to return an existing directory.
   * Eventually, if SM stays with the WM, I'd like to make this
   * something like <config>/window_placement in a standard format.
   * Future optimisers should note also that by the time we get here
   * we probably already have full_save_path figured out and therefore
   * can just use the directory name from that.
   */
  croma_dir = g_strconcat (g_get_user_config_dir (),
                              G_DIR_SEPARATOR_S "croma",
                              NULL);

  session_dir = g_strconcat (croma_dir,
                             G_DIR_SEPARATOR_S "sessions",
                             NULL);

  if (mkdir (croma_dir, 0700) < 0 &&
      errno != EEXIST)
    {
      meta_warning (_("Could not create directory '%s': %s\n"),
                    croma_dir, g_strerror (errno));
    }

  if (mkdir (session_dir, 0700) < 0 &&
      errno != EEXIST)
    {
      meta_warning (_("Could not create directory '%s': %s\n"),
                    session_dir, g_strerror (errno));
    }

  meta_topic (META_DEBUG_SM, "Saving session to '%s'\n", full_save_file ());

  outfile = fopen (full_save_file (), "w");

  if (outfile == NULL)
    {
      meta_warning (_("Could not open session file '%s' for writing: %s\n"),
                    full_save_file (), g_strerror (errno));
      goto out;
    }

  /* The file format is:
   * <croma_session id="foo">
   *   <window id="bar" class="XTerm" name="xterm" title="/foo/bar" role="blah" type="normal" stacking="5">
   *     <workspace index="2"/>
   *     <workspace index="4"/>
   *     <sticky/> <minimized/> <maximized/>
   *     <geometry x="100" y="100" width="200" height="200" gravity="northwest"/>
   *   </window>
   * </croma_session>
   *
   * Note that attributes on <window> are the match info we use to
   * see if the saved state applies to a restored window, and
   * child elements are the saved state to be applied.
   *
   */

  fprintf (outfile, "<croma_session id=\"%s\">\n",
           client_id);

  windows = meta_display_list_windows (meta_get_display ());

  windows = g_slist_sort (windows, meta_display_stack_cmp);
  tmp = windows;
  stack_position = 0;

  while (tmp != NULL)
    {
      MetaWindow *window;

      window = tmp->data;

      if (window->sm_client_id)
        {
          char *sm_client_id;
          char *res_class;
          char *res_name;
          char *role;
          char *title;

          /* client id, class, name, role are not expected to be
           * in UTF-8 (I think they are in XPCS which is Latin-1?
           * in practice they are always ascii though.)
           */

          sm_client_id = encode_text_as_utf8_markup (window->sm_client_id);
          res_class = window->res_class ?
            encode_text_as_utf8_markup (window->res_class) : NULL;
          res_name = window->res_name ?
            encode_text_as_utf8_markup (window->res_name) : NULL;
          role = window->role ?
            encode_text_as_utf8_markup (window->role) : NULL;
          if (window->title)
            title = g_markup_escape_text (window->title, -1);
          else
            title = NULL;

          meta_topic (META_DEBUG_SM, "Saving session managed window %s, client ID '%s'\n",
                      window->desc, window->sm_client_id);

          fprintf (outfile,
                   "  <window id=\"%s\" class=\"%s\" name=\"%s\" title=\"%s\" role=\"%s\" type=\"%s\" stacking=\"%d\">\n",
                   sm_client_id,
                   res_class ? res_class : "",
                   res_name ? res_name : "",
                   title ? title : "",
                   role ? role : "",
                   window_type_to_string (window->type),
                   stack_position);

          g_free (sm_client_id);
          g_free (res_class);
          g_free (res_name);
          g_free (role);
          g_free (title);

          /* Sticky */
          if (window->on_all_workspaces)
            fputs ("    <sticky/>\n", outfile);

          /* Minimized */
          if (window->minimized)
            fputs ("    <minimized/>\n", outfile);

          /* Maximized */
          if (META_WINDOW_MAXIMIZED (window))
            {
              fprintf (outfile,
                       "    <maximized saved_x=\"%d\" saved_y=\"%d\" saved_width=\"%d\" saved_height=\"%d\"/>\n",
                       window->saved_rect.x,
                       window->saved_rect.y,
                       window->saved_rect.width,
                       window->saved_rect.height);
            }

          /* Workspaces we're on */
          {
            int n;
            n = meta_workspace_index (window->workspace);
            fprintf (outfile,
                     "    <workspace index=\"%d\"/>\n", n);
          }

          /* Gravity */
          {
            int x, y, w, h;
            meta_window_get_geometry (window, &x, &y, &w, &h);

            fprintf (outfile,
                     "    <geometry x=\"%d\" y=\"%d\" width=\"%d\" height=\"%d\" gravity=\"%s\"/>\n",
                     x, y, w, h,
                     meta_gravity_to_string (window->size_hints.win_gravity));
          }

          fputs ("  </window>\n", outfile);
        }
      else
        {
          meta_topic (META_DEBUG_SM, "Not saving window '%s', not session managed\n",
                      window->desc);
        }

      tmp = tmp->next;
      ++stack_position;
    }

  g_slist_free (windows);

  fputs ("</croma_session>\n", outfile);

 out:
  if (outfile)
    {
      /* FIXME need a dialog for this */
      if (ferror (outfile))
        {
          meta_warning (_("Error writing session file '%s': %s\n"),
                        full_save_file (), g_strerror (errno));
        }
      if (fclose (outfile))
        {
          meta_warning (_("Error closing session file '%s': %s\n"),
                        full_save_file (), g_strerror (errno));
        }
    }

  g_free (croma_dir);
  g_free (session_dir);
}

typedef enum
{
  WINDOW_TAG_NONE,
  WINDOW_TAG_DESKTOP,
  WINDOW_TAG_STICKY,
  WINDOW_TAG_MINIMIZED,
  WINDOW_TAG_MAXIMIZED,
  WINDOW_TAG_GEOMETRY
} WindowTag;

typedef struct
{
  MetaWindowSessionInfo *info;
  char *previous_id;
} ParseData;

static void                   session_info_free (MetaWindowSessionInfo *info);
static MetaWindowSessionInfo* session_info_new  (void);

static void start_element_handler (GMarkupParseContext  *context,
                                   const gchar          *element_name,
                                   const gchar         **attribute_names,
                                   const gchar         **attribute_values,
                                   gpointer              user_data,
                                   GError              **error);
static void end_element_handler   (GMarkupParseContext  *context,
                                   const gchar          *element_name,
                                   gpointer              user_data,
                                   GError              **error);
static void text_handler          (GMarkupParseContext  *context,
                                   const gchar          *text,
                                   gsize                 text_len,
                                   gpointer              user_data,
                                   GError              **error);

static GMarkupParser croma_session_parser = {
  start_element_handler,
  end_element_handler,
  text_handler,
  NULL,
  NULL
};

static GSList *window_info_list = NULL;

static char*
load_state (const char *previous_save_file)
{
  GMarkupParseContext *context;
  GError *error;
  ParseData parse_data;
  char *text;
  gsize length;
  char *session_file;

  session_file = g_strconcat (g_get_user_config_dir (),
                              G_DIR_SEPARATOR_S "croma"
                              G_DIR_SEPARATOR_S "sessions" G_DIR_SEPARATOR_S,<--- There is an unknown macro here somewhere. Configuration is required. If G_DIR_SEPARATOR_S is a macro then please configure it.
                              previous_save_file,
                              NULL);

  error = NULL;
  if (!g_file_get_contents (session_file,
                            &text,
                            &length,
                            &error))
    {
      char *canonical_session_file = session_file;

      /* Maybe they were doing it the old way, with ~/.croma */
      session_file = g_strconcat (g_get_home_dir (),
                                  G_DIR_SEPARATOR_S ".croma"
                                  G_DIR_SEPARATOR_S "sessions"
                                  G_DIR_SEPARATOR_S,
                                  previous_save_file,
                                  NULL);

      if (!g_file_get_contents (session_file,
                                &text,
                                &length,
                                NULL))
        {
          /* oh, just give up */

          g_error_free (error);
          g_free (session_file);
          g_free (canonical_session_file);
          return NULL;
        }

      g_free (canonical_session_file);
    }

  meta_topic (META_DEBUG_SM, "Parsing saved session file %s\n", session_file);
  g_free (session_file);
  session_file = NULL;

  parse_data.info = NULL;
  parse_data.previous_id = NULL;

  context = g_markup_parse_context_new (&croma_session_parser,
                                        0, &parse_data, NULL);

  error = NULL;
  if (!g_markup_parse_context_parse (context,
                                     text,
                                     length,
                                     &error))
    goto error;


  error = NULL;
  if (!g_markup_parse_context_end_parse (context, &error))
    goto error;

  g_markup_parse_context_free (context);

  goto out;

 error:

  meta_warning (_("Failed to parse saved session file: %s\n"),
                error->message);
  g_error_free (error);

  if (parse_data.info)
    session_info_free (parse_data.info);

  g_free (parse_data.previous_id);
  parse_data.previous_id = NULL;

 out:

  g_free (text);

  return parse_data.previous_id;
}

/* FIXME this isn't very robust against bogus session files */
static void
start_element_handler  (GMarkupParseContext *context,
                        const gchar         *element_name,
                        const gchar        **attribute_names,
                        const gchar        **attribute_values,
                        gpointer             user_data,
                        GError             **error)
{
  ParseData *pd;

  pd = user_data;

  if (strcmp (element_name, "croma_session") == 0)
    {
      /* Get previous ID */
      int i;

      i = 0;
      while (attribute_names[i])
        {
          const char *name;
          const char *val;

          name = attribute_names[i];
          val = attribute_values[i];

          if (pd->previous_id)
            {
              g_set_error (error,
                           G_MARKUP_ERROR,
                       G_MARKUP_ERROR_PARSE,
                           _("<croma_session> attribute seen but we already have the session ID"));
              return;
            }

          if (strcmp (name, "id") == 0)
            {
              pd->previous_id = decode_text_from_utf8 (val);
            }
          else
            {
              g_set_error (error,
                           G_MARKUP_ERROR,
                           G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
                           _("Unknown attribute %s on <%s> element"),
                           name, "croma_session");
              return;
            }

          ++i;
        }
    }
  else if (strcmp (element_name, "window") == 0)
    {
      int i;

      if (pd->info)
        {
          g_set_error (error,
                       G_MARKUP_ERROR,
                       G_MARKUP_ERROR_PARSE,
                       _("nested <window> tag"));
          return;
        }

      pd->info = session_info_new ();

      i = 0;
      while (attribute_names[i])
        {
          const char *name;
          const char *val;

          name = attribute_names[i];
          val = attribute_values[i];

          if (strcmp (name, "id") == 0)
            {
              if (*val)
                pd->info->id = decode_text_from_utf8 (val);
            }
          else if (strcmp (name, "class") == 0)
            {
              if (*val)
                pd->info->res_class = decode_text_from_utf8 (val);
            }
          else if (strcmp (name, "name") == 0)
            {
              if (*val)
                pd->info->res_name = decode_text_from_utf8 (val);
            }
          else if (strcmp (name, "title") == 0)
            {
              if (*val)
                pd->info->title = g_strdup (val);
            }
          else if (strcmp (name, "role") == 0)
            {
              if (*val)
                pd->info->role = decode_text_from_utf8 (val);
            }
          else if (strcmp (name, "type") == 0)
            {
              if (*val)
                pd->info->type = window_type_from_string (val);
            }
          else if (strcmp (name, "stacking") == 0)
            {
              if (*val)
                {
                  pd->info->stack_position = atoi (val);
                  pd->info->stack_position_set = TRUE;
                }
            }
          else
            {
              g_set_error (error,
                           G_MARKUP_ERROR,
                           G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
                           _("Unknown attribute %s on <%s> element"),
                           name, "window");
              session_info_free (pd->info);
              pd->info = NULL;
              return;
            }

          ++i;
        }
    }
  else if (strcmp (element_name, "workspace") == 0)
    {
      int i;

      i = 0;
      while (attribute_names[i])
        {
          const char *name;

          name = attribute_names[i];

          if (strcmp (name, "index") == 0)
            {
              pd->info->workspace_indices =
                g_slist_prepend (pd->info->workspace_indices,
                                 GINT_TO_POINTER (atoi (attribute_values[i])));
            }
          else
            {
              g_set_error (error,
                           G_MARKUP_ERROR,
                           G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
                           _("Unknown attribute %s on <%s> element"),
                           name, "window");
              session_info_free (pd->info);
              pd->info = NULL;
              return;
            }

          ++i;
        }
    }
  else if (strcmp (element_name, "sticky") == 0)
    {
      pd->info->on_all_workspaces = TRUE;
      pd->info->on_all_workspaces_set = TRUE;
    }
  else if (strcmp (element_name, "minimized") == 0)
    {
      pd->info->minimized = TRUE;
      pd->info->minimized_set = TRUE;
    }
  else if (strcmp (element_name, "maximized") == 0)
    {
      int i;

      i = 0;
      pd->info->maximized = TRUE;
      pd->info->maximized_set = TRUE;
      while (attribute_names[i])
        {
          const char *name;
          const char *val;

          name = attribute_names[i];
          val = attribute_values[i];

          if (strcmp (name, "saved_x") == 0)
            {
              if (*val)
                {
                  pd->info->saved_rect.x = atoi (val);
                  pd->info->saved_rect_set = TRUE;
                }
            }
          else if (strcmp (name, "saved_y") == 0)
            {
              if (*val)
                {
                  pd->info->saved_rect.y = atoi (val);
                  pd->info->saved_rect_set = TRUE;
                }
            }
          else if (strcmp (name, "saved_width") == 0)
            {
              if (*val)
                {
                  pd->info->saved_rect.width = atoi (val);
                  pd->info->saved_rect_set = TRUE;
                }
            }
          else if (strcmp (name, "saved_height") == 0)
            {
              if (*val)
                {
                  pd->info->saved_rect.height = atoi (val);
                  pd->info->saved_rect_set = TRUE;
                }
            }
          else
            {
              g_set_error (error,
                           G_MARKUP_ERROR,
                           G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
                           _("Unknown attribute %s on <%s> element"),
                           name, "maximized");
              return;
            }

          ++i;
        }

      if (pd->info->saved_rect_set)
        meta_topic (META_DEBUG_SM, "Saved unmaximized size %d,%d %dx%d \n",
                    pd->info->saved_rect.x,
                    pd->info->saved_rect.y,
                    pd->info->saved_rect.width,
                    pd->info->saved_rect.height);
    }
  else if (strcmp (element_name, "geometry") == 0)
    {
      int i;

      pd->info->geometry_set = TRUE;

      i = 0;
      while (attribute_names[i])
        {
          const char *name;
          const char *val;

          name = attribute_names[i];
          val = attribute_values[i];

          if (strcmp (name, "x") == 0)
            {
              if (*val)
                pd->info->rect.x = atoi (val);
            }
          else if (strcmp (name, "y") == 0)
            {
              if (*val)
                pd->info->rect.y = atoi (val);
            }
          else if (strcmp (name, "width") == 0)
            {
              if (*val)
                pd->info->rect.width = atoi (val);
            }
          else if (strcmp (name, "height") == 0)
            {
              if (*val)
                pd->info->rect.height = atoi (val);
            }
          else if (strcmp (name, "gravity") == 0)
            {
              if (*val)
                pd->info->gravity = window_gravity_from_string (val);
            }
          else
            {
              g_set_error (error,
                           G_MARKUP_ERROR,
                           G_MARKUP_ERROR_UNKNOWN_ATTRIBUTE,
                           _("Unknown attribute %s on <%s> element"),
                           name, "geometry");
              return;
            }

          ++i;
        }

      meta_topic (META_DEBUG_SM, "Loaded geometry %d,%d %dx%d gravity %s\n",
                  pd->info->rect.x,
                  pd->info->rect.y,
                  pd->info->rect.width,
                  pd->info->rect.height,
                  meta_gravity_to_string (pd->info->gravity));
    }
  else
    {
      g_set_error (error,
                   G_MARKUP_ERROR,
                   G_MARKUP_ERROR_UNKNOWN_ELEMENT,
                   _("Unknown element %s"),
                   element_name);
      return;
    }
}

static void
end_element_handler    (GMarkupParseContext *context,
                        const gchar         *element_name,
                        gpointer             user_data,
                        GError             **error)
{
  ParseData *pd;

  pd = user_data;

  if (strcmp (element_name, "window") == 0)
    {
      g_assert (pd->info);

      window_info_list = g_slist_prepend (window_info_list,
                                          pd->info);

      meta_topic (META_DEBUG_SM, "Loaded window info from session with class: %s name: %s role: %s\n",
                  pd->info->res_class ? pd->info->res_class : "(none)",
                  pd->info->res_name ? pd->info->res_name : "(none)",
                  pd->info->role ? pd->info->role : "(none)");

      pd->info = NULL;
    }
}

static void
text_handler           (GMarkupParseContext *context,
                        const gchar         *text,
                        gsize                text_len,
                        gpointer             user_data,
                        GError             **error)
{
  /* Right now we don't have any elements where we care about their
   * content
   */
}

static gboolean
both_null_or_matching (const char *a,
                       const char *b)
{
  if (a == NULL && b == NULL)
    return TRUE;
  else if (a && b && strcmp (a, b) == 0)
    return TRUE;
  else
    return FALSE;
}

static GSList*
get_possible_matches (MetaWindow *window)
{
  /* Get all windows with this client ID */
  GSList *retval;
  GSList *tmp;
  gboolean ignore_client_id;

  retval = NULL;

  ignore_client_id = g_getenv ("CROMA_DEBUG_SM") != NULL;

  tmp = window_info_list;
  while (tmp != NULL)
    {
      MetaWindowSessionInfo *info;

      info = tmp->data;

      if ((ignore_client_id ||
           both_null_or_matching (info->id, window->sm_client_id)) &&
          both_null_or_matching (info->res_class, window->res_class) &&
          both_null_or_matching (info->res_name, window->res_name) &&
          both_null_or_matching (info->role, window->role))
        {
          meta_topic (META_DEBUG_SM, "Window %s may match saved window with class: %s name: %s role: %s\n",
                      window->desc,
                      info->res_class ? info->res_class : "(none)",
                      info->res_name ? info->res_name : "(none)",
                      info->role ? info->role : "(none)");

          retval = g_slist_prepend (retval, info);
        }
      else
        {
          if (meta_is_verbose ())
            {
              if (!both_null_or_matching (info->id, window->sm_client_id))
                meta_topic (META_DEBUG_SM, "Window %s has SM client ID %s, saved state has %s, no match\n",
                            window->desc,
                            window->sm_client_id ? window->sm_client_id : "(none)",
                            info->id ? info->id : "(none)");
              else if (!both_null_or_matching (info->res_class, window->res_class))
                meta_topic (META_DEBUG_SM, "Window %s has class %s doesn't match saved class %s, no match\n",
                            window->desc,
                            window->res_class ? window->res_class : "(none)",
                            info->res_class ? info->res_class : "(none)");

              else if (!both_null_or_matching (info->res_name, window->res_name))
                meta_topic (META_DEBUG_SM, "Window %s has name %s doesn't match saved name %s, no match\n",
                            window->desc,
                            window->res_name ? window->res_name : "(none)",
                            info->res_name ? info->res_name : "(none)");
              else if (!both_null_or_matching (info->role, window->role))
                meta_topic (META_DEBUG_SM, "Window %s has role %s doesn't match saved role %s, no match\n",
                            window->desc,
                            window->role ? window->role : "(none)",
                            info->role ? info->role : "(none)");
              else
                meta_topic (META_DEBUG_SM, "???? should not happen - window %s doesn't match saved state %s for no good reason\n",
                            window->desc, info->id);
            }
        }

      tmp = tmp->next;
    }

  return retval;
}

static const MetaWindowSessionInfo*
find_best_match (GSList     *infos,
                 MetaWindow *window)
{
  GSList *tmp;
  const MetaWindowSessionInfo *matching_title;
  const MetaWindowSessionInfo *matching_type;

  matching_title = NULL;
  matching_type = NULL;

  tmp = infos;
  while (tmp != NULL)
    {
      MetaWindowSessionInfo *info;

      info = tmp->data;

      if (matching_title == NULL &&
          both_null_or_matching (info->title, window->title))
        matching_title = info;

      if (matching_type == NULL &&
          info->type == window->type)
        matching_type = info;

      tmp = tmp->next;
    }

  /* Prefer same title, then same type of window, then
   * just pick something. Eventually we could enhance this
   * to e.g. break ties by geometry hint similarity,
   * or other window features.
   */

  if (matching_title)
    return matching_title;
  else if (matching_type)
    return matching_type;
  else
    return infos->data;
}

const MetaWindowSessionInfo*
meta_window_lookup_saved_state (MetaWindow *window)
{
  GSList *possibles;
  const MetaWindowSessionInfo *info;

  /* Window is not session managed.
   * I haven't yet figured out how to deal with these
   * in a way that doesn't cause broken side effects in
   * situations other than on session restore.
   */
  if (window->sm_client_id == NULL)
    {
      meta_topic (META_DEBUG_SM,
                  "Window %s is not session managed, not checking for saved state\n",
                  window->desc);
      return NULL;
    }

  possibles = get_possible_matches (window);

  if (possibles == NULL)
    {
      meta_topic (META_DEBUG_SM, "Window %s has no possible matches in the list of saved window states\n",
                  window->desc);
      return NULL;
    }

  info = find_best_match (possibles, window);

  g_slist_free (possibles);

  return info;
}

void
meta_window_release_saved_state (const MetaWindowSessionInfo *info)
{
  /* We don't want to use the same saved state again for another
   * window.
   */
  window_info_list = g_slist_remove (window_info_list, info);

  session_info_free ((MetaWindowSessionInfo*) info);
}

static void
session_info_free (MetaWindowSessionInfo *info)
{
  g_free (info->id);
  g_free (info->res_class);
  g_free (info->res_name);
  g_free (info->title);
  g_free (info->role);

  g_slist_free (info->workspace_indices);

  g_free (info);
}

static MetaWindowSessionInfo*
session_info_new (void)
{
  MetaWindowSessionInfo *info;

  info = g_new0 (MetaWindowSessionInfo, 1);

  info->type = META_WINDOW_NORMAL;
  info->gravity = NorthWestGravity;

  return info;
}

static char* full_save_path = NULL;

static void
regenerate_save_file (void)
{
  g_free (full_save_path);

  if (client_id)
    full_save_path = g_strconcat (g_get_user_config_dir (),
                                  G_DIR_SEPARATOR_S "croma"
                                  G_DIR_SEPARATOR_S "sessions" G_DIR_SEPARATOR_S,
                                  client_id,
                                  ".ms",
                                  NULL);
  else
    full_save_path = NULL;
}

static const char*
full_save_file (void)
{
  return full_save_path;
}

static int
windows_cmp_by_title (MetaWindow *a,
                      MetaWindow *b)
{
  return g_utf8_collate (a->title, b->title);
}

static void
finish_interact (gboolean shutdown)
{
  if (current_state == STATE_DONE_WITH_INTERACT) /* paranoia */
    {
      SmcInteractDone (session_connection, False /* don't cancel logout */);

      save_yourself_possibly_done (shutdown, TRUE);
    }
}

static void
dialog_closed (GPid pid, int status, gpointer user_data)
{
  gboolean shutdown = GPOINTER_TO_INT (user_data);

  if (WIFEXITED (status) && WEXITSTATUS (status) == 0) /* pressed "OK" */
    {
      finish_interact (shutdown);
    }
}

static void
warn_about_lame_clients_and_finish_interact (gboolean shutdown)
{
  GSList *lame = NULL;
  GSList *windows;
  GSList *lame_details = NULL;
  GSList *tmp;
  GSList *columns = NULL;
  GPid pid;

  windows = meta_display_list_windows (meta_get_display ());
  tmp = windows;
  while (tmp != NULL)
    {
      MetaWindow *window;

      window = tmp->data;

      /* only complain about normal windows, the others
       * are kind of dumb to worry about
       */
      if (window->sm_client_id == NULL &&
          window->type == META_WINDOW_NORMAL)
        lame = g_slist_prepend (lame, window);

      tmp = tmp->next;
    }

  g_slist_free (windows);

  if (lame == NULL)
    {
      /* No lame apps. */
      finish_interact (shutdown);
      return;
    }

  columns = g_slist_prepend (columns, "Window");
  columns = g_slist_prepend (columns, "Class");

  lame = g_slist_sort (lame, (GCompareFunc) windows_cmp_by_title);

  tmp = lame;
  while (tmp != NULL)
    {
      MetaWindow *w = tmp->data;

      lame_details = g_slist_prepend (lame_details,
                                      w->res_class ? w->res_class : "");
      lame_details = g_slist_prepend (lame_details,
                                      w->title);

      tmp = tmp->next;
    }
  g_slist_free (lame);

  pid = meta_show_dialog("--list",
                         _("These windows do not support &quot;save current setup&quot; "
                           "and will have to be restarted manually next time "
                           "you log in."),
                         "240",
                         meta_get_display()->active_screen->screen_name,
                         NULL, NULL,
                         None,
                         columns,
                         lame_details);

  g_slist_free (lame_details);

  g_child_watch_add (pid, dialog_closed, GINT_TO_POINTER (shutdown));
}

#endif /* HAVE_SM */