summaryrefslogtreecommitdiff
path: root/mate-session/gsm-manager.c
blob: 260836a2dd60a740239d0d7e23831e104df2c8e2 (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
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
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
/* -*- Mode: C; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 8 -*-
 *
 * Copyright (C) 2007 Novell, Inc.
 * Copyright (C) 2008 Red Hat, Inc.
 * Copyright (C) 2008 William Jon McCann <jmccann@redhat.com>
 *
 * 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 <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
#include <signal.h>
#include <sys/stat.h>
#include <sys/types.h>

#include <glib.h>
#include <glib/gi18n.h>
#include <glib/gstdio.h>
#include <glib-object.h>
#include <dbus/dbus-glib.h>
#include <dbus/dbus-glib-lowlevel.h>

#include <gtk/gtk.h> /* for logout dialog */
#include <gio/gio.h> /* for gsettings */
#include <gdk/gdkx.h>

#include "gsm-manager.h"
#include "gsm-manager-glue.h"

#include "gsm-store.h"
#include "gsm-inhibitor.h"
#include "gsm-presence.h"

#include "gsm-xsmp-client.h"
#include "gsm-dbus-client.h"

#include "gsm-autostart-app.h"

#include "gsm-util.h"
#include "mdm.h"
#include "gsm-logout-dialog.h"
#include "gsm-inhibit-dialog.h"
#include "gsm-consolekit.h"
#ifdef HAVE_SYSTEMD
#include "gsm-systemd.h"
#endif
#include "gsm-session-save.h"

#define GSM_MANAGER_GET_PRIVATE(o) (G_TYPE_INSTANCE_GET_PRIVATE ((o), GSM_TYPE_MANAGER, GsmManagerPrivate))

#define GSM_MANAGER_DBUS_PATH "/org/gnome/SessionManager"
#define GSM_MANAGER_DBUS_NAME "org.gnome.SessionManager"

#define GSM_MANAGER_PHASE_TIMEOUT 30 /* seconds */

/* In the exit phase, all apps were already given the chance to inhibit the session end
 * At that stage we don't want to wait much for apps to respond, we want to exit, and fast.
 */
#define GSM_MANAGER_EXIT_PHASE_TIMEOUT 1 /* seconds */

#define MDM_FLEXISERVER_COMMAND "mdmflexiserver"
#define MDM_FLEXISERVER_ARGS    "--startnew Standard"

#define GDM_FLEXISERVER_COMMAND "gdmflexiserver"
#define GDM_FLEXISERVER_ARGS    "--startnew Standard"


#define LOCKDOWN_SCHEMA              "org.mate.lockdown"
#define KEY_LOCK_DISABLE             "disable-lock-screen"
#define KEY_LOG_OUT_DISABLE          "disable-log-out"
#define KEY_USER_SWITCH_DISABLE      "disable-user-switching"

#define SESSION_SCHEMA               "org.mate.session"
#define KEY_IDLE_DELAY               "idle-delay"
#define KEY_AUTOSAVE                 "auto-save-session"

#define SCREENSAVER_SCHEMA           "org.mate.screensaver"
#define KEY_SLEEP_LOCK               "lock-enabled"

#ifdef __GNUC__
#define UNUSED_VARIABLE __attribute__ ((unused))
#else
#define UNUSED_VARIABLE
#endif

typedef enum
{
        GSM_MANAGER_LOGOUT_NONE,
        GSM_MANAGER_LOGOUT_LOGOUT,
        GSM_MANAGER_LOGOUT_REBOOT,
        GSM_MANAGER_LOGOUT_REBOOT_INTERACT,
        GSM_MANAGER_LOGOUT_REBOOT_MDM,
        GSM_MANAGER_LOGOUT_SHUTDOWN,
        GSM_MANAGER_LOGOUT_SHUTDOWN_INTERACT,
        GSM_MANAGER_LOGOUT_SHUTDOWN_MDM
} GsmManagerLogoutType;

typedef struct {
        gboolean                failsafe;
        GsmStore               *clients;
        GsmStore               *inhibitors;
        GsmStore               *apps;
        GsmPresence            *presence;

        /* Current status */
        GsmManagerPhase         phase;
        guint                   phase_timeout_id;
        GSList                 *pending_apps;
        GsmManagerLogoutMode    logout_mode;
        GSList                 *query_clients;
        guint                   query_timeout_id;
        /* This is used for GSM_MANAGER_PHASE_END_SESSION only at the moment,
         * since it uses a sublist of all running client that replied in a
         * specific way */
        GSList                 *next_query_clients;
        /* This is the action that will be done just before we exit */
        GsmManagerLogoutType    logout_type;

        GtkWidget              *inhibit_dialog;

        /* List of clients which were disconnected due to disabled condition
         * and shouldn't be automatically restarted */
        GSList                 *condition_clients;

        GSettings              *settings_session;
        GSettings              *settings_lockdown;
        GSettings              *settings_screensaver;

        const char             *renderer;

        DBusGProxy             *bus_proxy;
        DBusGConnection        *connection;
        gboolean                dbus_disconnected : 1;
} GsmManagerPrivate;

enum {
        PROP_0,
        PROP_CLIENT_STORE,
        PROP_RENDERER,
        PROP_FAILSAFE
};

enum {
        PHASE_CHANGED,
        CLIENT_ADDED,
        CLIENT_REMOVED,
        INHIBITOR_ADDED,
        INHIBITOR_REMOVED,
        SESSION_RUNNING,
        SESSION_OVER,
        LAST_SIGNAL
};

static guint signals [LAST_SIGNAL] = { 0 };

static void     gsm_manager_finalize    (GObject         *object);

static gboolean _log_out_is_locked_down     (GsmManager *manager);
static gboolean _switch_user_is_locked_down (GsmManager *manager);

static void     _handle_client_end_session_response (GsmManager *manager,
                                                     GsmClient  *client,
                                                     gboolean    is_ok,
                                                     gboolean    do_last,
                                                     gboolean    cancel,
                                                     const char *reason);

static gboolean auto_save_is_enabled (GsmManager *manager);
static void     maybe_save_session   (GsmManager *manager);

static gpointer manager_object = NULL;

G_DEFINE_TYPE_WITH_PRIVATE (GsmManager, gsm_manager, G_TYPE_OBJECT)

GQuark
gsm_manager_error_quark (void)
{
        static GQuark ret = 0;
        if (ret == 0) {
                ret = g_quark_from_static_string ("gsm_manager_error");
        }

        return ret;
}

#define ENUM_ENTRY(NAME, DESC) { NAME, "" #NAME "", DESC }

GType
gsm_manager_error_get_type (void)
{
        static GType etype = 0;

        if (etype == 0) {
                static const GEnumValue values[] = {
                        ENUM_ENTRY (GSM_MANAGER_ERROR_GENERAL, "GeneralError"),
                        ENUM_ENTRY (GSM_MANAGER_ERROR_NOT_IN_INITIALIZATION, "NotInInitialization"),
                        ENUM_ENTRY (GSM_MANAGER_ERROR_NOT_IN_RUNNING, "NotInRunning"),
                        ENUM_ENTRY (GSM_MANAGER_ERROR_ALREADY_REGISTERED, "AlreadyRegistered"),
                        ENUM_ENTRY (GSM_MANAGER_ERROR_NOT_REGISTERED, "NotRegistered"),
                        ENUM_ENTRY (GSM_MANAGER_ERROR_INVALID_OPTION, "InvalidOption"),
                        ENUM_ENTRY (GSM_MANAGER_ERROR_LOCKED_DOWN, "LockedDown"),
                        { 0, 0, 0 }
                };

                g_assert (GSM_MANAGER_NUM_ERRORS == G_N_ELEMENTS (values) - 1);

                etype = g_enum_register_static ("GsmManagerError", values);
        }

        return etype;
}

static gboolean
_debug_client (const char *id,
               GsmClient  *client,
               GsmManager *manager)
{
        g_debug ("GsmManager: Client %s", gsm_client_peek_id (client));
        return FALSE;
}

static void
debug_clients (GsmManager *manager)
{
        GsmManagerPrivate *priv;
        priv = gsm_manager_get_instance_private (manager);
        gsm_store_foreach (priv->clients,
                           (GsmStoreFunc)_debug_client,
                           manager);
}

static gboolean
_debug_inhibitor (const char    *id,
                  GsmInhibitor  *inhibitor,
                  GsmManager    *manager)
{
        g_debug ("GsmManager: Inhibitor app:%s client:%s bus-name:%s reason:%s",
                 gsm_inhibitor_peek_app_id (inhibitor),
                 gsm_inhibitor_peek_client_id (inhibitor),
                 gsm_inhibitor_peek_bus_name (inhibitor),
                 gsm_inhibitor_peek_reason (inhibitor));
        return FALSE;
}

static void
debug_inhibitors (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        gsm_store_foreach (priv->inhibitors,
                           (GsmStoreFunc)_debug_inhibitor,
                           manager);
}

static gboolean
_find_by_cookie (const char   *id,
                 GsmInhibitor *inhibitor,
                 guint        *cookie_ap)
{
        guint cookie_b;

        cookie_b = gsm_inhibitor_peek_cookie (inhibitor);

        return (*cookie_ap == cookie_b);
}

static gboolean
_find_by_startup_id (const char *id,
                     GsmClient  *client,
                     const char *startup_id_a)
{
        const char *startup_id_b;

        startup_id_b = gsm_client_peek_startup_id (client);
        if (IS_STRING_EMPTY (startup_id_b)) {
                return FALSE;
        }

        return (strcmp (startup_id_a, startup_id_b) == 0);
}

static void
app_condition_changed (GsmApp     *app,
                       gboolean    condition,
                       GsmManager *manager)
{
        GsmClient *client;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        g_debug ("GsmManager: app:%s condition changed condition:%d",
                 gsm_app_peek_id (app),
                 condition);

        client = (GsmClient *)gsm_store_find (priv->clients,
                                              (GsmStoreFunc)_find_by_startup_id,
                                              (char *)gsm_app_peek_startup_id (app));

        if (condition) {
                if (!gsm_app_is_running (app) && client == NULL) {
                        GError  *error = NULL;
                        gboolean UNUSED_VARIABLE res;

                        g_debug ("GsmManager: starting app '%s'", gsm_app_peek_id (app));

                        res = gsm_app_start (app, &error);
                        if (error != NULL) {
                                g_warning ("Not able to start app from its condition: %s",
                                           error->message);
                                g_error_free (error);
                        }
                } else {
                        g_debug ("GsmManager: not starting - app still running '%s'", gsm_app_peek_id (app));
                }
        } else {
                GError  *error;
                gboolean UNUSED_VARIABLE res;

                if (client != NULL) {
                        /* Kill client in case condition if false and make sure it won't
                         * be automatically restarted by adding the client to
                         * condition_clients */
                        priv->condition_clients =
                                g_slist_prepend (priv->condition_clients, client);

                        g_debug ("GsmManager: stopping client %s for app", gsm_client_peek_id (client));

                        error = NULL;
                        res = gsm_client_stop (client, &error);
                        if (error != NULL) {
                                g_warning ("Not able to stop app client from its condition: %s",
                                           error->message);
                                g_error_free (error);
                        }
                } else {
                        g_debug ("GsmManager: stopping app %s", gsm_app_peek_id (app));

                        /* If we don't have a client then we should try to kill the app,
                         * if it is running */
                        error = NULL;
                        if (gsm_app_is_running (app)) {
                                res = gsm_app_stop (app, &error);
                                if (error != NULL) {
                                       g_warning ("Not able to stop app from its condition: %s",
                                                error->message);
                                   g_error_free (error);
                                }
                        }
                }
        }
}

static const char *
phase_num_to_name (guint phase)
{
        const char *name;

        switch (phase) {
        case GSM_MANAGER_PHASE_STARTUP:
                name = "STARTUP";
                break;
        case GSM_MANAGER_PHASE_INITIALIZATION:
                name = "INITIALIZATION";
                break;
        case GSM_MANAGER_PHASE_WINDOW_MANAGER:
                name = "WINDOW_MANAGER";
                break;
        case GSM_MANAGER_PHASE_PANEL:
                name = "PANEL";
                break;
        case GSM_MANAGER_PHASE_DESKTOP:
                name = "DESKTOP";
                break;
        case GSM_MANAGER_PHASE_APPLICATION:
                name = "APPLICATION";
                break;
        case GSM_MANAGER_PHASE_RUNNING:
                name = "RUNNING";
                break;
        case GSM_MANAGER_PHASE_QUERY_END_SESSION:
                name = "QUERY_END_SESSION";
                break;
        case GSM_MANAGER_PHASE_END_SESSION:
                name = "END_SESSION";
                break;
        case GSM_MANAGER_PHASE_EXIT:
                name = "EXIT";
                break;
        default:
                g_assert_not_reached ();
                break;
        }

        return name;
}

static void start_phase (GsmManager *manager);

static void
quit_request_completed_consolekit (GsmConsolekit *consolekit,
                                   GError        *error,
                                   gpointer       user_data)
{
        MdmLogoutAction fallback_action = GPOINTER_TO_INT (user_data);

        if (error != NULL) {
                mdm_set_logout_action (fallback_action);
        }

        g_object_unref (consolekit);

        gtk_main_quit ();
}

#ifdef HAVE_SYSTEMD
static void
quit_request_completed_systemd (GsmSystemd *systemd,
                                GError     *error,
                                gpointer    user_data)
{
        MdmLogoutAction fallback_action = GPOINTER_TO_INT (user_data);

        if (error != NULL) {
                mdm_set_logout_action (fallback_action);
        }

        g_object_unref (systemd);

        gtk_main_quit ();
}
#endif

static void
gsm_manager_quit (GsmManager *manager)
{
        GsmConsolekit *consolekit;
        GsmManagerPrivate *priv;
#ifdef HAVE_SYSTEMD
        GsmSystemd *systemd;
#endif

        priv = gsm_manager_get_instance_private (manager);
        /* See the comment in request_reboot() for some more details about how
         * this works. */

        switch (priv->logout_type) {
        case GSM_MANAGER_LOGOUT_LOGOUT:
                gtk_main_quit ();
                break;
        case GSM_MANAGER_LOGOUT_REBOOT:
        case GSM_MANAGER_LOGOUT_REBOOT_INTERACT:
                mdm_set_logout_action (MDM_LOGOUT_ACTION_NONE);

#ifdef HAVE_SYSTEMD
                if (LOGIND_RUNNING()) {
                    systemd = gsm_get_systemd ();
                    g_signal_connect (systemd,
                                      "request-completed",
                                      G_CALLBACK (quit_request_completed_systemd),
                                      GINT_TO_POINTER (MDM_LOGOUT_ACTION_REBOOT));
                    gsm_systemd_attempt_restart (systemd);
                }
                else {
#endif
                consolekit = gsm_get_consolekit ();
                g_signal_connect (consolekit,
                                  "request-completed",
                                  G_CALLBACK (quit_request_completed_consolekit),
                                  GINT_TO_POINTER (MDM_LOGOUT_ACTION_REBOOT));
                gsm_consolekit_attempt_restart (consolekit);
#ifdef HAVE_SYSTEMD
                }
#endif
                break;
        case GSM_MANAGER_LOGOUT_REBOOT_MDM:
                mdm_set_logout_action (MDM_LOGOUT_ACTION_REBOOT);
                gtk_main_quit ();
                break;
        case GSM_MANAGER_LOGOUT_SHUTDOWN:
        case GSM_MANAGER_LOGOUT_SHUTDOWN_INTERACT:
                mdm_set_logout_action (MDM_LOGOUT_ACTION_NONE);

#ifdef HAVE_SYSTEMD
                if (LOGIND_RUNNING()) {
                    systemd = gsm_get_systemd ();
                    g_signal_connect (systemd,
                                      "request-completed",
                                      G_CALLBACK (quit_request_completed_systemd),
                                      GINT_TO_POINTER (MDM_LOGOUT_ACTION_SHUTDOWN));
                    gsm_systemd_attempt_stop (systemd);
                }
                else {
#endif
                consolekit = gsm_get_consolekit ();
                g_signal_connect (consolekit,
                                  "request-completed",
                                  G_CALLBACK (quit_request_completed_consolekit),
                                  GINT_TO_POINTER (MDM_LOGOUT_ACTION_SHUTDOWN));
                gsm_consolekit_attempt_stop (consolekit);
#ifdef HAVE_SYSTEMD
                }
#endif
                break;
        case GSM_MANAGER_LOGOUT_SHUTDOWN_MDM:
                mdm_set_logout_action (MDM_LOGOUT_ACTION_SHUTDOWN);
                gtk_main_quit ();
                break;
        default:
                g_assert_not_reached ();
                break;
        }
}

static void
end_phase (GsmManager *manager)
{
        GsmManagerPrivate *priv;
        gboolean start_next_phase = TRUE;

        priv = gsm_manager_get_instance_private (manager);

        g_debug ("GsmManager: ending phase %s\n",
                 phase_num_to_name (priv->phase));

        g_slist_free (priv->pending_apps);
        priv->pending_apps = NULL;

        g_slist_free (priv->query_clients);
        priv->query_clients = NULL;

        g_slist_free (priv->next_query_clients);
        priv->next_query_clients = NULL;

        if (priv->phase_timeout_id > 0) {
                g_source_remove (priv->phase_timeout_id);
                priv->phase_timeout_id = 0;
        }

        switch (priv->phase) {
        case GSM_MANAGER_PHASE_STARTUP:
        case GSM_MANAGER_PHASE_INITIALIZATION:
        case GSM_MANAGER_PHASE_WINDOW_MANAGER:
        case GSM_MANAGER_PHASE_PANEL:
        case GSM_MANAGER_PHASE_DESKTOP:
        case GSM_MANAGER_PHASE_APPLICATION:
                break;
        case GSM_MANAGER_PHASE_RUNNING:
                if (_log_out_is_locked_down (manager)) {
                        g_warning ("Unable to logout: Logout has been locked down");
                        start_next_phase = FALSE;
                }
                break;
        case GSM_MANAGER_PHASE_QUERY_END_SESSION:
                break;
        case GSM_MANAGER_PHASE_END_SESSION:
                if (auto_save_is_enabled (manager))
                        maybe_save_session (manager);
                break;
        case GSM_MANAGER_PHASE_EXIT:
                start_next_phase = FALSE;
                gsm_manager_quit (manager);
                break;
        default:
                g_assert_not_reached ();
                break;
        }

        if (start_next_phase) {
                priv->phase++;
                start_phase (manager);
        }
}

static void
app_registered (GsmApp     *app,
                GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        priv->pending_apps = g_slist_remove (priv->pending_apps, app);
        g_signal_handlers_disconnect_by_func (app, app_registered, manager);

        if (priv->pending_apps == NULL) {
                if (priv->phase_timeout_id > 0) {
                        g_source_remove (priv->phase_timeout_id);
                        priv->phase_timeout_id = 0;
                }

                end_phase (manager);
        }
}

static gboolean
on_phase_timeout (GsmManager *manager)
{
        GSList *a;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        priv->phase_timeout_id = 0;

        switch (priv->phase) {
        case GSM_MANAGER_PHASE_STARTUP:
        case GSM_MANAGER_PHASE_INITIALIZATION:
        case GSM_MANAGER_PHASE_WINDOW_MANAGER:
        case GSM_MANAGER_PHASE_PANEL:
        case GSM_MANAGER_PHASE_DESKTOP:
        case GSM_MANAGER_PHASE_APPLICATION:
                for (a = priv->pending_apps; a; a = a->next) {
                        g_warning ("Application '%s' failed to register before timeout",
                                   gsm_app_peek_app_id (a->data));
                        g_signal_handlers_disconnect_by_func (a->data, app_registered, manager);
                        /* FIXME: what if the app was filling in a required slot? */
                }
                break;
        case GSM_MANAGER_PHASE_RUNNING:
                break;
        case GSM_MANAGER_PHASE_QUERY_END_SESSION:
        case GSM_MANAGER_PHASE_END_SESSION:
                break;
        case GSM_MANAGER_PHASE_EXIT:
                break;
        default:
                g_assert_not_reached ();
                break;
        }

        end_phase (manager);

        return FALSE;
}

static gboolean
_autostart_delay_timeout (GsmApp *app)
{
        GError *error = NULL;
        gboolean res;

        if (!gsm_app_peek_is_disabled (app)
            && !gsm_app_peek_is_conditionally_disabled (app)) {
                res = gsm_app_start (app, &error);
                if (!res) {
                        if (error != NULL) {
                                g_warning ("Could not launch application '%s': %s",
                                           gsm_app_peek_app_id (app),
                                           error->message);
                                g_error_free (error);
                        }
                }
        }

        g_object_unref (app);

        return FALSE;
}

static gboolean
_start_app (const char *id,
            GsmApp     *app,
            GsmManager *manager)
{
        GError  *error;
        gboolean res;
        int      delay;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        if (gsm_app_peek_phase (app) != priv->phase) {
                goto out;
        }

        /* Keep track of app autostart condition in order to react
         * accordingly in the future. */
        g_signal_connect (app,
                          "condition-changed",
                          G_CALLBACK (app_condition_changed),
                          manager);

        if (gsm_app_peek_is_disabled (app)
            || gsm_app_peek_is_conditionally_disabled (app)) {
                g_debug ("GsmManager: Skipping disabled app: %s", id);
                goto out;
        }

        delay = gsm_app_peek_autostart_delay (app);
        if (delay > 0) {
                g_timeout_add_seconds (delay,
                                       (GSourceFunc)_autostart_delay_timeout,
                                       g_object_ref (app));
                g_debug ("GsmManager: %s is scheduled to start in %d seconds", id, delay);
                goto out;
        }

        error = NULL;
        res = gsm_app_start (app, &error);
        if (!res) {
                if (error != NULL) {
                        g_warning ("Could not launch application '%s': %s",
                                   gsm_app_peek_app_id (app),
                                   error->message);
                        g_error_free (error);
                        error = NULL;
                }
                goto out;
        }

        if (priv->phase < GSM_MANAGER_PHASE_APPLICATION) {
                g_signal_connect (app,
                                  "exited",
                                  G_CALLBACK (app_registered),
                                  manager);
                g_signal_connect (app,
                                  "registered",
                                  G_CALLBACK (app_registered),
                                  manager);
                priv->pending_apps = g_slist_prepend (priv->pending_apps, app);
        }
 out:
        return FALSE;
}

static void
do_phase_startup (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        gsm_store_foreach (priv->apps,
                           (GsmStoreFunc)_start_app,
                           manager);

        if (priv->pending_apps != NULL) {
                if (priv->phase < GSM_MANAGER_PHASE_APPLICATION) {
                        priv->phase_timeout_id = g_timeout_add_seconds (GSM_MANAGER_PHASE_TIMEOUT,
                                                                        (GSourceFunc)on_phase_timeout,
                                                                        manager);
                }
        } else {
                end_phase (manager);
        }
}

typedef struct {
        GsmManager *manager;
        guint       flags;
} ClientEndSessionData;


static gboolean
_client_end_session (GsmClient            *client,
                     ClientEndSessionData *data)
{
        gboolean ret;
        GError  *error;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (data->manager);

        error = NULL;
        ret = gsm_client_end_session (client, data->flags, &error);
        if (! ret) {
                g_warning ("Unable to query client: %s", error->message);
                g_error_free (error);
                /* FIXME: what should we do if we can't communicate with client? */
        } else {
                g_debug ("GsmManager: adding client to end-session clients: %s", gsm_client_peek_id (client));
                priv->query_clients = g_slist_prepend (priv->query_clients,
                                                       client);
        }

        return FALSE;
}

static gboolean
_client_end_session_helper (const char           *id,
                            GsmClient            *client,
                            ClientEndSessionData *data)
{
        return _client_end_session (client, data);
}

static void
do_phase_end_session (GsmManager *manager)
{
        ClientEndSessionData data;
        GsmManagerPrivate *priv;

        data.manager = manager;
        data.flags = 0;
        priv = gsm_manager_get_instance_private (manager);

        if (priv->logout_mode == GSM_MANAGER_LOGOUT_MODE_FORCE) {
                data.flags |= GSM_CLIENT_END_SESSION_FLAG_FORCEFUL;
        }
        if (auto_save_is_enabled (manager)) {
                data.flags |= GSM_CLIENT_END_SESSION_FLAG_SAVE;
        }

        if (priv->phase_timeout_id > 0) {
                g_source_remove (priv->phase_timeout_id);
                priv->phase_timeout_id = 0;
        }

        if (gsm_store_size (priv->clients) > 0) {
                priv->phase_timeout_id = g_timeout_add_seconds (GSM_MANAGER_PHASE_TIMEOUT,
                                                                (GSourceFunc)on_phase_timeout,
                                                                manager);

                gsm_store_foreach (priv->clients,
                                   (GsmStoreFunc)_client_end_session_helper,
                                   &data);
        } else {
                end_phase (manager);
        }
}

static void
do_phase_end_session_part_2 (GsmManager *manager)
{
        ClientEndSessionData data;
        GsmManagerPrivate *priv;

        data.manager = manager;
        data.flags = 0;
        priv = gsm_manager_get_instance_private (manager);

        if (priv->logout_mode == GSM_MANAGER_LOGOUT_MODE_FORCE) {
                data.flags |= GSM_CLIENT_END_SESSION_FLAG_FORCEFUL;
        }
        if (auto_save_is_enabled (manager)) {
                data.flags |= GSM_CLIENT_END_SESSION_FLAG_SAVE;
        }
        data.flags |= GSM_CLIENT_END_SESSION_FLAG_LAST;

        /* keep the timeout that was started at the beginning of the
         * GSM_MANAGER_PHASE_END_SESSION phase */

        if (g_slist_length (priv->next_query_clients) > 0) {
                g_slist_foreach (priv->next_query_clients,
                                 (GFunc)_client_end_session,
                                 &data);

                g_slist_free (priv->next_query_clients);
                priv->next_query_clients = NULL;
        } else {
                end_phase (manager);
        }
}

static gboolean
_client_stop (const char *id,
              GsmClient  *client,
              gpointer    user_data)
{
        gboolean ret;
        GError  *error;

        error = NULL;
        ret = gsm_client_stop (client, &error);
        if (! ret) {
                g_warning ("Unable to stop client: %s", error->message);
                g_error_free (error);
                /* FIXME: what should we do if we can't communicate with client? */
        } else {
                g_debug ("GsmManager: stopped client: %s", gsm_client_peek_id (client));
        }

        return FALSE;
}

#ifdef HAVE_SYSTEMD
static void
maybe_restart_user_bus (GsmManager *manager)
{
        GsmSystemd *systemd;
        GsmManagerPrivate *priv;
        GDBusConnection *connection;

        g_autoptr(GVariant) reply = NULL;
        g_autoptr(GError) error = NULL;

        priv = gsm_manager_get_instance_private (manager);
        if (priv->dbus_disconnected)
                return;

        systemd = gsm_get_systemd ();

        if (!gsm_systemd_is_last_session_for_user (systemd))
                return;

        connection = g_bus_get_sync (G_BUS_TYPE_SESSION, NULL, &error);

        if (error != NULL) {
                g_debug ("GsmManager: failed to connect to session bus: %s", error->message);
                return;
        }

        reply = g_dbus_connection_call_sync (connection,
                                             "org.freedesktop.systemd1",
                                             "/org/freedesktop/systemd1",
                                             "org.freedesktop.systemd1.Manager",
                                             "TryRestartUnit",
                                             g_variant_new ("(ss)", "dbus.service", "replace"),
                                             NULL,
                                             G_DBUS_CALL_FLAGS_NONE,
                                             -1,
                                             NULL,
                                             &error);

        if (error != NULL) {
                g_debug ("GsmManager: reloading user bus failed: %s", error->message);
        }
}
#endif

static void
do_phase_exit (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        if (gsm_store_size (priv->clients) > 0) {
                gsm_store_foreach (priv->clients,
                                   (GsmStoreFunc)_client_stop,
                                   NULL);
        }

#ifdef HAVE_SYSTEMD
        maybe_restart_user_bus (manager);
#endif

        end_phase (manager);
}

static gboolean
_client_query_end_session (const char           *id,
                           GsmClient            *client,
                           ClientEndSessionData *data)
{
        gboolean ret;
        GError  *error;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (data->manager);

        error = NULL;
        ret = gsm_client_query_end_session (client, data->flags, &error);
        if (! ret) {
                g_warning ("Unable to query client: %s", error->message);
                g_error_free (error);
                /* FIXME: what should we do if we can't communicate with client? */
        } else {
                g_debug ("GsmManager: adding client to query clients: %s", gsm_client_peek_id (client));
                priv->query_clients = g_slist_prepend (priv->query_clients, client);
        }

        return FALSE;
}

static gboolean
inhibitor_has_flag (gpointer      key,
                    GsmInhibitor *inhibitor,
                    gpointer      data)
{
        guint flag;
        guint flags;

        flag = GPOINTER_TO_UINT (data);

        flags = gsm_inhibitor_peek_flags (inhibitor);

        return (flags & flag);
}

static gboolean
gsm_manager_is_logout_inhibited (GsmManager *manager)
{
        GsmInhibitor *inhibitor;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        if (priv->inhibitors == NULL) {
                return FALSE;
        }

        inhibitor = (GsmInhibitor *)gsm_store_find (priv->inhibitors,
                                                    (GsmStoreFunc)inhibitor_has_flag,
                                                    GUINT_TO_POINTER (GSM_INHIBITOR_FLAG_LOGOUT));
        if (inhibitor == NULL) {
                return FALSE;
        }
        return TRUE;
}

static gboolean
gsm_manager_is_idle_inhibited (GsmManager *manager)
{
        GsmInhibitor *inhibitor;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        if (priv->inhibitors == NULL) {
                return FALSE;
        }

        inhibitor = (GsmInhibitor *)gsm_store_find (priv->inhibitors,
                                                    (GsmStoreFunc)inhibitor_has_flag,
                                                    GUINT_TO_POINTER (GSM_INHIBITOR_FLAG_IDLE));
        if (inhibitor == NULL) {
                return FALSE;
        }
        return TRUE;
}

static gboolean
_client_cancel_end_session (const char *id,
                            GsmClient  *client,
                            GsmManager *manager)
{
        gboolean res;
        GError  *error;

        error = NULL;
        res = gsm_client_cancel_end_session (client, &error);
        if (! res) {
                g_warning ("Unable to cancel end session: %s", error->message);
                g_error_free (error);
        }

        return FALSE;
}

static gboolean
inhibitor_is_jit (gpointer      key,
                  GsmInhibitor *inhibitor,
                  GsmManager   *manager)
{
        gboolean    matches;
        const char *id;

        id = gsm_inhibitor_peek_client_id (inhibitor);

        matches = (id != NULL && id[0] != '\0');

        return matches;
}

static void
cancel_end_session (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        /* just ignore if received outside of shutdown */
        if (priv->phase < GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                return;
        }

        /* switch back to running phase */
        g_debug ("GsmManager: Cancelling the end of session");

        /* remove the dialog before we remove the inhibitors, else the dialog
         * will activate itself automatically when the last inhibitor will be
         * removed */
        if (priv->inhibit_dialog)
                gtk_widget_destroy (GTK_WIDGET (priv->inhibit_dialog));
        priv->inhibit_dialog = NULL;

        /* clear all JIT inhibitors */
        gsm_store_foreach_remove (priv->inhibitors,
                                  (GsmStoreFunc)inhibitor_is_jit,
                                  (gpointer)manager);

        gsm_store_foreach (priv->clients,
                           (GsmStoreFunc)_client_cancel_end_session,
                           NULL);

        gsm_manager_set_phase (manager, GSM_MANAGER_PHASE_RUNNING);
        priv->logout_mode = GSM_MANAGER_LOGOUT_MODE_NORMAL;

        priv->logout_type = GSM_MANAGER_LOGOUT_NONE;
        mdm_set_logout_action (MDM_LOGOUT_ACTION_NONE);

        start_phase (manager);
}

static gboolean
process_is_running (const char * name)
{
       int num_processes;
       char * command = g_strdup_printf ("pidof %s | wc -l", name);
       FILE *fp = popen(command, "r");

       if (fscanf(fp, "%d", &num_processes) != 1)
           num_processes = 0;

       pclose(fp);
       g_free (command);

       if (num_processes > 0) {
           return TRUE;
       }
       else {
           return FALSE;
       }
}

static void
manager_switch_user (GsmManager *manager)
{
        GError  *error;
        gboolean res;
        char    *command;
        const gchar *xdg_seat_path = g_getenv ("XDG_SEAT_PATH");

        /* We have to do this here and in request_switch_user() because this
         * function can be called at a later time, not just directly after
         * request_switch_user(). */
        if (_switch_user_is_locked_down (manager)) {
                g_warning ("Unable to switch user: User switching has been locked down");
                return;
        }

        if (process_is_running("mdm")) {
                /* MDM */
                command = g_strdup_printf ("%s %s",
                                           MDM_FLEXISERVER_COMMAND,
                                           MDM_FLEXISERVER_ARGS);

                error = NULL;
                res = g_spawn_command_line_sync (command, NULL, NULL, NULL, &error);

                g_free (command);

                if (! res) {
                        g_debug ("GsmManager: Unable to start MDM greeter: %s", error->message);
                        g_error_free (error);
                }
        }
        else if (process_is_running("gdm") || process_is_running("gdm3") || process_is_running("gdm-binary")) {
                /* GDM */
                command = g_strdup_printf ("%s %s",
                                           GDM_FLEXISERVER_COMMAND,
                                           GDM_FLEXISERVER_ARGS);

                error = NULL;
                res = g_spawn_command_line_sync (command, NULL, NULL, NULL, &error);

                g_free (command);

                if (! res) {
                        g_debug ("GsmManager: Unable to start GDM greeter: %s", error->message);
                        g_error_free (error);
                }
        }
        else if (xdg_seat_path != NULL) {
                /* LightDM */
                GDBusProxyFlags flags = G_DBUS_PROXY_FLAGS_DO_NOT_AUTO_START;
                GDBusProxy *proxy = NULL;
                error = NULL;

                proxy = g_dbus_proxy_new_for_bus_sync(G_BUS_TYPE_SYSTEM,
                                                      flags,
                                                      NULL,
                                                      "org.freedesktop.DisplayManager",
                                                      xdg_seat_path,
                                                      "org.freedesktop.DisplayManager.Seat",
                                                      NULL,
                                                      &error);
                if (proxy != NULL) {
                        g_dbus_proxy_call_sync (proxy,
                                                "SwitchToGreeter",
                                                g_variant_new ("()"),
                                                G_DBUS_CALL_FLAGS_NONE,
                                                -1,
                                                NULL,
                                                NULL);
                        g_object_unref (proxy);
                }
                else {
                        g_debug ("GsmManager: Unable to start LightDM greeter: %s", error->message);
                        g_error_free (error);
                }
         }
}

static gboolean
sleep_lock_is_enabled (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        if (priv->settings_screensaver != NULL)
                return g_settings_get_boolean (priv->settings_screensaver,
                                               KEY_SLEEP_LOCK);
        else
                return FALSE;
}

static void
manager_perhaps_lock (GsmManager *manager)
{
        gchar **screen_locker_command;

        if ((screen_locker_command = gsm_get_screen_locker_command ()) != NULL) {
                GError *error = NULL;

                /* only lock if mate-screensaver is set to lock */
                if (!g_strcmp0 (screen_locker_command[0], "mate-screensaver-command") &&
                    !sleep_lock_is_enabled (manager)) {
                        goto clear_screen_locker_command;
                }

                /* do this sync to ensure it's on the screen when we start suspending */
                g_spawn_sync (NULL, screen_locker_command, NULL,
                              G_SPAWN_DEFAULT | G_SPAWN_SEARCH_PATH,
                              NULL, NULL, NULL, NULL, NULL, &error);

                if (error) {
                        g_warning ("Couldn't lock screen: %s", error->message);
                        g_error_free (error);
                }

        } else {
                g_warning ("Couldn't find any screen locker");
        }

clear_screen_locker_command:

        g_strfreev (screen_locker_command);
}

static void
manager_attempt_hibernate (GsmManager *manager)
{
#ifdef HAVE_SYSTEMD
        if (LOGIND_RUNNING()) {

                GsmSystemd *systemd;

                systemd = gsm_get_systemd ();

                /* lock the screen before we suspend */
                manager_perhaps_lock (manager);

                gsm_systemd_attempt_hibernate (systemd);
        }
        else {
#endif
        GsmConsolekit *consolekit;
        consolekit = gsm_get_consolekit ();

        gboolean can_hibernate = gsm_consolekit_can_hibernate (consolekit);
        if (can_hibernate) {
                /* lock the screen before we suspend */
                manager_perhaps_lock (manager);

                gsm_consolekit_attempt_hibernate (consolekit);
        }
#ifdef HAVE_SYSTEMD
        }
#endif
}

static void
manager_attempt_suspend (GsmManager *manager)
{
#ifdef HAVE_SYSTEMD
        if (LOGIND_RUNNING()) {

                GsmSystemd *systemd;

                systemd = gsm_get_systemd ();

                /* lock the screen before we suspend */
                manager_perhaps_lock (manager);

                gsm_systemd_attempt_suspend (systemd);
        }
        else {
#endif
        GsmConsolekit *consolekit;
        consolekit = gsm_get_consolekit ();

        gboolean can_suspend = gsm_consolekit_can_suspend (consolekit);
        if (can_suspend) {
                /* lock the screen before we suspend */
                manager_perhaps_lock (manager);

                gsm_consolekit_attempt_suspend (consolekit);
        }
#ifdef HAVE_SYSTEMD
        }
#endif
}

static void
do_inhibit_dialog_action (GsmManager *manager,
                          int         action)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        switch (action) {
        case GSM_LOGOUT_ACTION_SWITCH_USER:
                manager_switch_user (manager);
                break;
        case GSM_LOGOUT_ACTION_HIBERNATE:
                manager_attempt_hibernate (manager);
                break;
        case GSM_LOGOUT_ACTION_SLEEP:
                manager_attempt_suspend (manager);
                break;
        case GSM_LOGOUT_ACTION_SHUTDOWN:
        case GSM_LOGOUT_ACTION_REBOOT:
        case GSM_LOGOUT_ACTION_LOGOUT:
                priv->logout_mode = GSM_MANAGER_LOGOUT_MODE_FORCE;
                end_phase (manager);
                break;
        default:
                g_assert_not_reached ();
                break;
        }
}

static void
inhibit_dialog_response (GsmInhibitDialog *dialog,
                         guint             response_id,
                         GsmManager       *manager)
{
        int action;
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: Inhibit dialog response: %d", response_id);

        priv = gsm_manager_get_instance_private (manager);
        /* must destroy dialog before cancelling since we'll
           remove JIT inhibitors and we don't want to trigger
           action. */
        g_object_get (dialog, "action", &action, NULL);
        gtk_widget_destroy (GTK_WIDGET (dialog));
        priv->inhibit_dialog = NULL;

        /* In case of dialog cancel, switch user, hibernate and
         * suspend, we just perform the respective action and return,
         * without shutting down the session. */
        switch (response_id) {
        case GTK_RESPONSE_CANCEL:
        case GTK_RESPONSE_NONE:
        case GTK_RESPONSE_DELETE_EVENT:
                if (action == GSM_LOGOUT_ACTION_LOGOUT
                    || action == GSM_LOGOUT_ACTION_SHUTDOWN
                    || action == GSM_LOGOUT_ACTION_REBOOT) {
                        cancel_end_session (manager);
                }
                break;
        case GTK_RESPONSE_ACCEPT:
                g_debug ("GsmManager: doing action %d", action);
                do_inhibit_dialog_action (manager, action);
                break;
        default:
                g_assert_not_reached ();
                break;
        }
}

static void
query_end_session_complete (GsmManager *manager)
{
        GsmLogoutAction action;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        g_debug ("GsmManager: query end session complete");

        /* Remove the timeout since this can be called from outside the timer
         * and we don't want to have it called twice */
        if (priv->query_timeout_id > 0) {
                g_source_remove (priv->query_timeout_id);
                priv->query_timeout_id = 0;
        }

        if (! gsm_manager_is_logout_inhibited (manager)) {
                end_phase (manager);
                return;
        }

        if (priv->inhibit_dialog != NULL) {
                g_debug ("GsmManager: inhibit dialog already up");
                gtk_window_present (GTK_WINDOW (priv->inhibit_dialog));
                return;
        }

        switch (priv->logout_type) {
        case GSM_MANAGER_LOGOUT_LOGOUT:
                action = GSM_LOGOUT_ACTION_LOGOUT;
                break;
        case GSM_MANAGER_LOGOUT_REBOOT:
        case GSM_MANAGER_LOGOUT_REBOOT_INTERACT:
        case GSM_MANAGER_LOGOUT_REBOOT_MDM:
                action = GSM_LOGOUT_ACTION_REBOOT;
                break;
        case GSM_MANAGER_LOGOUT_SHUTDOWN:
        case GSM_MANAGER_LOGOUT_SHUTDOWN_INTERACT:
        case GSM_MANAGER_LOGOUT_SHUTDOWN_MDM:
                action = GSM_LOGOUT_ACTION_SHUTDOWN;
                break;
        default:
                g_warning ("Unexpected logout type %d when creating inhibit dialog",
                           priv->logout_type);
                action = GSM_LOGOUT_ACTION_LOGOUT;
                break;
        }

        /* Note: GSM_LOGOUT_ACTION_SHUTDOWN and GSM_LOGOUT_ACTION_REBOOT are
         * actually handled the same way as GSM_LOGOUT_ACTION_LOGOUT in the
         * inhibit dialog; the action, if the button is clicked, will be to
         * simply go to the next phase. */
        priv->inhibit_dialog = gsm_inhibit_dialog_new (priv->inhibitors,
                                                       priv->clients,
                                                       action);

        g_signal_connect (priv->inhibit_dialog,
                          "response",
                          G_CALLBACK (inhibit_dialog_response),
                          manager);
        gtk_widget_show (priv->inhibit_dialog);

}

static guint32
generate_cookie (void)
{
        guint32 cookie;

        cookie = (guint32)g_random_int_range (1, G_MAXINT32);

        return cookie;
}

static guint32
_generate_unique_cookie (GsmManager *manager)
{
        guint32 cookie;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        do {
                cookie = generate_cookie ();
        } while (gsm_store_find (priv->inhibitors, (GsmStoreFunc)_find_by_cookie, &cookie) != NULL);

        return cookie;
}

static gboolean
_on_query_end_session_timeout (GsmManager *manager)
{
        GSList *l;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        priv->query_timeout_id = 0;

        g_debug ("GsmManager: query end session timed out");

        for (l = priv->query_clients; l != NULL; l = l->next) {
                guint         cookie;
                GsmInhibitor *inhibitor;
                const char   *bus_name;
                char         *app_id;

                g_warning ("Client '%s' failed to reply before timeout",
                           gsm_client_peek_id (l->data));

                /* Don't add "not responding" inhibitors if logout is forced
                 */
                if (priv->logout_mode == GSM_MANAGER_LOGOUT_MODE_FORCE) {
                        continue;
                }

                /* Add JIT inhibit for unresponsive client */
                if (GSM_IS_DBUS_CLIENT (l->data)) {
                        bus_name = gsm_dbus_client_get_bus_name (l->data);
                } else {
                        bus_name = NULL;
                }

                app_id = g_strdup (gsm_client_peek_app_id (l->data));
                if (IS_STRING_EMPTY (app_id)) {
                        /* XSMP clients don't give us an app id unless we start them */
                        g_free (app_id);
                        app_id = gsm_client_get_app_name (l->data);
                }

                cookie = _generate_unique_cookie (manager);
                inhibitor = gsm_inhibitor_new_for_client (gsm_client_peek_id (l->data),
                                                          app_id,
                                                          GSM_INHIBITOR_FLAG_LOGOUT,
                                                          _("Not responding"),
                                                          bus_name,
                                                          cookie);
                g_free (app_id);
                gsm_store_add (priv->inhibitors, gsm_inhibitor_peek_id (inhibitor), G_OBJECT (inhibitor));
                g_object_unref (inhibitor);
        }

        g_slist_free (priv->query_clients);
        priv->query_clients = NULL;

        query_end_session_complete (manager);

        return FALSE;
}

static void
do_phase_query_end_session (GsmManager *manager)
{
        ClientEndSessionData data;
        GsmManagerPrivate *priv;

        data.manager = manager;
        data.flags = 0;
        priv = gsm_manager_get_instance_private (manager);

        if (priv->logout_mode == GSM_MANAGER_LOGOUT_MODE_FORCE) {
                data.flags |= GSM_CLIENT_END_SESSION_FLAG_FORCEFUL;
        }
        /* We only query if an app is ready to log out, so we don't use
         * GSM_CLIENT_END_SESSION_FLAG_SAVE here.
         */

        debug_clients (manager);
        g_debug ("GsmManager: sending query-end-session to clients (logout mode: %s)",
                 priv->logout_mode == GSM_MANAGER_LOGOUT_MODE_NORMAL? "normal" :
                 priv->logout_mode == GSM_MANAGER_LOGOUT_MODE_FORCE? "forceful":
                 "no confirmation");
        gsm_store_foreach (priv->clients,
                           (GsmStoreFunc)_client_query_end_session,
                           &data);

        /* This phase doesn't time out unless logout is forced. Typically, this
         * separate timer is only used to show UI. */
        priv->query_timeout_id = g_timeout_add_seconds (1, (GSourceFunc)_on_query_end_session_timeout, manager);
}

static void
update_idle (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        if (gsm_manager_is_idle_inhibited (manager)) {
                gsm_presence_set_idle_enabled (priv->presence, FALSE);
        } else {
                gsm_presence_set_idle_enabled (priv->presence, TRUE);
        }
}

static void
start_phase (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        g_debug ("GsmManager: starting phase %s\n",
                 phase_num_to_name (priv->phase));

        /* reset state */
        g_slist_free (priv->pending_apps);
        priv->pending_apps = NULL;
        g_slist_free (priv->query_clients);
        priv->query_clients = NULL;
        g_slist_free (priv->next_query_clients);
        priv->next_query_clients = NULL;

        if (priv->query_timeout_id > 0) {
                g_source_remove (priv->query_timeout_id);
                priv->query_timeout_id = 0;
        }
        if (priv->phase_timeout_id > 0) {
                g_source_remove (priv->phase_timeout_id);
                priv->phase_timeout_id = 0;
        }

        switch (priv->phase) {
        case GSM_MANAGER_PHASE_STARTUP:
        case GSM_MANAGER_PHASE_INITIALIZATION:
        case GSM_MANAGER_PHASE_WINDOW_MANAGER:
        case GSM_MANAGER_PHASE_PANEL:
        case GSM_MANAGER_PHASE_DESKTOP:
        case GSM_MANAGER_PHASE_APPLICATION:
                do_phase_startup (manager);
                break;
        case GSM_MANAGER_PHASE_RUNNING:
                g_signal_emit (manager, signals[SESSION_RUNNING], 0);
                update_idle (manager);
                break;
        case GSM_MANAGER_PHASE_QUERY_END_SESSION:
                do_phase_query_end_session (manager);
                break;
        case GSM_MANAGER_PHASE_END_SESSION:
                do_phase_end_session (manager);
                break;
        case GSM_MANAGER_PHASE_EXIT:
                do_phase_exit (manager);
                break;
        default:
                g_assert_not_reached ();
                break;
        }
}

static gboolean
_debug_app_for_phase (const char *id,
                      GsmApp     *app,
                      gpointer    data)
{
        guint phase;

        phase = GPOINTER_TO_UINT (data);

        if (gsm_app_peek_phase (app) != phase) {
                return FALSE;
        }

        g_debug ("GsmManager:\tID: %s\tapp-id:%s\tis-disabled:%d\tis-conditionally-disabled:%d\tis-delayed:%d",
                 gsm_app_peek_id (app),
                 gsm_app_peek_app_id (app),
                 gsm_app_peek_is_disabled (app),
                 gsm_app_peek_is_conditionally_disabled (app),
                 (gsm_app_peek_autostart_delay (app) > 0));

        return FALSE;
}

static void
debug_app_summary (GsmManager *manager)
{
        guint phase;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        g_debug ("GsmManager: App startup summary");
        for (phase = GSM_MANAGER_PHASE_INITIALIZATION; phase < GSM_MANAGER_PHASE_RUNNING; phase++) {
                g_debug ("GsmManager: Phase %s", phase_num_to_name (phase));
                gsm_store_foreach (priv->apps,
                                   (GsmStoreFunc)_debug_app_for_phase,
                                   GUINT_TO_POINTER (phase));
        }
}

void
gsm_manager_start (GsmManager *manager)
{
        g_debug ("GsmManager: GSM starting to manage");

        g_return_if_fail (GSM_IS_MANAGER (manager));

        gsm_manager_set_phase (manager, GSM_MANAGER_PHASE_INITIALIZATION);
        debug_app_summary (manager);
        start_phase (manager);
}

void
_gsm_manager_set_renderer (GsmManager *manager,
                           const char *renderer)
{
        GsmManagerPrivate *priv;
        priv = gsm_manager_get_instance_private (manager);
        priv->renderer = renderer;
}

static gboolean
_app_has_app_id (const char   *id,
                 GsmApp       *app,
                 const char   *app_id_a)
{
        const char *app_id_b;

        app_id_b = gsm_app_peek_app_id (app);
        return (app_id_b != NULL && strcmp (app_id_a, app_id_b) == 0);
}

static GsmApp *
find_app_for_app_id (GsmManager *manager,
                     const char *app_id)
{
        GsmApp *app;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        app = (GsmApp *)gsm_store_find (priv->apps,
                                        (GsmStoreFunc)_app_has_app_id,
                                        (char *)app_id);
        return app;
}

static gboolean
inhibitor_has_client_id (gpointer      key,
                         GsmInhibitor *inhibitor,
                         const char   *client_id_a)
{
        gboolean    matches;
        const char *client_id_b;

        client_id_b = gsm_inhibitor_peek_client_id (inhibitor);

        matches = FALSE;
        if (! IS_STRING_EMPTY (client_id_a) && ! IS_STRING_EMPTY (client_id_b)) {
                matches = (strcmp (client_id_a, client_id_b) == 0);
                if (matches) {
                        g_debug ("GsmManager: removing JIT inhibitor for %s for reason '%s'",
                                 gsm_inhibitor_peek_client_id (inhibitor),
                                 gsm_inhibitor_peek_reason (inhibitor));
                }
        }

        return matches;
}

static gboolean
_app_has_startup_id (const char *id,
                     GsmApp     *app,
                     const char *startup_id_a)
{
        const char *startup_id_b;

        startup_id_b = gsm_app_peek_startup_id (app);

        if (IS_STRING_EMPTY (startup_id_b)) {
                return FALSE;
        }

        return (strcmp (startup_id_a, startup_id_b) == 0);
}

static GsmApp *
find_app_for_startup_id (GsmManager *manager,
                        const char *startup_id)
{
        GsmApp *found_app;
        GSList *a;
        GsmManagerPrivate *priv;

        found_app = NULL;
        priv = gsm_manager_get_instance_private (manager);

        /* If we're starting up the session, try to match the new client
         * with one pending apps for the current phase. If not, try to match
         * with any of the autostarted apps. */
        if (priv->phase < GSM_MANAGER_PHASE_APPLICATION) {
                for (a = priv->pending_apps; a != NULL; a = a->next) {
                        GsmApp *app = GSM_APP (a->data);

                        if (strcmp (startup_id, gsm_app_peek_startup_id (app)) == 0) {
                                found_app = app;
                                goto out;
                        }
                }
        } else {
                GsmApp *app;

                app = (GsmApp *)gsm_store_find (priv->apps,
                                                (GsmStoreFunc)_app_has_startup_id,
                                                (char *)startup_id);
                if (app != NULL) {
                        found_app = app;
                        goto out;
                }
        }
 out:
        return found_app;
}

static void
_disconnect_client (GsmManager *manager,
                    GsmClient  *client)
{
        gboolean              is_condition_client;
        GsmApp               *app;
        GError               *error;
        gboolean UNUSED_VARIABLE res;
        const char           *app_id;
        const char           *startup_id;
        gboolean              app_restart;
        GsmClientRestartStyle client_restart_hint;
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: disconnect client: %s", gsm_client_peek_id (client));

        /* take a ref so it doesn't get finalized */
        g_object_ref (client);

        gsm_client_set_status (client, GSM_CLIENT_FINISHED);

        is_condition_client = FALSE;
        priv = gsm_manager_get_instance_private (manager);
        if (g_slist_find (priv->condition_clients, client)) {
                priv->condition_clients = g_slist_remove (priv->condition_clients, client);

                is_condition_client = TRUE;
        }

        /* remove any inhibitors for this client */
        gsm_store_foreach_remove (priv->inhibitors,
                                  (GsmStoreFunc)inhibitor_has_client_id,
                                  (gpointer)gsm_client_peek_id (client));

        app = NULL;

        /* first try to match on startup ID */
        startup_id = gsm_client_peek_startup_id (client);
        if (! IS_STRING_EMPTY (startup_id)) {
                app = find_app_for_startup_id (manager, startup_id);

        }

        /* then try to find matching app-id */
        if (app == NULL) {
                app_id = gsm_client_peek_app_id (client);
                if (! IS_STRING_EMPTY (app_id)) {
                        g_debug ("GsmManager: disconnect for app '%s'", app_id);
                        app = find_app_for_app_id (manager, app_id);
                }
        }

        if (priv->phase == GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                /* Instead of answering our end session query, the client just exited.
                 * Treat that as an "okay, end the session" answer.
                 *
                 * This call implicitly removes any inhibitors for the client, along
                 * with removing the client from the pending query list.
                 */
                _handle_client_end_session_response (manager,
                                                     client,
                                                     TRUE,
                                                     FALSE,
                                                     FALSE,
                                                     "Client exited in "
                                                     "query end session phase "
                                                     "instead of end session "
                                                     "phase");
        }

        if (priv->dbus_disconnected && GSM_IS_DBUS_CLIENT (client)) {
                g_debug ("GsmManager: dbus disconnected, not restarting application");
                goto out;
        }


        if (app == NULL) {
                g_debug ("GsmManager: unable to find application for client - not restarting");
                goto out;
        }

        if (priv->phase >= GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                g_debug ("GsmManager: in shutdown, not restarting application");
                goto out;
        }

        app_restart = gsm_app_peek_autorestart (app);
        client_restart_hint = gsm_client_peek_restart_style_hint (client);

        /* allow legacy clients to override the app info */
        if (! app_restart
            && client_restart_hint != GSM_CLIENT_RESTART_IMMEDIATELY) {
                g_debug ("GsmManager: autorestart not set, not restarting application");
                goto out;
        }

        if (is_condition_client) {
                g_debug ("GsmManager: app conditionally disabled, not restarting application");
                goto out;
        }

        g_debug ("GsmManager: restarting app");

        error = NULL;
        res = gsm_app_restart (app, &error);
        if (error != NULL) {
                g_warning ("Error on restarting session managed app: %s", error->message);
                g_error_free (error);
        }

 out:
        g_object_unref (client);
}

typedef struct {
        const char *service_name;
        GsmManager *manager;
} RemoveClientData;

static gboolean
_disconnect_dbus_client (const char       *id,
                         GsmClient        *client,
                         RemoveClientData *data)
{
        const char *name;

        if (! GSM_IS_DBUS_CLIENT (client)) {
                return FALSE;
        }

        /* If no service name, then we simply disconnect all clients */
        if (!data->service_name) {
                _disconnect_client (data->manager, client);
                return TRUE;
        }

        name = gsm_dbus_client_get_bus_name (GSM_DBUS_CLIENT (client));
        if (IS_STRING_EMPTY (name)) {
                return FALSE;
        }

        if (strcmp (data->service_name, name) == 0) {
                _disconnect_client (data->manager, client);
                return TRUE;
        }

        return FALSE;
}

/**
 * remove_clients_for_connection:
 * @manager: a #GsmManager
 * @service_name: a service name
 *
 * Disconnects clients that own @service_name.
 *
 * If @service_name is NULL, then disconnects all clients for the connection.
 */
static void
remove_clients_for_connection (GsmManager *manager,
                               const char *service_name)
{
        RemoveClientData data;
        GsmManagerPrivate *priv;

        data.service_name = service_name;
        data.manager = manager;
        priv = gsm_manager_get_instance_private (manager);

        /* disconnect dbus clients for name */
        gsm_store_foreach_remove (priv->clients,
                                  (GsmStoreFunc)_disconnect_dbus_client,
                                  &data);

        if (priv->phase >= GSM_MANAGER_PHASE_QUERY_END_SESSION
            && gsm_store_size (priv->clients) == 0) {
                g_debug ("GsmManager: last client disconnected - exiting");
                end_phase (manager);
        }
}

static gboolean
inhibitor_has_bus_name (gpointer          key,
                        GsmInhibitor     *inhibitor,
                        RemoveClientData *data)
{
        gboolean    matches;
        const char *bus_name_b;

        bus_name_b = gsm_inhibitor_peek_bus_name (inhibitor);

        matches = FALSE;
        if (! IS_STRING_EMPTY (data->service_name) && ! IS_STRING_EMPTY (bus_name_b)) {
                matches = (strcmp (data->service_name, bus_name_b) == 0);
                if (matches) {
                        g_debug ("GsmManager: removing inhibitor from %s for reason '%s' on connection %s",
                                 gsm_inhibitor_peek_app_id (inhibitor),
                                 gsm_inhibitor_peek_reason (inhibitor),
                                 gsm_inhibitor_peek_bus_name (inhibitor));
                }
        }

        return matches;
}

static void
remove_inhibitors_for_connection (GsmManager *manager,
                                  const char *service_name)
{
        guint UNUSED_VARIABLE n_removed;
        RemoveClientData data;
        GsmManagerPrivate *priv;

        data.service_name = service_name;
        data.manager = manager;
        priv = gsm_manager_get_instance_private (manager);

        debug_inhibitors (manager);

        n_removed = gsm_store_foreach_remove (priv->inhibitors,
                                              (GsmStoreFunc)inhibitor_has_bus_name,
                                              &data);
}

static void
bus_name_owner_changed (DBusGProxy  *bus_proxy,
                        const char  *service_name,
                        const char  *old_service_name,
                        const char  *new_service_name,
                        GsmManager  *manager)
{
        if (strlen (new_service_name) == 0
            && strlen (old_service_name) > 0) {
                /* service removed */
                remove_inhibitors_for_connection (manager, old_service_name);
                remove_clients_for_connection (manager, old_service_name);
        } else if (strlen (old_service_name) == 0
                   && strlen (new_service_name) > 0) {
                /* service added */

                /* use this if we support automatically registering
                 * well known bus names */
        }
}

static DBusHandlerResult
gsm_manager_bus_filter (DBusConnection *connection,
                        DBusMessage    *message,
                        void           *user_data)
{
        GsmManager *manager;
        GsmManagerPrivate *priv;

        manager = GSM_MANAGER (user_data);
        priv = gsm_manager_get_instance_private (manager);

        if (dbus_message_is_signal (message,
                                    DBUS_INTERFACE_LOCAL, "Disconnected") &&
            strcmp (dbus_message_get_path (message), DBUS_PATH_LOCAL) == 0) {
                g_debug ("GsmManager: dbus disconnected; disconnecting dbus clients...");
                priv->dbus_disconnected = TRUE;
                remove_clients_for_connection (manager, NULL);
                /* let other filters get this disconnected signal, so that they
                 * can handle it too */
        }

        return DBUS_HANDLER_RESULT_NOT_YET_HANDLED;
}

static gboolean
register_manager (GsmManager *manager)
{
        GError *error = NULL;
        GsmManagerPrivate *priv;
        DBusConnection *connection;

        error = NULL;
        priv = gsm_manager_get_instance_private (manager);

        priv->connection = dbus_g_bus_get (DBUS_BUS_SESSION, &error);
        if (priv->connection == NULL) {
                if (error != NULL) {
                        g_critical ("error getting session bus: %s", error->message);
                        g_error_free (error);
                }
                exit (1);
        }

        connection = dbus_g_connection_get_connection (priv->connection);
        dbus_connection_add_filter (connection,
                                    gsm_manager_bus_filter,
                                    manager, NULL);
        priv->dbus_disconnected = FALSE;

        priv->bus_proxy = dbus_g_proxy_new_for_name (priv->connection,
                                                     DBUS_SERVICE_DBUS,
                                                     DBUS_PATH_DBUS,
                                                     DBUS_INTERFACE_DBUS);
        dbus_g_proxy_add_signal (priv->bus_proxy,
                                 "NameOwnerChanged",
                                 G_TYPE_STRING,
                                 G_TYPE_STRING,
                                 G_TYPE_STRING,
                                 G_TYPE_INVALID);
        dbus_g_proxy_connect_signal (priv->bus_proxy,
                                     "NameOwnerChanged",
                                     G_CALLBACK (bus_name_owner_changed),
                                     manager,
                                     NULL);

        dbus_g_connection_register_g_object (priv->connection, GSM_MANAGER_DBUS_PATH, G_OBJECT (manager));

        return TRUE;
}

static void
gsm_manager_set_failsafe (GsmManager *manager,
                          gboolean    enabled)
{
        GsmManagerPrivate *priv;

        g_return_if_fail (GSM_IS_MANAGER (manager));

        priv = gsm_manager_get_instance_private (manager);

        priv->failsafe = enabled;
}

static gboolean
_client_has_startup_id (const char *id,
                        GsmClient  *client,
                        const char *startup_id_a)
{
        const char *startup_id_b;

        startup_id_b = gsm_client_peek_startup_id (client);

        if (IS_STRING_EMPTY (startup_id_b)) {
                return FALSE;
        }

        return (strcmp (startup_id_a, startup_id_b) == 0);
}

static void
on_client_disconnected (GsmClient  *client,
                        GsmManager *manager)
{
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: disconnect client");

        priv = gsm_manager_get_instance_private (manager);

        _disconnect_client (manager, client);
        gsm_store_remove (priv->clients, gsm_client_peek_id (client));
        if (priv->phase >= GSM_MANAGER_PHASE_QUERY_END_SESSION
            && gsm_store_size (priv->clients) == 0) {
                g_debug ("GsmManager: last client disconnected - exiting");
                end_phase (manager);
        }
}

static gboolean
on_xsmp_client_register_request (GsmXSMPClient *client,
                                 char         **id,
                                 GsmManager    *manager)
{
        gboolean handled;
        char    *new_id;
        GsmApp  *app;
        GsmManagerPrivate *priv;

        handled = TRUE;
        new_id = NULL;
        priv = gsm_manager_get_instance_private (manager);

        if (priv->phase >= GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                goto out;
        }

        if (IS_STRING_EMPTY (*id)) {
                new_id = gsm_util_generate_startup_id ();
        } else {
                GsmClient *client;

                client = (GsmClient *)gsm_store_find (priv->clients,
                                                      (GsmStoreFunc)_client_has_startup_id,
                                                      *id);
                /* We can't have two clients with the same id. */
                if (client != NULL) {
                        goto out;
                }

                new_id = g_strdup (*id);
        }

        g_debug ("GsmManager: Adding new client %s to session", new_id);

        g_signal_connect (client,
                          "disconnected",
                          G_CALLBACK (on_client_disconnected),
                          manager);

        /* If it's a brand new client id, we just accept the client*/
        if (IS_STRING_EMPTY (*id)) {
                goto out;
        }

        app = find_app_for_startup_id (manager, new_id);
        if (app != NULL) {
                gsm_client_set_app_id (GSM_CLIENT (client), gsm_app_peek_app_id (app));
                gsm_app_registered (app);
                goto out;
        }

        /* app not found */
        g_free (new_id);
        new_id = NULL;

 out:
        g_free (*id);
        *id = new_id;

        return handled;
}

static gboolean
auto_save_is_enabled (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        return g_settings_get_boolean (priv->settings_session,
                                       KEY_AUTOSAVE);
}

static void
maybe_save_session (GsmManager *manager)
{
        GsmConsolekit *consolekit = NULL;
#ifdef HAVE_SYSTEMD
        GsmSystemd *systemd = NULL;
#endif
        char *session_type;
        GError *error;
        GsmManagerPrivate *priv;

#ifdef HAVE_SYSTEMD
        if (LOGIND_RUNNING()) {
                systemd = gsm_get_systemd ();
                session_type = gsm_systemd_get_current_session_type (systemd);

                if (g_strcmp0 (session_type, GSM_SYSTEMD_SESSION_TYPE_LOGIN_WINDOW) == 0) {
                        goto out;
                }
        }
        else {
#endif
        consolekit = gsm_get_consolekit ();
        session_type = gsm_consolekit_get_current_session_type (consolekit);

        if (g_strcmp0 (session_type, GSM_CONSOLEKIT_SESSION_TYPE_LOGIN_WINDOW) == 0) {
                goto out;
        }
#ifdef HAVE_SYSTEMD
        }
#endif

        priv = gsm_manager_get_instance_private (manager);
        /* We only allow session saving when session is running or when
         * logging out */
        if (priv->phase != GSM_MANAGER_PHASE_RUNNING &&
            priv->phase != GSM_MANAGER_PHASE_END_SESSION) {
                goto out;
        }

        error = NULL;
        gsm_session_save (priv->clients, &error);

        if (error) {
                g_warning ("Error saving session: %s", error->message);
                g_error_free (error);
        }

out:
        if (consolekit != NULL)
                g_object_unref (consolekit);
#ifdef HAVE_SYSTEMD
        if (systemd != NULL)
                g_object_unref (systemd);
#endif
        g_free (session_type);
}

static void
_handle_client_end_session_response (GsmManager *manager,
                                     GsmClient  *client,
                                     gboolean    is_ok,
                                     gboolean    do_last,
                                     gboolean    cancel,
                                     const char *reason)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        /* just ignore if received outside of shutdown */
        if (priv->phase < GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                return;
        }

        g_debug ("GsmManager: Response from end session request: is-ok=%d do-last=%d cancel=%d reason=%s", is_ok, do_last, cancel, reason ? reason :"");

        if (cancel) {
                cancel_end_session (manager);
                return;
        }

        priv->query_clients = g_slist_remove (priv->query_clients, client);

        if (! is_ok && priv->logout_mode != GSM_MANAGER_LOGOUT_MODE_FORCE) {
                guint         cookie;
                GsmInhibitor *inhibitor;
                char         *app_id;
                const char   *bus_name;

                /* FIXME: do we support updating the reason? */

                /* Create JIT inhibit */
                if (GSM_IS_DBUS_CLIENT (client)) {
                        bus_name = gsm_dbus_client_get_bus_name (GSM_DBUS_CLIENT (client));
                } else {
                        bus_name = NULL;
                }

                app_id = g_strdup (gsm_client_peek_app_id (client));
                if (IS_STRING_EMPTY (app_id)) {
                        /* XSMP clients don't give us an app id unless we start them */
                        g_free (app_id);
                        app_id = gsm_client_get_app_name (client);
                }

                cookie = _generate_unique_cookie (manager);
                inhibitor = gsm_inhibitor_new_for_client (gsm_client_peek_id (client),
                                                          app_id,
                                                          GSM_INHIBITOR_FLAG_LOGOUT,
                                                          reason != NULL ? reason : _("Not responding"),
                                                          bus_name,
                                                          cookie);
                g_free (app_id);
                gsm_store_add (priv->inhibitors, gsm_inhibitor_peek_id (inhibitor), G_OBJECT (inhibitor));
                g_object_unref (inhibitor);
        } else {
                gsm_store_foreach_remove (priv->inhibitors,
                                          (GsmStoreFunc)inhibitor_has_client_id,
                                          (gpointer)gsm_client_peek_id (client));
        }

        if (priv->phase == GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                if (priv->query_clients == NULL) {
                        query_end_session_complete (manager);
                }
        } else if (priv->phase == GSM_MANAGER_PHASE_END_SESSION) {
                if (do_last) {
                        /* This only makes sense if we're in part 1 of
                         * GSM_MANAGER_PHASE_END_SESSION. Doing this in part 2
                         * can only happen because of a buggy client that loops
                         * wanting to be last again and again. The phase
                         * timeout will take care of this issue. */
                        priv->next_query_clients = g_slist_prepend (priv->next_query_clients,
                                                                    client);
                }

                /* we can continue to the next step if all clients have replied
                 * and if there's no inhibitor */
                if (priv->query_clients != NULL
                    || gsm_manager_is_logout_inhibited (manager)) {
                        return;
                }

                if (priv->next_query_clients != NULL) {
                        do_phase_end_session_part_2 (manager);
                } else {
                        end_phase (manager);
                }
        }
}

static void
on_client_end_session_response (GsmClient  *client,
                                gboolean    is_ok,
                                gboolean    do_last,
                                gboolean    cancel,
                                const char *reason,
                                GsmManager *manager)
{
        _handle_client_end_session_response (manager,
                                             client,
                                             is_ok,
                                             do_last,
                                             cancel,
                                             reason);
}

static void
on_xsmp_client_logout_request (GsmXSMPClient *client,
                               gboolean       show_dialog,
                               GsmManager    *manager)
{
        GError *error;
        int     logout_mode;

        if (show_dialog) {
                logout_mode = GSM_MANAGER_LOGOUT_MODE_NORMAL;
        } else {
                logout_mode = GSM_MANAGER_LOGOUT_MODE_NO_CONFIRMATION;
        }

        error = NULL;
        gsm_manager_logout (manager, logout_mode, &error);
        if (error != NULL) {
                g_warning ("Unable to logout: %s", error->message);
                g_error_free (error);
        }
}

static void
on_store_client_added (GsmStore   *store,
                       const char *id,
                       GsmManager *manager)
{
        GsmClient *client;

        g_debug ("GsmManager: Client added: %s", id);

        client = (GsmClient *)gsm_store_lookup (store, id);

        /* a bit hacky */
        if (GSM_IS_XSMP_CLIENT (client)) {
                g_signal_connect (client,
                                  "register-request",
                                  G_CALLBACK (on_xsmp_client_register_request),
                                  manager);
                g_signal_connect (client,
                                  "logout-request",
                                  G_CALLBACK (on_xsmp_client_logout_request),
                                  manager);
        }

        g_signal_connect (client,
                          "end-session-response",
                          G_CALLBACK (on_client_end_session_response),
                          manager);

        g_signal_emit (manager, signals [CLIENT_ADDED], 0, id);
        /* FIXME: disconnect signal handler */
}

static void
on_store_client_removed (GsmStore   *store,
                         const char *id,
                         GsmManager *manager)
{
        g_debug ("GsmManager: Client removed: %s", id);

        g_signal_emit (manager, signals [CLIENT_REMOVED], 0, id);
}

static void
gsm_manager_set_client_store (GsmManager *manager,
                              GsmStore   *store)
{
        GsmManagerPrivate *priv;

        g_return_if_fail (GSM_IS_MANAGER (manager));
        priv = gsm_manager_get_instance_private (manager);

        if (store != NULL) {
                g_object_ref (store);
        }

        if (priv->clients != NULL) {
                g_signal_handlers_disconnect_by_func (priv->clients,
                                                      on_store_client_added,
                                                      manager);
                g_signal_handlers_disconnect_by_func (priv->clients,
                                                      on_store_client_removed,
                                                      manager);

                g_object_unref (priv->clients);
        }


        g_debug ("GsmManager: setting client store %p", store);

        priv->clients = store;

        if (priv->clients != NULL) {
                g_signal_connect (priv->clients,
                                  "added",
                                  G_CALLBACK (on_store_client_added),
                                  manager);
                g_signal_connect (priv->clients,
                                  "removed",
                                  G_CALLBACK (on_store_client_removed),
                                  manager);
        }
}

static void
gsm_manager_set_property (GObject       *object,
                          guint          prop_id,
                          const GValue  *value,
                          GParamSpec    *pspec)
{
        GsmManager *self;

        self = GSM_MANAGER (object);

        switch (prop_id) {
        case PROP_FAILSAFE:
                gsm_manager_set_failsafe (self, g_value_get_boolean (value));
                break;
         case PROP_CLIENT_STORE:
                gsm_manager_set_client_store (self, g_value_get_object (value));
                break;
        default:
                G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
                break;
        }
}

static void
gsm_manager_get_property (GObject    *object,
                          guint       prop_id,
                          GValue     *value,
                          GParamSpec *pspec)
{
        GsmManager *self;
        GsmManagerPrivate *priv;

        self = GSM_MANAGER (object);
        priv = gsm_manager_get_instance_private (self);

        switch (prop_id) {
        case PROP_FAILSAFE:
                g_value_set_boolean (value, priv->failsafe);
                break;
        case PROP_CLIENT_STORE:
                g_value_set_object (value, priv->clients);
                break;
        case PROP_RENDERER:
                g_value_set_string (value, priv->renderer);
                break;
        default:
                G_OBJECT_WARN_INVALID_PROPERTY_ID (object, prop_id, pspec);
                break;
        }
}

static gboolean
_find_app_provides (const char *id,
                    GsmApp     *app,
                    const char *service)
{
        return gsm_app_provides (app, service);
}

static GObject *
gsm_manager_constructor (GType                  type,
                         guint                  n_construct_properties,
                         GObjectConstructParam *construct_properties)
{
        GsmManager *manager;

        manager = GSM_MANAGER (G_OBJECT_CLASS (gsm_manager_parent_class)->constructor (type,
                                                                                       n_construct_properties,
                                                                                       construct_properties));
        return G_OBJECT (manager);
}

static void
on_store_inhibitor_added (GsmStore   *store,
                          const char *id,
                          GsmManager *manager)
{
        g_debug ("GsmManager: Inhibitor added: %s", id);
        g_signal_emit (manager, signals [INHIBITOR_ADDED], 0, id);
        update_idle (manager);
}

static void
on_store_inhibitor_removed (GsmStore   *store,
                            const char *id,
                            GsmManager *manager)
{
        g_debug ("GsmManager: Inhibitor removed: %s", id);
        g_signal_emit (manager, signals [INHIBITOR_REMOVED], 0, id);
        update_idle (manager);
}

static void
gsm_manager_dispose (GObject *object)
{
        GsmManagerPrivate *priv;
        GsmManager *manager = GSM_MANAGER (object);

        g_debug ("GsmManager: disposing manager");

        priv = gsm_manager_get_instance_private (manager);

        if (priv->clients != NULL) {
                g_signal_handlers_disconnect_by_func (priv->clients,
                                                      on_store_client_added,
                                                      manager);
                g_signal_handlers_disconnect_by_func (priv->clients,
                                                      on_store_client_removed,
                                                      manager);
                g_object_unref (priv->clients);
                priv->clients = NULL;
        }

        if (priv->apps != NULL) {
                g_object_unref (priv->apps);
                priv->apps = NULL;
        }

        if (priv->inhibitors != NULL) {
                g_signal_handlers_disconnect_by_func (priv->inhibitors,
                                                      on_store_inhibitor_added,
                                                      manager);
                g_signal_handlers_disconnect_by_func (priv->inhibitors,
                                                      on_store_inhibitor_removed,
                                                      manager);

                g_object_unref (priv->inhibitors);
                priv->inhibitors = NULL;
        }

        if (priv->presence != NULL) {
                g_object_unref (priv->presence);
                priv->presence = NULL;
        }

        if (priv->settings_session) {
                g_object_unref (priv->settings_session);
                priv->settings_session = NULL;
        }

        if (priv->settings_lockdown) {
                g_object_unref (priv->settings_lockdown);
                priv->settings_lockdown = NULL;
        }

        if (priv->settings_screensaver) {
                g_object_unref (priv->settings_screensaver);
                priv->settings_screensaver = NULL;
        }
        G_OBJECT_CLASS (gsm_manager_parent_class)->dispose (object);
}

static void
gsm_manager_class_init (GsmManagerClass *klass)
{
        GObjectClass   *object_class = G_OBJECT_CLASS (klass);

        object_class->get_property = gsm_manager_get_property;
        object_class->set_property = gsm_manager_set_property;
        object_class->constructor = gsm_manager_constructor;
        object_class->finalize = gsm_manager_finalize;
        object_class->dispose = gsm_manager_dispose;

        signals [PHASE_CHANGED] =
                g_signal_new ("phase-changed",
                              G_TYPE_FROM_CLASS (object_class),
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GsmManagerClass, phase_changed),
                              NULL,
                              NULL,
                              g_cclosure_marshal_VOID__STRING,
                              G_TYPE_NONE,
                              1, G_TYPE_STRING);

        signals [SESSION_RUNNING] =
                g_signal_new ("session-running",
                              G_OBJECT_CLASS_TYPE (object_class),
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GsmManagerClass, session_running),
                              NULL,
                              NULL,
                              g_cclosure_marshal_VOID__VOID,
                              G_TYPE_NONE,
                              0);

        signals [SESSION_OVER] =
                g_signal_new ("session-over",
                              G_OBJECT_CLASS_TYPE (object_class),
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GsmManagerClass, session_over),
                              NULL, NULL,
                              g_cclosure_marshal_VOID__VOID,
                              G_TYPE_NONE,
                              0);
        signals [CLIENT_ADDED] =
                g_signal_new ("client-added",
                              G_TYPE_FROM_CLASS (object_class),
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GsmManagerClass, client_added),
                              NULL,
                              NULL,
                              g_cclosure_marshal_VOID__BOXED,
                              G_TYPE_NONE,
                              1, DBUS_TYPE_G_OBJECT_PATH);
        signals [CLIENT_REMOVED] =
                g_signal_new ("client-removed",
                              G_TYPE_FROM_CLASS (object_class),
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GsmManagerClass, client_removed),
                              NULL,
                              NULL,
                              g_cclosure_marshal_VOID__BOXED,
                              G_TYPE_NONE,
                              1, DBUS_TYPE_G_OBJECT_PATH);
        signals [INHIBITOR_ADDED] =
                g_signal_new ("inhibitor-added",
                              G_TYPE_FROM_CLASS (object_class),
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GsmManagerClass, inhibitor_added),
                              NULL,
                              NULL,
                              g_cclosure_marshal_VOID__BOXED,
                              G_TYPE_NONE,
                              1, DBUS_TYPE_G_OBJECT_PATH);
        signals [INHIBITOR_REMOVED] =
                g_signal_new ("inhibitor-removed",
                              G_TYPE_FROM_CLASS (object_class),
                              G_SIGNAL_RUN_LAST,
                              G_STRUCT_OFFSET (GsmManagerClass, inhibitor_removed),
                              NULL,
                              NULL,
                              g_cclosure_marshal_VOID__BOXED,
                              G_TYPE_NONE,
                              1, DBUS_TYPE_G_OBJECT_PATH);

        g_object_class_install_property (object_class,
                                         PROP_FAILSAFE,
                                         g_param_spec_boolean ("failsafe",
                                                               NULL,
                                                               NULL,
                                                               FALSE,
                                                               G_PARAM_READWRITE | G_PARAM_CONSTRUCT));
        g_object_class_install_property (object_class,
                                         PROP_CLIENT_STORE,
                                         g_param_spec_object ("client-store",
                                                              NULL,
                                                              NULL,
                                                              GSM_TYPE_STORE,
                                                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT));

        g_object_class_install_property (object_class,
                                         PROP_RENDERER,
                                         g_param_spec_string ("renderer",
                                                              NULL,
                                                              NULL,
                                                              NULL,
                                                              G_PARAM_READABLE));

        dbus_g_object_type_install_info (GSM_TYPE_MANAGER, &dbus_glib_gsm_manager_object_info);
        dbus_g_error_domain_register (GSM_MANAGER_ERROR, NULL, GSM_MANAGER_TYPE_ERROR);
}

static void
load_idle_delay_from_gsettings (GsmManager *manager)
{
        glong   value;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        value = g_settings_get_int (priv->settings_session,
                                    KEY_IDLE_DELAY);
        gsm_presence_set_idle_timeout (priv->presence, value * 60000);
}

static void
on_gsettings_key_changed (GSettings   *settings,
                          gchar       *key,
                          GsmManager  *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        if (g_strcmp0 (key, KEY_IDLE_DELAY) == 0) {
                int delay;
                delay = g_settings_get_int (settings, key);
                gsm_presence_set_idle_timeout (priv->presence, delay * 60000);
        } else if (g_strcmp0 (key, KEY_LOCK_DISABLE) == 0) {
                /* ??? */
                gboolean UNUSED_VARIABLE disabled;
                disabled = g_settings_get_boolean (settings, key);
        } else if (g_strcmp0 (key, KEY_USER_SWITCH_DISABLE) == 0) {
                /* ??? */
                gboolean UNUSED_VARIABLE disabled;
                disabled = g_settings_get_boolean (settings, key);
        } else {
                g_debug ("Config key not handled: %s", key);
        }
}

static void
on_presence_status_changed (GsmPresence  *presence,
                            guint         status,
                            GsmManager   *manager)
{
#ifdef HAVE_SYSTEMD
        if (LOGIND_RUNNING()) {
                GsmSystemd *systemd;

                systemd = gsm_get_systemd ();
                gsm_systemd_set_session_idle (systemd,
                                              (status == GSM_PRESENCE_STATUS_IDLE));
        }
        else {
#endif
        GsmConsolekit *consolekit;

        consolekit = gsm_get_consolekit ();
        gsm_consolekit_set_session_idle (consolekit,
                                         (status == GSM_PRESENCE_STATUS_IDLE));
#ifdef HAVE_SYSTEMD
        }
#endif
}

static void
gsm_manager_init (GsmManager *manager)
{
        gchar **schemas = NULL;
        gboolean schema_exists;
        guint i;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        priv->settings_session = g_settings_new (SESSION_SCHEMA);
        priv->settings_lockdown = g_settings_new (LOCKDOWN_SCHEMA);

        /* check if mate-screensaver is installed */
        g_settings_schema_source_list_schemas (g_settings_schema_source_get_default (), TRUE, &schemas, NULL);
        schema_exists = FALSE;
        for (i = 0; schemas[i] != NULL; i++) {
                if (g_str_equal (schemas[i], SCREENSAVER_SCHEMA)) {
                        schema_exists = TRUE;
                        break;
                }
        }

        g_strfreev (schemas);

        if (schema_exists == TRUE)
                priv->settings_screensaver = g_settings_new (SCREENSAVER_SCHEMA);
        else
                priv->settings_screensaver = NULL;

        priv->inhibitors = gsm_store_new ();
        g_signal_connect (priv->inhibitors,
                          "added",
                          G_CALLBACK (on_store_inhibitor_added),
                          manager);
        g_signal_connect (priv->inhibitors,
                          "removed",
                          G_CALLBACK (on_store_inhibitor_removed),
                          manager);

        priv->apps = gsm_store_new ();

        priv->presence = gsm_presence_new ();
        g_signal_connect (priv->presence,
                          "status-changed",
                          G_CALLBACK (on_presence_status_changed),
                          manager);
        g_signal_connect (priv->settings_session,
                          "changed",
                          G_CALLBACK (on_gsettings_key_changed),
                          manager);
        g_signal_connect (priv->settings_lockdown,
                          "changed",
                          G_CALLBACK (on_gsettings_key_changed),
                          manager);

        load_idle_delay_from_gsettings (manager);
}

static void
gsm_manager_finalize (GObject *object)
{
        GsmManager *manager;
        GsmManagerPrivate *priv;

        g_return_if_fail (object != NULL);
        g_return_if_fail (GSM_IS_MANAGER (object));

        manager = GSM_MANAGER (object);
        priv = gsm_manager_get_instance_private (manager);

        g_return_if_fail (priv != NULL);

        G_OBJECT_CLASS (gsm_manager_parent_class)->finalize (object);
}

GsmManager *
gsm_manager_new (GsmStore *client_store,
                 gboolean  failsafe)
{
        if (manager_object != NULL) {
                g_object_ref (manager_object);
        } else {
                gboolean res;

                manager_object = g_object_new (GSM_TYPE_MANAGER,
                                               "client-store", client_store,
                                               "failsafe", failsafe,
                                               NULL);

                g_object_add_weak_pointer (manager_object,
                                           (gpointer *) &manager_object);
                res = register_manager (manager_object);
                if (! res) {
                        g_object_unref (manager_object);
                        return NULL;
                }
        }

        return GSM_MANAGER (manager_object);
}

gboolean
gsm_manager_setenv (GsmManager  *manager,
                    const char  *variable,
                    const char  *value,
                    GError     **error)
{
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        if (priv->phase > GSM_MANAGER_PHASE_INITIALIZATION) {
                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_NOT_IN_INITIALIZATION,
                             "Setenv interface is only available during the Initialization phase");
                return FALSE;
        }

        gsm_util_setenv (variable, value);

        return TRUE;
}

gboolean
gsm_manager_initialization_error (GsmManager  *manager,
                                  const char  *message,
                                  gboolean     fatal,
                                  GError     **error)
{
        GsmManagerPrivate *priv;
        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);

        if (priv->phase > GSM_MANAGER_PHASE_INITIALIZATION) {
                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_NOT_IN_INITIALIZATION,
                             "InitializationError interface is only available during the Initialization phase");
                return FALSE;
        }

        gsm_util_init_error (fatal, "%s", message);

        return TRUE;
}

static gboolean
gsm_manager_is_switch_user_inhibited (GsmManager *manager)
{
        GsmInhibitor *inhibitor;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        if (priv->inhibitors == NULL) {
                return FALSE;
        }

        inhibitor = (GsmInhibitor *)gsm_store_find (priv->inhibitors,
                                                    (GsmStoreFunc)inhibitor_has_flag,
                                                    GUINT_TO_POINTER (GSM_INHIBITOR_FLAG_SWITCH_USER));
        if (inhibitor == NULL) {
                return FALSE;
        }
        return TRUE;
}

static gboolean
gsm_manager_is_suspend_inhibited (GsmManager *manager)
{
        GsmInhibitor *inhibitor;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        if (priv->inhibitors == NULL) {
                return FALSE;
        }

        inhibitor = (GsmInhibitor *)gsm_store_find (priv->inhibitors,
                                                    (GsmStoreFunc)inhibitor_has_flag,
                                                    GUINT_TO_POINTER (GSM_INHIBITOR_FLAG_SUSPEND));
        if (inhibitor == NULL) {
                return FALSE;
        }
        return TRUE;
}

static void
request_reboot_privileges_completed_consolekit (GsmConsolekit *consolekit,
                                                gboolean       success,
                                                gboolean       ask_later,
                                                GError        *error,
                                                GsmManager    *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        /* make sure we disconnect the signal handler so that it's not called
         * again next time the event is fired -- this can happen if the reboot
         * is cancelled. */
        g_signal_handlers_disconnect_by_func (consolekit,
                                              request_reboot_privileges_completed_consolekit,
                                              manager);

        g_object_unref (consolekit);

        if (success) {
                if (ask_later) {
                        priv->logout_type = GSM_MANAGER_LOGOUT_REBOOT_INTERACT;
                } else {
                        priv->logout_type = GSM_MANAGER_LOGOUT_REBOOT;
                }

                end_phase (manager);
        }
}

#ifdef HAVE_SYSTEMD
static void
request_reboot_privileges_completed_systemd (GsmSystemd *systemd,
                                             gboolean    success,
                                             gboolean    ask_later,
                                             GError     *error,
                                             GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        /* make sure we disconnect the signal handler so that it's not called
         * again next time the event is fired -- this can happen if the reboot
         * is cancelled. */
        g_signal_handlers_disconnect_by_func (systemd,
                                              request_reboot_privileges_completed_systemd,
                                              manager);

        g_object_unref (systemd);

        if (success) {
                if (ask_later) {
                        priv->logout_type = GSM_MANAGER_LOGOUT_REBOOT_INTERACT;
                } else {
                        priv->logout_type = GSM_MANAGER_LOGOUT_REBOOT;
                }

                end_phase (manager);
        }
}
#endif

static void
request_reboot (GsmManager *manager)
{
        GsmConsolekit *consolekit;
#ifdef HAVE_SYSTEMD
        GsmSystemd *systemd;
#endif
        gboolean       success;
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: requesting reboot");

        priv = gsm_manager_get_instance_private (manager);

        /* We request the privileges before doing anything. There are a few
         * different cases here:
         *
         *   - no systemd: we fallback on ConsoleKit
         *   - no ConsoleKit: we fallback on MDM
         *   - no password required: everything is fine
         *   - password asked once: we ask for it now. If the user enters it
         *     fine, then all is great. If the user doesn't enter it fine, we
         *     don't do anything (so no logout).
         *   - password asked each time: we don't ask it for now since we don't
         *     want to ask for it twice. Instead we'll ask for it at the very
         *     end. If the user will enter it fine, then all is great again. If
         *     the user doesn't enter it fine, then we'll just fallback to MDM.
         *
         * The last case (password asked each time) is a bit broken, but
         * there's really nothing we can do about it. Generally speaking,
         * though, the password will only be asked once (unless the system is
         * configured in paranoid mode), and most probably only if there are
         * more than one user connected. So the general case is that it will
         * just work fine.
         */

#ifdef HAVE_SYSTEMD
        if (LOGIND_RUNNING()) {
                systemd = gsm_get_systemd ();
                g_signal_connect (systemd,
                                  "privileges-completed",
                                  G_CALLBACK (request_reboot_privileges_completed_systemd),
                                  manager);
                success = gsm_systemd_get_restart_privileges (systemd);

                if (!success) {
                        g_signal_handlers_disconnect_by_func (systemd,
                                                              request_reboot_privileges_completed_systemd,
                                                              manager);
                        g_object_unref (systemd);

                        priv->logout_type = GSM_MANAGER_LOGOUT_REBOOT_MDM;
                        end_phase (manager);
                }
        }
        else {
#endif
        consolekit = gsm_get_consolekit ();
        g_signal_connect (consolekit,
                          "privileges-completed",
                          G_CALLBACK (request_reboot_privileges_completed_consolekit),
                          manager);
        success = gsm_consolekit_get_restart_privileges (consolekit);

        if (!success) {
                g_signal_handlers_disconnect_by_func (consolekit,
                                                      request_reboot_privileges_completed_consolekit,
                                                      manager);
                g_object_unref (consolekit);

                priv->logout_type = GSM_MANAGER_LOGOUT_REBOOT_MDM;
                end_phase (manager);
        }
#ifdef HAVE_SYSTEMD
        }
#endif
}

static void
request_shutdown_privileges_completed_consolekit (GsmConsolekit *consolekit,
                                                  gboolean       success,
                                                  gboolean       ask_later,
                                                  GError        *error,
                                                  GsmManager    *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        /* make sure we disconnect the signal handler so that it's not called
         * again next time the event is fired -- this can happen if the reboot
         * is cancelled. */
        g_signal_handlers_disconnect_by_func (consolekit,
                                              request_shutdown_privileges_completed_consolekit,
                                              manager);

        g_object_unref (consolekit);

        if (success) {
                if (ask_later) {
                        priv->logout_type = GSM_MANAGER_LOGOUT_SHUTDOWN_INTERACT;
                } else {
                        priv->logout_type = GSM_MANAGER_LOGOUT_SHUTDOWN;
                }

                end_phase (manager);
        }
}

#ifdef HAVE_SYSTEMD
static void
request_shutdown_privileges_completed_systemd (GsmSystemd *systemd,
                                               gboolean    success,
                                               gboolean    ask_later,
                                               GError     *error,
                                               GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        /* make sure we disconnect the signal handler so that it's not called
         * again next time the event is fired -- this can happen if the reboot
         * is cancelled. */
        g_signal_handlers_disconnect_by_func (systemd,
                                              request_shutdown_privileges_completed_systemd,
                                              manager);

        g_object_unref (systemd);

        if (success) {
                if (ask_later) {
                        priv->logout_type = GSM_MANAGER_LOGOUT_SHUTDOWN_INTERACT;
                } else {
                        priv->logout_type = GSM_MANAGER_LOGOUT_SHUTDOWN;
                }

                end_phase (manager);
        }
}
#endif

static void
request_shutdown (GsmManager *manager)
{
        GsmConsolekit *consolekit;
#ifdef HAVE_SYSTEMD
        GsmSystemd *systemd;
#endif
        gboolean       success;
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: requesting shutdown");

        priv = gsm_manager_get_instance_private (manager);

        /* See the comment in request_reboot() for some more details about how
         * this works. */

#ifdef HAVE_SYSTEMD
        if (LOGIND_RUNNING()) {
                systemd = gsm_get_systemd ();
                g_signal_connect (systemd,
                                  "privileges-completed",
                                  G_CALLBACK (request_shutdown_privileges_completed_systemd),
                                  manager);
                success = gsm_systemd_get_stop_privileges (systemd);

                if (!success) {
                        g_signal_handlers_disconnect_by_func (systemd,
                                                              request_shutdown_privileges_completed_systemd,
                                                              manager);
                        g_object_unref (systemd);

                        priv->logout_type = GSM_MANAGER_LOGOUT_SHUTDOWN_MDM;
                        end_phase (manager);
                }
        }
        else {
#endif
        consolekit = gsm_get_consolekit ();
        g_signal_connect (consolekit,
                          "privileges-completed",
                          G_CALLBACK (request_shutdown_privileges_completed_consolekit),
                          manager);
        success = gsm_consolekit_get_stop_privileges (consolekit);

        if (!success) {
                g_signal_handlers_disconnect_by_func (consolekit,
                                                      request_shutdown_privileges_completed_consolekit,
                                                      manager);
                g_object_unref (consolekit);

                priv->logout_type = GSM_MANAGER_LOGOUT_SHUTDOWN_MDM;
                end_phase (manager);
        }
#ifdef HAVE_SYSTEMD
        }
#endif
}

static void
request_suspend (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: requesting suspend");

        if (! gsm_manager_is_suspend_inhibited (manager)) {
                manager_attempt_suspend (manager);
                return;
        }

        priv = gsm_manager_get_instance_private (manager);
        if (priv->inhibit_dialog != NULL) {
                g_debug ("GsmManager: inhibit dialog already up");
                gtk_window_present (GTK_WINDOW (priv->inhibit_dialog));
                return;
        }

        priv->inhibit_dialog = gsm_inhibit_dialog_new (priv->inhibitors,
                                                       priv->clients,
                                                       GSM_LOGOUT_ACTION_SLEEP);

        g_signal_connect (priv->inhibit_dialog,
                          "response",
                          G_CALLBACK (inhibit_dialog_response),
                          manager);
        gtk_widget_show (priv->inhibit_dialog);
}

static void
request_hibernate (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: requesting hibernate");

        /* hibernate uses suspend inhibit */
        if (! gsm_manager_is_suspend_inhibited (manager)) {
                manager_attempt_hibernate (manager);
                return;
        }

        priv = gsm_manager_get_instance_private (manager);
        if (priv->inhibit_dialog != NULL) {
                g_debug ("GsmManager: inhibit dialog already up");
                gtk_window_present (GTK_WINDOW (priv->inhibit_dialog));
                return;
        }

        priv->inhibit_dialog = gsm_inhibit_dialog_new (priv->inhibitors,
                                                       priv->clients,
                                                       GSM_LOGOUT_ACTION_HIBERNATE);

        g_signal_connect (priv->inhibit_dialog,
                          "response",
                          G_CALLBACK (inhibit_dialog_response),
                          manager);
        gtk_widget_show (priv->inhibit_dialog);
}


static void
request_logout (GsmManager            *manager,
                GsmManagerLogoutMode  mode)
{
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: requesting logout");

        priv = gsm_manager_get_instance_private (manager);

        priv->logout_mode = mode;
        priv->logout_type = GSM_MANAGER_LOGOUT_LOGOUT;

        end_phase (manager);
}

static void
request_switch_user (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: requesting user switch");

        /* See comment in manager_switch_user() to understand why we do this in
         * both functions. */
        if (_switch_user_is_locked_down (manager)) {
                g_warning ("Unable to switch user: User switching has been locked down");
                return;
        }

        if (! gsm_manager_is_switch_user_inhibited (manager)) {
                manager_switch_user (manager);
                return;
        }

        priv = gsm_manager_get_instance_private (manager);
        if (priv->inhibit_dialog != NULL) {
                g_debug ("GsmManager: inhibit dialog already up");
                gtk_window_present (GTK_WINDOW (priv->inhibit_dialog));
                return;
        }

        priv->inhibit_dialog = gsm_inhibit_dialog_new (priv->inhibitors,
                                                       priv->clients,
                                                       GSM_LOGOUT_ACTION_SWITCH_USER);

        g_signal_connect (priv->inhibit_dialog,
                          "response",
                          G_CALLBACK (inhibit_dialog_response),
                          manager);
        gtk_widget_show (priv->inhibit_dialog);
}

static void
logout_dialog_response (GsmLogoutDialog *logout_dialog,
                        guint            response_id,
                        GsmManager      *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        /* We should only be here if mode has already have been set from
         * show_fallback_shutdown/logout_dialog
         */
        g_assert (priv->logout_mode == GSM_MANAGER_LOGOUT_MODE_NORMAL);

        g_debug ("GsmManager: Logout dialog response: %d", response_id);

        gtk_widget_destroy (GTK_WIDGET (logout_dialog));

        /* In case of dialog cancel, switch user, hibernate and
         * suspend, we just perform the respective action and return,
         * without shutting down the session. */
        switch (response_id) {
        case GTK_RESPONSE_CANCEL:
        case GTK_RESPONSE_NONE:
        case GTK_RESPONSE_DELETE_EVENT:
                break;
        case GSM_LOGOUT_RESPONSE_SWITCH_USER:
                request_switch_user (manager);
                break;
        case GSM_LOGOUT_RESPONSE_HIBERNATE:
                request_hibernate (manager);
                break;
        case GSM_LOGOUT_RESPONSE_SLEEP:
                request_suspend (manager);
                break;
        case GSM_LOGOUT_RESPONSE_SHUTDOWN:
                request_shutdown (manager);
                break;
        case GSM_LOGOUT_RESPONSE_REBOOT:
                request_reboot (manager);
                break;
        case GSM_LOGOUT_RESPONSE_LOGOUT:
                /* We've already gotten confirmation from the user so
                 * initiate the logout in NO_CONFIRMATION mode.
                 *
                 * (it shouldn't matter whether we use NO_CONFIRMATION or stay
                 * with NORMAL, unless the shell happens to start after the
                 * user confirmed)
                 */
                request_logout (manager, GSM_MANAGER_LOGOUT_MODE_NO_CONFIRMATION);
                break;
        default:
                g_assert_not_reached ();
                break;
        }
}

static void
show_shutdown_dialog (GsmManager *manager)
{
        GtkWidget *dialog;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        if (priv->phase >= GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                /* Already shutting down, nothing more to do */
                return;
        }

        priv->logout_mode = GSM_MANAGER_LOGOUT_MODE_NORMAL;

        dialog = gsm_get_shutdown_dialog (gdk_screen_get_default (),
                                          gtk_get_current_event_time ());

        g_signal_connect (dialog,
                          "response",
                          G_CALLBACK (logout_dialog_response),
                          manager);
        gtk_widget_show (dialog);
        gtk_window_present_with_time (GTK_WINDOW (dialog),
                                      gdk_x11_get_server_time (gtk_widget_get_window (GTK_WIDGET (dialog))));
}

static void
show_logout_dialog (GsmManager *manager)
{
        GtkWidget *dialog;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        if (priv->phase >= GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                /* Already shutting down, nothing more to do */
                return;
        }

        priv->logout_mode = GSM_MANAGER_LOGOUT_MODE_NORMAL;

        dialog = gsm_get_logout_dialog (gdk_screen_get_default (),
                                        gtk_get_current_event_time ());

        g_signal_connect (dialog,
                          "response",
                          G_CALLBACK (logout_dialog_response),
                          manager);
        gtk_widget_show (dialog);
        gtk_window_present_with_time (GTK_WINDOW (dialog),
                                      gdk_x11_get_server_time (gtk_widget_get_window (GTK_WIDGET (dialog))));
}

static void
user_logout (GsmManager           *manager,
             GsmManagerLogoutMode  mode)
{
        gboolean logout_prompt;
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        if (priv->phase >= GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                /* Already shutting down, nothing more to do */
                return;
        }

        logout_prompt =
               g_settings_get_boolean (priv->settings_session,
                                       "logout-prompt");

        /* If the shell isn't running, and this isn't a non-interative logout request,
         * and the user has their settings configured to show a confirmation dialog for
         * logout, then go ahead and show the confirmation dialog now.
         */
        if (mode == GSM_MANAGER_LOGOUT_MODE_NORMAL && logout_prompt) {
                show_logout_dialog (manager);
        } else {
                request_logout (manager, mode);
        }
}

/*
  dbus-send --session --type=method_call --print-reply
      --dest=org.gnome.SessionManager
      /org/gnome/SessionManager
      org.freedesktop.DBus.Introspectable.Introspect
*/

gboolean
gsm_manager_set_phase (GsmManager      *manager,
                       GsmManagerPhase  phase)
{
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        priv->phase = phase;
        return (TRUE);
}

gboolean
gsm_manager_request_shutdown (GsmManager *manager,
                              GError    **error)
{
        GsmManagerPrivate *priv;
        g_debug ("GsmManager: RequestShutdown called");

        g_return_val_if_fail(GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        if (priv->phase != GSM_MANAGER_PHASE_RUNNING) {
                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_NOT_IN_RUNNING,
                             "RequestShutdown interface is only available during the Running phase");
                return FALSE;
        }

        request_shutdown (manager);

        return TRUE;
}

gboolean
gsm_manager_request_reboot (GsmManager *manager,
                            GError    **error)
{
        GsmManagerPrivate *priv;

        g_debug ("GsmManager: RequestReboot called");

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        if (priv->phase != GSM_MANAGER_PHASE_RUNNING) {
                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_NOT_IN_RUNNING,
                             "RequestReboot interface is only available during the running phase");
                return FALSE;
        }

        request_reboot (manager);

        return TRUE;
}

static gboolean
_log_out_is_locked_down (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);

        return g_settings_get_boolean (priv->settings_lockdown,
                                       KEY_LOG_OUT_DISABLE);
}

static gboolean
_switch_user_is_locked_down (GsmManager *manager)
{
        GsmManagerPrivate *priv;

        priv = gsm_manager_get_instance_private (manager);
        return g_settings_get_boolean (priv->settings_lockdown,
                                       KEY_USER_SWITCH_DISABLE);
}

gboolean
gsm_manager_shutdown (GsmManager *manager,
                      GError    **error)
{
        GsmManagerPrivate *priv;
        g_debug ("GsmManager: Shutdown called");

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        if (priv->phase != GSM_MANAGER_PHASE_RUNNING) {
                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_NOT_IN_RUNNING,
                             "Shutdown interface is only available during the Running phase");
                return FALSE;
        }

        if (_log_out_is_locked_down (manager)) {
                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_LOCKED_DOWN,
                             "Logout has been locked down");
                return FALSE;
        }

        show_shutdown_dialog (manager);

        return TRUE;
}

gboolean
gsm_manager_can_shutdown (GsmManager *manager,
                          gboolean   *shutdown_available,
                          GError    **error)
{
        GsmConsolekit *consolekit;
#ifdef HAVE_SYSTEMD
        GsmSystemd *systemd;
#endif
        g_debug ("GsmManager: CanShutdown called");

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

#ifdef HAVE_SYSTEMD
        if (LOGIND_RUNNING()) {
                systemd = gsm_get_systemd ();
                *shutdown_available = gsm_systemd_can_stop (systemd)
                                      || gsm_systemd_can_restart (systemd)
                                      || gsm_systemd_can_suspend (systemd)
                                      || gsm_systemd_can_hibernate (systemd);
                g_object_unref (systemd);
        }
        else {
#endif
        consolekit = gsm_get_consolekit ();
        *shutdown_available = !_log_out_is_locked_down (manager) &&
                              (gsm_consolekit_can_stop (consolekit)
                               || gsm_consolekit_can_restart (consolekit)
                               || gsm_consolekit_can_suspend (consolekit)
                               || gsm_consolekit_can_hibernate (consolekit));
        g_object_unref (consolekit);
#ifdef HAVE_SYSTEMD
        }
#endif

        return TRUE;
}

gboolean
gsm_manager_logout (GsmManager *manager,
                    guint       logout_mode,
                    GError    **error)
{
        GsmManagerPrivate *priv;
        g_debug ("GsmManager: Logout called");

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        if (priv->phase != GSM_MANAGER_PHASE_RUNNING) {
                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_NOT_IN_RUNNING,
                             "Shutdown interface is only available during the Running phase");
                return FALSE;
        }

        if (_log_out_is_locked_down (manager)) {
                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_LOCKED_DOWN,
                             "Logout has been locked down");
                return FALSE;
        }

        switch (logout_mode) {
        case GSM_MANAGER_LOGOUT_MODE_NORMAL:
        case GSM_MANAGER_LOGOUT_MODE_NO_CONFIRMATION:
        case GSM_MANAGER_LOGOUT_MODE_FORCE:
                user_logout (manager, logout_mode);
                break;

        default:
                g_debug ("Unknown logout mode option");

                g_set_error (error,
                             GSM_MANAGER_ERROR,
                             GSM_MANAGER_ERROR_INVALID_OPTION,
                             "Unknown logout mode flag");
                return FALSE;
        }

        return TRUE;
}

gboolean
gsm_manager_register_client (GsmManager            *manager,
                             const char            *app_id,
                             const char            *startup_id,
                             DBusGMethodInvocation *context)
{
        char      *new_startup_id;
        char      *sender;
        GsmClient *client;
        GsmApp    *app;
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        app = NULL;
        client = NULL;

        g_debug ("GsmManager: RegisterClient %s", startup_id);

        priv = gsm_manager_get_instance_private (manager);
        if (priv->phase >= GSM_MANAGER_PHASE_QUERY_END_SESSION) {
                GError *new_error;

                g_debug ("Unable to register client: shutting down");

                new_error = g_error_new (GSM_MANAGER_ERROR,
                                         GSM_MANAGER_ERROR_NOT_IN_RUNNING,
                                         "Unable to register client");
                dbus_g_method_return_error (context, new_error);
                g_error_free (new_error);
                return FALSE;
        }

        if (IS_STRING_EMPTY (startup_id)) {
                new_startup_id = gsm_util_generate_startup_id ();
        } else {

                client = (GsmClient *)gsm_store_find (priv->clients,
                                                      (GsmStoreFunc)_client_has_startup_id,
                                                      (char *)startup_id);
                /* We can't have two clients with the same startup id. */
                if (client != NULL) {
                        GError *new_error;

                        g_debug ("Unable to register client: already registered");

                        new_error = g_error_new (GSM_MANAGER_ERROR,
                                                 GSM_MANAGER_ERROR_ALREADY_REGISTERED,
                                                 "Unable to register client");
                        dbus_g_method_return_error (context, new_error);
                        g_error_free (new_error);
                        return FALSE;
                }

                new_startup_id = g_strdup (startup_id);
        }

        g_debug ("GsmManager: Adding new client %s to session", new_startup_id);

        if (app == NULL && !IS_STRING_EMPTY (startup_id)) {
                app = find_app_for_startup_id (manager, startup_id);
        }
        if (app == NULL && !IS_STRING_EMPTY (app_id)) {
                /* try to associate this app id with a known app */
                app = find_app_for_app_id (manager, app_id);
        }

        sender = dbus_g_method_get_sender (context);
        client = gsm_dbus_client_new (new_startup_id, sender);
        g_free (sender);
        if (client == NULL) {
                GError *new_error;

                g_debug ("Unable to create client");

                new_error = g_error_new (GSM_MANAGER_ERROR,
                                         GSM_MANAGER_ERROR_GENERAL,
                                         "Unable to register client");
                dbus_g_method_return_error (context, new_error);
                g_error_free (new_error);
                return FALSE;
        }

        gsm_store_add (priv->clients, gsm_client_peek_id (client), G_OBJECT (client));
        /* the store will own the ref */
        g_object_unref (client);

        if (app != NULL) {
                gsm_client_set_app_id (client, gsm_app_peek_app_id (app));
                gsm_app_registered (app);
        } else {
                /* if an app id is specified store it in the client
                   so we can save it later */
                gsm_client_set_app_id (client, app_id);
        }

        gsm_client_set_status (client, GSM_CLIENT_REGISTERED);

        g_assert (new_startup_id != NULL);
        g_free (new_startup_id);

        dbus_g_method_return (context, gsm_client_peek_id (client));

        return TRUE;
}

gboolean
gsm_manager_unregister_client (GsmManager            *manager,
                               const char            *client_id,
                               DBusGMethodInvocation *context)
{
        GsmClient *client;
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        g_debug ("GsmManager: UnregisterClient %s", client_id);

        priv = gsm_manager_get_instance_private (manager);
        client = (GsmClient *)gsm_store_lookup (priv->clients, client_id);
        if (client == NULL) {
                GError *new_error;

                g_debug ("Unable to unregister client: not registered");

                new_error = g_error_new (GSM_MANAGER_ERROR,
                                         GSM_MANAGER_ERROR_NOT_REGISTERED,
                                         "Unable to unregister client");
                dbus_g_method_return_error (context, new_error);
                g_error_free (new_error);
                return FALSE;
        }

        /* don't disconnect client here, only change the status.
           Wait until it leaves the bus before disconnecting it */
        gsm_client_set_status (client, GSM_CLIENT_UNREGISTERED);

        dbus_g_method_return (context);

        return TRUE;
}

gboolean
gsm_manager_inhibit (GsmManager            *manager,
                     const char            *app_id,
                     guint                  toplevel_xid,
                     const char            *reason,
                     guint                  flags,
                     DBusGMethodInvocation *context)
{
        GsmInhibitor *inhibitor;
        guint         cookie;
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        g_debug ("GsmManager: Inhibit xid=%u app_id=%s reason=%s flags=%u",
                 toplevel_xid,
                 app_id,
                 reason,
                 flags);

        priv = gsm_manager_get_instance_private (manager);
        if (priv->logout_mode == GSM_MANAGER_LOGOUT_MODE_FORCE) {
                GError *new_error;

                new_error = g_error_new (GSM_MANAGER_ERROR,
                                         GSM_MANAGER_ERROR_GENERAL,
                                         "Forced logout cannot be inhibited");
                g_debug ("GsmManager: Unable to inhibit: %s", new_error->message);
                dbus_g_method_return_error (context, new_error);
                g_error_free (new_error);
                return FALSE;
        }

        if (IS_STRING_EMPTY (app_id)) {
                GError *new_error;

                new_error = g_error_new (GSM_MANAGER_ERROR,
                                         GSM_MANAGER_ERROR_GENERAL,
                                         "Application ID not specified");
                g_debug ("GsmManager: Unable to inhibit: %s", new_error->message);
                dbus_g_method_return_error (context, new_error);
                g_error_free (new_error);
                return FALSE;
        }

        if (IS_STRING_EMPTY (reason)) {
                GError *new_error;

                new_error = g_error_new (GSM_MANAGER_ERROR,
                                         GSM_MANAGER_ERROR_GENERAL,
                                         "Reason not specified");
                g_debug ("GsmManager: Unable to inhibit: %s", new_error->message);
                dbus_g_method_return_error (context, new_error);
                g_error_free (new_error);
                return FALSE;
        }

        if (flags == 0) {
                GError *new_error;

                new_error = g_error_new (GSM_MANAGER_ERROR,
                                         GSM_MANAGER_ERROR_GENERAL,
                                         "Invalid inhibit flags");
                g_debug ("GsmManager: Unable to inhibit: %s", new_error->message);
                dbus_g_method_return_error (context, new_error);
                g_error_free (new_error);
                return FALSE;
        }

        cookie = _generate_unique_cookie (manager);
        inhibitor = gsm_inhibitor_new (app_id,
                                       toplevel_xid,
                                       flags,
                                       reason,
                                       dbus_g_method_get_sender (context),
                                       cookie);
        gsm_store_add (priv->inhibitors, gsm_inhibitor_peek_id (inhibitor), G_OBJECT (inhibitor));
        g_object_unref (inhibitor);

        dbus_g_method_return (context, cookie);

        return TRUE;
}

gboolean
gsm_manager_uninhibit (GsmManager            *manager,
                       guint                  cookie,
                       DBusGMethodInvocation *context)
{
        GsmInhibitor *inhibitor;
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        g_debug ("GsmManager: Uninhibit %u", cookie);

        priv = gsm_manager_get_instance_private (manager);
        inhibitor = (GsmInhibitor *)gsm_store_find (priv->inhibitors,
                                                    (GsmStoreFunc)_find_by_cookie,
                                                    &cookie);
        if (inhibitor == NULL) {
                GError *new_error;

                new_error = g_error_new (GSM_MANAGER_ERROR,
                                         GSM_MANAGER_ERROR_GENERAL,
                                         "Unable to uninhibit: Invalid cookie");
                dbus_g_method_return_error (context, new_error);
                g_debug ("Unable to uninhibit: %s", new_error->message);
                g_error_free (new_error);
                return FALSE;
        }

        g_debug ("GsmManager: removing inhibitor %s %u reason '%s' %u connection %s",
                 gsm_inhibitor_peek_app_id (inhibitor),
                 gsm_inhibitor_peek_toplevel_xid (inhibitor),
                 gsm_inhibitor_peek_reason (inhibitor),
                 gsm_inhibitor_peek_flags (inhibitor),
                 gsm_inhibitor_peek_bus_name (inhibitor));

        gsm_store_remove (priv->inhibitors, gsm_inhibitor_peek_id (inhibitor));

        dbus_g_method_return (context);

        return TRUE;
}

gboolean
gsm_manager_is_inhibited (GsmManager *manager,
                          guint       flags,
                          gboolean   *is_inhibited,
                          GError     *error)
{
        GsmInhibitor *inhibitor;
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        if (priv->inhibitors == NULL
            || gsm_store_size (priv->inhibitors) == 0) {
                *is_inhibited = FALSE;
                return TRUE;
        }

        inhibitor = (GsmInhibitor *) gsm_store_find (priv->inhibitors,
                                                     (GsmStoreFunc)inhibitor_has_flag,
                                                     GUINT_TO_POINTER (flags));
        if (inhibitor == NULL) {
                *is_inhibited = FALSE;
        } else {
                *is_inhibited = TRUE;
        }

        return TRUE;

}

static gboolean
listify_store_ids (char       *id,
                   GObject    *object,
                   GPtrArray **array)
{
        g_ptr_array_add (*array, g_strdup (id));
        return FALSE;
}

gboolean
gsm_manager_get_clients (GsmManager *manager,
                         GPtrArray **clients,
                         GError    **error)
{
        GsmManagerPrivate *priv;
        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        if (clients == NULL) {
                return FALSE;
        }

        *clients = g_ptr_array_new ();
        priv = gsm_manager_get_instance_private (manager);
        gsm_store_foreach (priv->clients, (GsmStoreFunc)listify_store_ids, clients);

        return TRUE;
}

gboolean
gsm_manager_get_inhibitors (GsmManager *manager,
                            GPtrArray **inhibitors,
                            GError    **error)
{
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        if (inhibitors == NULL) {
                return FALSE;
        }

        *inhibitors = g_ptr_array_new ();
        priv = gsm_manager_get_instance_private (manager);
        gsm_store_foreach (priv->inhibitors,
                           (GsmStoreFunc) listify_store_ids,
                           inhibitors);

        return TRUE;
}


static gboolean
_app_has_autostart_condition (const char *id,
                              GsmApp     *app,
                              const char *condition)
{
        gboolean has;
        gboolean disabled;

        has = gsm_app_has_autostart_condition (app, condition);
        disabled = gsm_app_peek_is_disabled (app);

        return has && !disabled;
}

gboolean
gsm_manager_is_autostart_condition_handled (GsmManager *manager,
                                            const char *condition,
                                            gboolean   *handled,
                                            GError    **error)
{
        GsmApp *app;
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        app = (GsmApp *) gsm_store_find (priv->apps,(
                                         GsmStoreFunc) _app_has_autostart_condition,
                                         (char *)condition);

        if (app != NULL) {
                *handled = TRUE;
        } else {
                *handled = FALSE;
        }

        return TRUE;
}

static void
append_app (GsmManager *manager,
            GsmApp     *app)
{
        const char *id;
        const char *app_id;
        GsmApp     *dup;
        GsmManagerPrivate *priv;

        id = gsm_app_peek_id (app);
        if (IS_STRING_EMPTY (id)) {
                g_debug ("GsmManager: not adding app: no id");
                return;
        }

        priv = gsm_manager_get_instance_private (manager);
        dup = (GsmApp *)gsm_store_lookup (priv->apps, id);
        if (dup != NULL) {
                g_debug ("GsmManager: not adding app: already added");
                return;
        }

        app_id = gsm_app_peek_app_id (app);
        if (IS_STRING_EMPTY (app_id)) {
                g_debug ("GsmManager: not adding app: no app-id");
                return;
        }

        dup = find_app_for_app_id (manager, app_id);
        if (dup != NULL) {
                g_debug ("GsmManager: not adding app: app-id already exists");
                return;
        }

        gsm_store_add (priv->apps, id, G_OBJECT (app));
}

gboolean
gsm_manager_add_autostart_app (GsmManager *manager,
                               const char *path,
                               const char *provides)
{
        GsmApp *app;
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);
        g_return_val_if_fail (path != NULL, FALSE);

        priv = gsm_manager_get_instance_private (manager);
        /* first check to see if service is already provided */
        if (provides != NULL) {
                GsmApp *dup;

                dup = (GsmApp *)gsm_store_find (priv->apps,
                                                (GsmStoreFunc)_find_app_provides,
                                                (char *)provides);
                if (dup != NULL) {
                        g_debug ("GsmManager: service '%s' is already provided", provides);
                        return FALSE;
                }
        }

        app = gsm_autostart_app_new (path);
        if (app == NULL) {
                g_warning ("could not read %s", path);
                return FALSE;
        }

        g_debug ("GsmManager: read %s", path);
        append_app (manager, app);
        g_object_unref (app);

        return TRUE;
}

gboolean
gsm_manager_add_autostart_apps_from_dir (GsmManager *manager,
                                         const char *path)
{
        GDir       *dir;
        const char *name;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);
        g_return_val_if_fail (path != NULL, FALSE);

        g_debug ("GsmManager: *** Adding autostart apps for %s", path);

        dir = g_dir_open (path, 0, NULL);
        if (dir == NULL) {
                return FALSE;
        }

        while ((name = g_dir_read_name (dir))) {
                char *desktop_file;

                if (!g_str_has_suffix (name, ".desktop")) {
                        continue;
                }

                desktop_file = g_build_filename (path, name, NULL);
                gsm_manager_add_autostart_app (manager, desktop_file, NULL);
                g_free (desktop_file);
        }

        g_dir_close (dir);

        return TRUE;
}

gboolean
gsm_manager_is_session_running (GsmManager *manager,
                                gboolean *running,
                                GError **error)
{
        GsmManagerPrivate *priv;

        g_return_val_if_fail (GSM_IS_MANAGER (manager), FALSE);

        priv = gsm_manager_get_instance_private (manager);
        *running = (priv->phase == GSM_MANAGER_PHASE_RUNNING);
        return TRUE;
}