aboutsummaryrefslogtreecommitdiff
path: root/libdbusmenu-glib/server.c
blob: 91e7a2555a48b514dd3502b85df8d3a856deae19 (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
/*
A library to communicate a menu object set accross DBus and
track updates and maintain consistency.

Copyright 2009 Canonical Ltd.

Authors:
    Ted Gould <ted@canonical.com>

This program is free software: you can redistribute it and/or modify it 
under the terms of either or both of the following licenses:

1) the GNU Lesser General Public License version 3, as published by the 
Free Software Foundation; and/or
2) the GNU Lesser General Public License version 2.1, as published by 
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but 
WITHOUT ANY WARRANTY; without even the implied warranties of 
MERCHANTABILITY, SATISFACTORY QUALITY or FITNESS FOR A PARTICULAR 
PURPOSE.  See the applicable version of the GNU Lesser General Public 
License for more details.

You should have received a copy of both the GNU Lesser General Public 
License version 3 and version 2.1 along with this program.  If not, see 
<http://www.gnu.org/licenses/>
*/

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif

#include <glib/gi18n.h>
#include <gio/gio.h>

#include "menuitem-private.h"
#include "server.h"
#include "server-marshal.h"
#include "enum-types.h"

#include "dbus-menu-clean.xml.h"

static void layout_update_signal (DbusmenuServer * server);

#define DBUSMENU_VERSION_NUMBER    2
#define DBUSMENU_INTERFACE         "com.canonical.dbusmenu"

/* Privates, I'll show you mine... */
struct _DbusmenuServerPrivate
{
	DbusmenuMenuitem * root;
	gchar * dbusobject;
	gint layout_revision;
	guint layout_idle;

	GDBusConnection * bus;
	GCancellable * bus_lookup;
	guint dbus_registration;

	DbusmenuTextDirection text_direction;
	DbusmenuStatus status;

	GArray * prop_array;
	guint property_idle;
};

#define DBUSMENU_SERVER_GET_PRIVATE(o) (DBUSMENU_SERVER(o)->priv)

/* Signals */
enum {
	ID_PROP_UPDATE,
	ID_UPDATE,
	LAYOUT_UPDATED,
	ITEM_ACTIVATION,
	LAST_SIGNAL
};

static guint signals[LAST_SIGNAL] = { 0 };

/* Properties */
enum {
	PROP_0,
	PROP_DBUS_OBJECT,
	PROP_ROOT_NODE,
	PROP_VERSION,
	PROP_TEXT_DIRECTION,
	PROP_STATUS
};

/* Errors */
enum {
	INVALID_MENUITEM_ID,
	INVALID_PROPERTY_NAME,
	UNKNOWN_DBUS_ERROR,
	NOT_IMPLEMENTED,
	NO_VALID_LAYOUT,
	LAST_ERROR
};

/* Method Table */
typedef void (*MethodTableFunc) (DbusmenuServer * server, GVariant * params, GDBusMethodInvocation * invocation);

typedef struct _method_table_t method_table_t;
struct _method_table_t {
	const gchar * interned_name;
	MethodTableFunc func;
};

enum {
	METHOD_GET_LAYOUT = 0,
	METHOD_GET_GROUP_PROPERTIES,
	METHOD_GET_CHILDREN,
	METHOD_GET_PROPERTY,
	METHOD_GET_PROPERTIES,
	METHOD_EVENT,
	METHOD_ABOUT_TO_SHOW,
	/* Counter, do not remove! */
	METHOD_COUNT
};

/* Prototype */
static void       dbusmenu_server_class_init  (DbusmenuServerClass *class);
static void       dbusmenu_server_init        (DbusmenuServer *self);
static void       dbusmenu_server_dispose     (GObject *object);
static void       dbusmenu_server_finalize    (GObject *object);
static void       set_property                (GObject * obj,
                                               guint id,
                                               const GValue * value,
                                               GParamSpec * pspec);
static void       get_property                (GObject * obj,
                                               guint id,
                                               GValue * value,
                                               GParamSpec * pspec);
static void       default_text_direction      (DbusmenuServer * server);
static void       register_object             (DbusmenuServer * server);
static void       bus_got_cb                  (GObject * obj,
                                               GAsyncResult * result,
                                               gpointer user_data);
static void       bus_method_call             (GDBusConnection * connection,
                                               const gchar * sender,
                                               const gchar * path,
                                               const gchar * interface,
                                               const gchar * method,
                                               GVariant * params,
                                               GDBusMethodInvocation * invocation,
                                               gpointer user_data);
static GVariant * bus_get_prop                (GDBusConnection * connection,
                                               const gchar * sender,
                                               const gchar * path,
                                               const gchar * interface,
                                               const gchar * property,
                                               GError ** error,
                                               gpointer user_data);
static void       menuitem_property_changed   (DbusmenuMenuitem * mi,
                                               gchar * property,
                                               GVariant * variant,
                                               DbusmenuServer * server);
static void       menuitem_child_added        (DbusmenuMenuitem * parent,
                                               DbusmenuMenuitem * child,
                                               guint pos,
                                               DbusmenuServer * server);
static void       menuitem_child_removed      (DbusmenuMenuitem * parent,
                                               DbusmenuMenuitem * child,
                                               DbusmenuServer * server);
static void       menuitem_signals_create     (DbusmenuMenuitem * mi,
                                               gpointer data);
static void       menuitem_signals_remove     (DbusmenuMenuitem * mi,
                                               gpointer data);
static GQuark     error_quark                 (void);
static void       prop_array_teardown         (GArray * prop_array);
static void       bus_get_layout              (DbusmenuServer * server,
                                               GVariant * params,
                                               GDBusMethodInvocation * invocation);
static void       bus_get_group_properties    (DbusmenuServer * server,
                                               GVariant * params,
                                               GDBusMethodInvocation * invocation);
static void       bus_get_children            (DbusmenuServer * server,
                                               GVariant * params,
                                               GDBusMethodInvocation * invocation);
static void       bus_get_property            (DbusmenuServer * server,
                                               GVariant * params,
                                               GDBusMethodInvocation * invocation);
static void       bus_get_properties          (DbusmenuServer * server,
                                               GVariant * params,
                                               GDBusMethodInvocation * invocation);
static void       bus_event                   (DbusmenuServer * server,
                                               GVariant * params,
                                               GDBusMethodInvocation * invocation);
static void       bus_about_to_show           (DbusmenuServer * server,
                                               GVariant * params,
                                               GDBusMethodInvocation * invocation);

/* Globals */
static GDBusNodeInfo *            dbusmenu_node_info = NULL;
static GDBusInterfaceInfo *       dbusmenu_interface_info = NULL;
static const GDBusInterfaceVTable dbusmenu_interface_table = {
	method_call:    bus_method_call,
	get_property:   bus_get_prop,
	set_property:   NULL /* No properties that can be set */
};
static method_table_t             dbusmenu_method_table[METHOD_COUNT];

G_DEFINE_TYPE (DbusmenuServer, dbusmenu_server, G_TYPE_OBJECT);

static void
dbusmenu_server_class_init (DbusmenuServerClass *class)
{
	GObjectClass *object_class = G_OBJECT_CLASS (class);

	g_type_class_add_private (class, sizeof (DbusmenuServerPrivate));

	object_class->dispose = dbusmenu_server_dispose;
	object_class->finalize = dbusmenu_server_finalize;
	object_class->set_property = set_property;
	object_class->get_property = get_property;

	/**
		DbusmenuServer::id-prop-update:
		@arg0: The #DbusmenuServer emitting the signal.
		@arg1: The ID of the #DbusmenuMenuitem changing a property.
		@arg2: The property being changed.
		@arg3: The value of the property being changed.

		This signal is emitted when a menuitem updates or
		adds a property.
	*/
	signals[ID_PROP_UPDATE] =   g_signal_new(DBUSMENU_SERVER_SIGNAL_ID_PROP_UPDATE,
	                                         G_TYPE_FROM_CLASS(class),
	                                         G_SIGNAL_RUN_LAST,
	                                         G_STRUCT_OFFSET(DbusmenuServerClass, id_prop_update),
	                                         NULL, NULL,
	                                         _dbusmenu_server_marshal_VOID__INT_STRING_VARIANT,
	                                         G_TYPE_NONE, 3, G_TYPE_INT, G_TYPE_STRING, G_TYPE_VARIANT);
	/**
		DbusmenuServer::id-update:
		@arg0: The #DbusmenuServer emitting the signal.
		@arg1: ID of the #DbusmenuMenuitem changing.

		The purpose of this signal is to show major change in
		a menuitem to the point that #DbusmenuServer::id-prop-update
		seems a little insubstantive.
	*/
	signals[ID_UPDATE] =        g_signal_new(DBUSMENU_SERVER_SIGNAL_ID_UPDATE,
	                                         G_TYPE_FROM_CLASS(class),
	                                         G_SIGNAL_RUN_LAST,
	                                         G_STRUCT_OFFSET(DbusmenuServerClass, id_update),
	                                         NULL, NULL,
	                                         g_cclosure_marshal_VOID__INT,
	                                         G_TYPE_NONE, 1, G_TYPE_INT);
	/**
		DbusmenuServer::layout-updated:
		@arg0: The #DbusmenuServer emitting the signal.
		@arg1: A revision number representing which revision the update
		       represents itself as.
		@arg2: The ID of the parent for this update.

		This signal is emitted any time the layout of the
		menuitems under this server is changed.
	*/
	signals[LAYOUT_UPDATED] =   g_signal_new(DBUSMENU_SERVER_SIGNAL_LAYOUT_UPDATED,
	                                         G_TYPE_FROM_CLASS(class),
	                                         G_SIGNAL_RUN_LAST,
	                                         G_STRUCT_OFFSET(DbusmenuServerClass, layout_updated),
	                                         NULL, NULL,
	                                         _dbusmenu_server_marshal_VOID__UINT_INT,
	                                         G_TYPE_NONE, 2, G_TYPE_UINT, G_TYPE_INT);
	/**
		DbusmenuServer::item-activation-requested:
		@arg0: The #DbusmenuServer emitting the signal.
		@arg1: The ID of the parent for this update.
		@arg2: The timestamp of when the event happened

		This is signaled when a menuitem under this server
		sends it's activate signal.
	*/
	signals[ITEM_ACTIVATION] =  g_signal_new(DBUSMENU_SERVER_SIGNAL_ITEM_ACTIVATION,
	                                         G_TYPE_FROM_CLASS(class),
	                                         G_SIGNAL_RUN_LAST,
	                                         G_STRUCT_OFFSET(DbusmenuServerClass, item_activation),
	                                         NULL, NULL,
	                                         _dbusmenu_server_marshal_VOID__INT_UINT,
	                                         G_TYPE_NONE, 2, G_TYPE_INT, G_TYPE_UINT);


	g_object_class_install_property (object_class, PROP_DBUS_OBJECT,
	                                 g_param_spec_string(DBUSMENU_SERVER_PROP_DBUS_OBJECT, "DBus object path",
	                                              "The object that represents this set of menus on DBus",
	                                              "/com/canonical/dbusmenu",
	                                              G_PARAM_READWRITE | G_PARAM_CONSTRUCT_ONLY | G_PARAM_STATIC_STRINGS));
	g_object_class_install_property (object_class, PROP_ROOT_NODE,
	                                 g_param_spec_object(DBUSMENU_SERVER_PROP_ROOT_NODE, "Root menu node",
	                                              "The base object of the menus that are served",
	                                              DBUSMENU_TYPE_MENUITEM,
	                                              G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
	g_object_class_install_property (object_class, PROP_VERSION,
	                                 g_param_spec_uint(DBUSMENU_SERVER_PROP_VERSION, "Dbusmenu API version",
	                                              "The version of the DBusmenu API that we're implementing.",
	                                              DBUSMENU_VERSION_NUMBER, DBUSMENU_VERSION_NUMBER, DBUSMENU_VERSION_NUMBER,
	                                              G_PARAM_READABLE | G_PARAM_STATIC_STRINGS));
	g_object_class_install_property (object_class, PROP_TEXT_DIRECTION,
	                                 g_param_spec_enum(DBUSMENU_SERVER_PROP_TEXT_DIRECTION, "The default direction of text",
	                                              "The object that represents this set of menus on DBus",
	                                              DBUSMENU_TYPE_TEXT_DIRECTION, DBUSMENU_TEXT_DIRECTION_NONE,
	                                              G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));
	g_object_class_install_property (object_class, PROP_STATUS,
	                                 g_param_spec_enum(DBUSMENU_SERVER_PROP_STATUS, "Status of viewing the menus",
	                                              "Exports over DBus whether the menus should be given special visuals",
	                                              DBUSMENU_TYPE_STATUS, DBUSMENU_STATUS_NORMAL,
	                                              G_PARAM_READWRITE | G_PARAM_STATIC_STRINGS));

	if (dbusmenu_node_info == NULL) {
		GError * error = NULL;

		dbusmenu_node_info = g_dbus_node_info_new_for_xml(dbus_menu_clean_xml, &error);
		if (error != NULL) {
			g_error("Unable to parse DBusmenu Interface description: %s", error->message);
			g_error_free(error);
		}
	}

	if (dbusmenu_interface_info == NULL) {
		dbusmenu_interface_info = g_dbus_node_info_lookup_interface(dbusmenu_node_info, DBUSMENU_INTERFACE);

		if (dbusmenu_interface_info == NULL) {
			g_error("Unable to find interface '" DBUSMENU_INTERFACE "'");
		}
	}

	/* Building our Method table :( */
	dbusmenu_method_table[METHOD_GET_LAYOUT].interned_name = g_intern_static_string("GetLayout");
	dbusmenu_method_table[METHOD_GET_LAYOUT].func          = bus_get_layout;

	dbusmenu_method_table[METHOD_GET_GROUP_PROPERTIES].interned_name = g_intern_static_string("GetGroupProperties");
	dbusmenu_method_table[METHOD_GET_GROUP_PROPERTIES].func          = bus_get_group_properties;

	dbusmenu_method_table[METHOD_GET_CHILDREN].interned_name = g_intern_static_string("GetChildren");
	dbusmenu_method_table[METHOD_GET_CHILDREN].func          = bus_get_children;

	dbusmenu_method_table[METHOD_GET_PROPERTY].interned_name = g_intern_static_string("GetProperty");
	dbusmenu_method_table[METHOD_GET_PROPERTY].func          = bus_get_property;

	dbusmenu_method_table[METHOD_GET_PROPERTIES].interned_name = g_intern_static_string("GetProperties");
	dbusmenu_method_table[METHOD_GET_PROPERTIES].func          = bus_get_properties;

	dbusmenu_method_table[METHOD_EVENT].interned_name = g_intern_static_string("Event");
	dbusmenu_method_table[METHOD_EVENT].func          = bus_event;

	dbusmenu_method_table[METHOD_ABOUT_TO_SHOW].interned_name = g_intern_static_string("AboutToShow");
	dbusmenu_method_table[METHOD_ABOUT_TO_SHOW].func          = bus_about_to_show;

	return;
}

static void
dbusmenu_server_init (DbusmenuServer *self)
{
	self->priv = G_TYPE_INSTANCE_GET_PRIVATE ((self), DBUSMENU_TYPE_SERVER, DbusmenuServerPrivate);

	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(self);

	priv->root = NULL;
	priv->dbusobject = NULL;
	priv->layout_revision = 1;
	priv->layout_idle = 0;
	priv->bus = NULL;
	priv->bus_lookup = NULL;
	priv->dbus_registration = 0;

	default_text_direction(self);
	priv->status = DBUSMENU_STATUS_NORMAL;

	return;
}

static void
dbusmenu_server_dispose (GObject *object)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(object);

	if (priv->layout_idle != 0) {
		g_source_remove(priv->layout_idle);
		priv->layout_idle = 0;
	}
	
	if (priv->property_idle != 0) {
		g_source_remove(priv->property_idle);
		priv->property_idle = 0;
	}

	if (priv->prop_array != NULL) {
		prop_array_teardown(priv->prop_array);
		priv->prop_array = NULL;
	}

	if (priv->root != NULL) {
		dbusmenu_menuitem_foreach(priv->root, menuitem_signals_remove, object);
		g_object_unref(priv->root);
	}

	if (priv->dbus_registration != 0) {
		g_dbus_connection_unregister_object(priv->bus, priv->dbus_registration);
		priv->dbus_registration = 0;
	}

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

	if (priv->bus_lookup != NULL) {
		if (!g_cancellable_is_cancelled(priv->bus_lookup)) {
			/* Note, this may case the async function to run at
			   some point in the future.  That's okay, it'll get an
			   error, but just FYI */
			g_cancellable_cancel(priv->bus_lookup);
		}
		g_object_unref(priv->bus_lookup);
		priv->bus_lookup = NULL;
	}

	G_OBJECT_CLASS (dbusmenu_server_parent_class)->dispose (object);
	return;
}

static void
dbusmenu_server_finalize (GObject *object)
{
	G_OBJECT_CLASS (dbusmenu_server_parent_class)->finalize (object);
	return;
}

static void
set_property (GObject * obj, guint id, const GValue * value, GParamSpec * pspec)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(obj);

	switch (id) {
	case PROP_DBUS_OBJECT:
		g_return_if_fail(priv->dbusobject == NULL);
		priv->dbusobject = g_value_dup_string(value);

		if (priv->bus == NULL) {
			if (priv->bus_lookup == NULL) {
				priv->bus_lookup = g_cancellable_new();
				g_return_if_fail(priv->bus_lookup != NULL);
			}

			g_bus_get(G_BUS_TYPE_SESSION, priv->bus_lookup, bus_got_cb, obj);
		} else {
			register_object(DBUSMENU_SERVER(obj));
		}
		break;
	case PROP_ROOT_NODE:
		if (priv->root != NULL) {
			dbusmenu_menuitem_foreach(priv->root, menuitem_signals_remove, obj);
			dbusmenu_menuitem_set_root(priv->root, FALSE);

			GList * properties = dbusmenu_menuitem_properties_list(priv->root);
			GList * iter;
			for (iter = properties; iter != NULL; iter = g_list_next(iter)) {
				gchar * property = (gchar *)iter->data;
				menuitem_property_changed(priv->root, property, NULL, DBUSMENU_SERVER(obj));
			}
			g_list_free(properties);

			g_object_unref(G_OBJECT(priv->root));
			priv->root = NULL;
		}
		priv->root = DBUSMENU_MENUITEM(g_value_get_object(value));
		if (priv->root != NULL) {
			g_object_ref(G_OBJECT(priv->root));
			dbusmenu_menuitem_set_root(priv->root, TRUE);
			dbusmenu_menuitem_foreach(priv->root, menuitem_signals_create, obj);

			GList * properties = dbusmenu_menuitem_properties_list(priv->root);
			GList * iter;
			for (iter = properties; iter != NULL; iter = g_list_next(iter)) {
				gchar * property = (gchar *)iter->data;
				menuitem_property_changed(priv->root, property, dbusmenu_menuitem_property_get_variant(priv->root, property), DBUSMENU_SERVER(obj));
			}
			g_list_free(properties);
		} else {
			g_debug("Setting root node to NULL");
		}
		layout_update_signal(DBUSMENU_SERVER(obj));
		break;
	case PROP_TEXT_DIRECTION: {
		DbusmenuTextDirection indir = g_value_get_enum(value);
		DbusmenuTextDirection olddir = priv->text_direction;

		/* If being set to none we need to go back to default, otherwise
		   we'll set things the way that we've been told */
		if (indir == DBUSMENU_TEXT_DIRECTION_NONE) {
			default_text_direction(DBUSMENU_SERVER(obj));
		} else {
			priv->text_direction = indir;
		}

		/* If the value has changed we need to signal that on DBus */
		if (priv->text_direction != olddir && priv->bus != NULL && priv->dbusobject != NULL) {
			GVariantBuilder params;
			g_variant_builder_init(&params, G_VARIANT_TYPE_ARRAY);
			g_variant_builder_add_value(&params, g_variant_new_string(DBUSMENU_INTERFACE));
			GVariant * dict = g_variant_new_dict_entry(g_variant_new_string("text-direction"), g_variant_new_string(dbusmenu_text_direction_get_nick(priv->text_direction)));
			g_variant_builder_add_value(&params, g_variant_new_array(NULL, &dict, 1));
			g_variant_builder_add_value(&params, g_variant_new_array(G_VARIANT_TYPE_STRING, NULL, 0));
			GVariant * vparams = g_variant_builder_end(&params);

			g_dbus_connection_emit_signal(priv->bus,
			                              NULL,
			                              priv->dbusobject,
			                              "org.freedesktop.DBus.Properties",
			                              "PropertiesChanged",
			                              vparams,
			                              NULL);
		}

		break;
	}
	case PROP_STATUS: {
		DbusmenuStatus instatus = g_value_get_enum(value);

		/* If the value has changed we need to signal that on DBus */
		if (priv->status != instatus && priv->bus != NULL && priv->dbusobject != NULL) {
			GVariantBuilder params;
			g_variant_builder_init(&params, G_VARIANT_TYPE_ARRAY);
			g_variant_builder_add_value(&params, g_variant_new_string(DBUSMENU_INTERFACE));
			GVariant * dict = g_variant_new_dict_entry(g_variant_new_string("status"), g_variant_new_string(dbusmenu_status_get_nick(instatus)));
			g_variant_builder_add_value(&params, g_variant_new_array(NULL, &dict, 1));
			g_variant_builder_add_value(&params, g_variant_new_array(G_VARIANT_TYPE_STRING, NULL, 0));
			GVariant * vparams = g_variant_builder_end(&params);

			g_dbus_connection_emit_signal(priv->bus,
			                              NULL,
			                              priv->dbusobject,
			                              "org.freedesktop.DBus.Properties",
			                              "PropertiesChanged",
			                              vparams,
			                              NULL);
		}

		priv->status = instatus;
		break;
	}
	default:
		g_return_if_reached();
		break;
	}

	return;
}

static void
get_property (GObject * obj, guint id, GValue * value, GParamSpec * pspec)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(obj);

	switch (id) {
	case PROP_DBUS_OBJECT:
		g_value_set_string(value, priv->dbusobject);
		break;
	case PROP_ROOT_NODE:
		g_value_set_object(value, priv->root);
		break;
	case PROP_VERSION:
		g_value_set_uint(value, DBUSMENU_VERSION_NUMBER);
		break;
	case PROP_TEXT_DIRECTION:
		g_value_set_enum(value, priv->text_direction);
		break;
	case PROP_STATUS:
		g_value_set_enum(value, priv->status);
		break;
	default:
		g_return_if_reached();
		break;
	}

	return;
}

/* Determines the default text direction */
static void
default_text_direction (DbusmenuServer * server)
{
	DbusmenuTextDirection dir = DBUSMENU_TEXT_DIRECTION_NONE;
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	const gchar * env = g_getenv("DBUSMENU_TEXT_DIRECTION");
	if (env != NULL) {
		if (g_strcmp0(env, "ltr") == 0) {
			dir = DBUSMENU_TEXT_DIRECTION_LTR;
		} else if (g_strcmp0(env, "rtl") == 0) {
			dir = DBUSMENU_TEXT_DIRECTION_RTL;
		} else {
			g_warning("Value of 'DBUSMENU_TEXT_DIRECTION' is '%s' which is not one of 'rtl' or 'ltr'", env);
		}
	}

	if (dir == DBUSMENU_TEXT_DIRECTION_NONE) {
		/* TRANSLATORS: This is the direction of the text and can
		   either be the value 'ltr' for left-to-right text (English)
		   or 'rtl' for right-to-left (Arabic). */
		const gchar * default_dir = C_("default text direction", "ltr");

		if (g_strcmp0(default_dir, "ltr") == 0) {
			dir = DBUSMENU_TEXT_DIRECTION_LTR;
		} else if (g_strcmp0(default_dir, "rtl") == 0) {
			dir = DBUSMENU_TEXT_DIRECTION_RTL;
		} else {
			g_warning("Translation has an invalid value '%s' for default text direction.  Defaulting to left-to-right.", default_dir);
			dir = DBUSMENU_TEXT_DIRECTION_LTR;
		}
	}

	/* Shouldn't happen, but incase future patches make a mistake
	   this'll catch them */
	g_return_if_fail(dir != DBUSMENU_TEXT_DIRECTION_NONE);

	priv->text_direction = dir;

	return;
}

/* Register the object on the dbus bus */
static void
register_object (DbusmenuServer * server)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	/* Object info */
	g_return_if_fail(priv->bus != NULL);
	g_return_if_fail(priv->dbusobject != NULL);

	/* Class info */
	g_return_if_fail(dbusmenu_node_info != NULL);
	g_return_if_fail(dbusmenu_interface_info != NULL);

	/* We might block on this in the future, but it'd be nice if
	   we could change the object path.  Thinking about it... */
	if (priv->dbus_registration != 0) {
		g_dbus_connection_unregister_object(priv->bus, priv->dbus_registration);
		priv->dbus_registration = 0;
	}

	GError * error = NULL;
	priv->dbus_registration = g_dbus_connection_register_object(priv->bus,
	                                                            priv->dbusobject,
	                                                            dbusmenu_interface_info,
	                                                            &dbusmenu_interface_table,
	                                                            server,
	                                                            NULL,
	                                                            &error);

	if (error != NULL) {
		g_warning("Unable to register object on bus: %s", error->message);
		g_error_free(error);
		return;
	}

	/* If we've got it registered let's tell everyone about it */
	g_signal_emit(G_OBJECT(server), signals[LAYOUT_UPDATED], 0, priv->layout_revision, 0, TRUE);
	if (priv->dbusobject != NULL && priv->bus != NULL) {
		g_dbus_connection_emit_signal(priv->bus,
		                              NULL,
		                              priv->dbusobject,
		                              DBUSMENU_INTERFACE,
		                              "LayoutUpdated",
		                              g_variant_new("(ui)", priv->layout_revision, 0),
		                              NULL);
	}

	return;
}

/* Callback from asking GIO to get us the session bus */
static void
bus_got_cb (GObject * obj, GAsyncResult * result, gpointer user_data)
{
	GError * error = NULL;

	GDBusConnection * bus = g_bus_get_finish(result, &error);

	if (error != NULL) {
		g_warning("Unable to get session bus: %s", error->message);
		g_error_free(error);
		return;
	}

	/* Note: We're not using the user_data before we check for
	   the error so that in the cancelled case at destruction of
	   the object we don't end up with an invalid object. */

	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(user_data);
	priv->bus = bus;

	register_object(DBUSMENU_SERVER(user_data));

	return;
}

/* Function for the GDBus vtable to handle all method calls and dish
   them out the appropriate functions */
static void
bus_method_call (GDBusConnection * connection, const gchar * sender, const gchar * path, const gchar * interface, const gchar * method, GVariant * params, GDBusMethodInvocation * invocation, gpointer user_data)
{
	int i;
	const gchar * interned_method = g_intern_string(method);

	for (i = 0; i < METHOD_COUNT; i++) {
		if (dbusmenu_method_table[i].interned_name == interned_method) {
			if (dbusmenu_method_table[i].func != NULL) {
				return dbusmenu_method_table[i].func(DBUSMENU_SERVER(user_data), params, invocation);
			} else {
				/* If we have a null function we're responding but nothing else. */
				g_warning("Invalid function call for '%s' with parameters: %s", method, g_variant_print(params, TRUE));
				g_dbus_method_invocation_return_value(invocation, NULL);
				return;
			}
		}
	}

	/* We're here because there's an error */
	g_dbus_method_invocation_return_error(invocation,
	                                      error_quark(),
	                                      NOT_IMPLEMENTED,
	                                      "Unable to find method '%s'",
	                                      method);
	return;
}

/* For the GDBus vtable but we only have one property so it's pretty
   simple. */
static GVariant *
bus_get_prop (GDBusConnection * connection, const gchar * sender, const gchar * path, const gchar * interface, const gchar * property, GError ** error, gpointer user_data)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(user_data);

	/* None of these should happen */
	g_return_val_if_fail(g_strcmp0(interface, DBUSMENU_INTERFACE) == 0, NULL);
	g_return_val_if_fail(g_strcmp0(path, priv->dbusobject) == 0, NULL);

	if (g_strcmp0(property, "version") == 0) {
		return g_variant_new_uint32(DBUSMENU_VERSION_NUMBER);
	} else if (g_strcmp0(property, "text-direction") == 0) {
		return g_variant_new_string(dbusmenu_text_direction_get_nick(priv->text_direction));
	} else {
		g_warning("Unknown property '%s'", property);
	}

	return NULL;
}

/* Handle actually signalling in the idle loop.  This way we collect all
   the updates. */
static gboolean
layout_update_idle (gpointer user_data)
{
	DbusmenuServer * server = DBUSMENU_SERVER(user_data);
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	g_signal_emit(G_OBJECT(server), signals[LAYOUT_UPDATED], 0, priv->layout_revision, 0, TRUE);
	if (priv->dbusobject != NULL && priv->bus != NULL) {
		g_dbus_connection_emit_signal(priv->bus,
		                              NULL,
		                              priv->dbusobject,
		                              DBUSMENU_INTERFACE,
		                              "LayoutUpdated",
		                              g_variant_new("(ui)", priv->layout_revision, 0),
		                              NULL);
	}

	priv->layout_idle = 0;

	return FALSE;
}

/* Signals that the layout has been updated */
static void
layout_update_signal (DbusmenuServer * server)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);
	priv->layout_revision++;

	if (priv->layout_idle == 0) {
		priv->layout_idle = g_idle_add(layout_update_idle, server);
	}

	return;
}

typedef struct _prop_idle_item_t prop_idle_item_t;
struct _prop_idle_item_t {
	gint id;
	GArray * array;
};

typedef struct _prop_idle_prop_t prop_idle_prop_t;
struct _prop_idle_prop_t {
	gchar * property;
	GVariant * variant;
};

/* Takes appart our data structure so we don't leak any
   memory or references. */
static void
prop_array_teardown (GArray * prop_array)
{
	int i, j;

	for (i = 0; i < prop_array->len; i++) {
		prop_idle_item_t * iitem = &g_array_index(prop_array, prop_idle_item_t, i);
		
		for (j = 0; j < iitem->array->len; j++) {
			prop_idle_prop_t * iprop = &g_array_index(iitem->array, prop_idle_prop_t, j);

			g_free(iprop->property);

			if (iprop->variant != NULL) {
				g_variant_unref(iprop->variant);
			}
		}

		g_array_free(iitem->array, TRUE);
	}

	g_array_free(prop_array, TRUE);

	return;
}

/* Works in the idle to send a set of property updates so that they'll
   all update in a single dbus message. */
static gboolean
menuitem_property_idle (gpointer user_data)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(user_data);

	/* Source will get removed as we return */
	priv->property_idle = 0;

	/* If there are no items, let's just not signal */
	if (priv->prop_array == NULL) {
		return FALSE;
	}

	int i, j;
	GVariantBuilder itembuilder;
	gboolean item_init = FALSE;

	GVariantBuilder removeitembuilder;
	gboolean removeitem_init = FALSE;

	for (i = 0; i < priv->prop_array->len; i++) {
		prop_idle_item_t * iitem = &g_array_index(priv->prop_array, prop_idle_item_t, i);

		GVariantBuilder dictbuilder;
		gboolean dictinit = FALSE;

		GVariantBuilder removedictbuilder;
		gboolean removedictinit = FALSE;
		
		/* Go throught each item and see if it should go in the removal list
		   or the additive list. */
		for (j = 0; j < iitem->array->len; j++) {
			prop_idle_prop_t * iprop = &g_array_index(iitem->array, prop_idle_prop_t, j);

			if (iprop->variant != NULL) {
				if (!dictinit) {
					g_variant_builder_init(&dictbuilder, G_VARIANT_TYPE_DICTIONARY);
					dictinit = TRUE;
				}

				GVariant * entry = g_variant_new_dict_entry(g_variant_new_string(iprop->property),
				                                            g_variant_new_variant(iprop->variant));

				g_variant_builder_add_value(&dictbuilder, entry);
			} else {
				if (!removedictinit) {
					g_variant_builder_init(&removedictbuilder, G_VARIANT_TYPE_ARRAY);
					removedictinit = TRUE;
				}

				g_variant_builder_add_value(&removedictbuilder, g_variant_new_string(iprop->property));
			}
		}

		/* If we've got new values that are real values we need to add that
		   to the list of items to send the value of */
		if (dictinit) {
			GVariantBuilder tuplebuilder;
			g_variant_builder_init(&tuplebuilder, G_VARIANT_TYPE_TUPLE);

			g_variant_builder_add_value(&tuplebuilder, g_variant_new_int32(iitem->id));
			g_variant_builder_add_value(&tuplebuilder, g_variant_builder_end(&dictbuilder));

			if (!item_init) {
				g_variant_builder_init(&itembuilder, G_VARIANT_TYPE_ARRAY);
				item_init = TRUE;
			}

			g_variant_builder_add_value(&itembuilder, g_variant_builder_end(&tuplebuilder));
		}

		/* If we've got properties that have been removed then we need to add
		   them to the list of removed items */
		if (removedictinit) {
			GVariantBuilder tuplebuilder;
			g_variant_builder_init(&tuplebuilder, G_VARIANT_TYPE_TUPLE);

			g_variant_builder_add_value(&tuplebuilder, g_variant_new_int32(iitem->id));
			g_variant_builder_add_value(&tuplebuilder, g_variant_builder_end(&removedictbuilder));

			if (!removeitem_init) {
				g_variant_builder_init(&removeitembuilder, G_VARIANT_TYPE_ARRAY);
				removeitem_init = TRUE;
			}

			g_variant_builder_add_value(&removeitembuilder, g_variant_builder_end(&tuplebuilder));
		}
	}

	GVariant * megadata[2];

	if (item_init) {
		megadata[0] = g_variant_builder_end(&itembuilder);
	} else {
		GError * error = NULL;
		megadata[0] = g_variant_parse(G_VARIANT_TYPE("a(ia{sv})"), "[ ]", NULL, NULL, &error);

		if (error != NULL) {
			g_warning("Unable to parse '[ ]' as a 'a(ia{sv})': %s", error->message);
			g_error_free(error);
		}
	}

	if (removeitem_init) {
		megadata[1] = g_variant_builder_end(&removeitembuilder);
	} else {
		GError * error = NULL;
		megadata[1] = g_variant_parse(G_VARIANT_TYPE("a(ia(s))"), "[ ]", NULL, NULL, &error);

		if (error != NULL) {
			g_warning("Unable to parse '[ ]' as a 'a(ia(s))': %s", error->message);
			g_error_free(error);
		}
	}

	if (priv->dbusobject != NULL && priv->bus != NULL) {
		g_dbus_connection_emit_signal(priv->bus,
		                              NULL,
		                              priv->dbusobject,
		                              DBUSMENU_INTERFACE,
		                              "ItemPropertiesUpdated",
		                              g_variant_new_tuple(megadata, 2),
		                              NULL);
	} else {
		g_variant_unref(megadata[0]);
		g_variant_unref(megadata[1]);
	}

	/* Clean everything up */
	prop_array_teardown(priv->prop_array);
	priv->prop_array = NULL;

	return FALSE;
}

static void 
menuitem_property_changed (DbusmenuMenuitem * mi, gchar * property, GVariant * variant, DbusmenuServer * server)
{
	int i;
	gint item_id;

	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	item_id = dbusmenu_menuitem_get_id(mi);

	g_signal_emit(G_OBJECT(server), signals[ID_PROP_UPDATE], 0, item_id, property, variant, TRUE);

	/* See if we have a property array, if not, we need to
	   build one of these suckers */
	if (priv->prop_array == NULL) {
		priv->prop_array = g_array_new(FALSE, FALSE, sizeof(prop_idle_item_t));
	}

	/* Look to see if we already have this item in the list
	   and use it if so */
	prop_idle_item_t * item = NULL;
	for (i = 0; i < priv->prop_array->len; i++) {
		prop_idle_item_t * iitem = &g_array_index(priv->prop_array, prop_idle_item_t, i);
		if (iitem->id == item_id) {
			item = iitem;
			break;
		}
	}

	GArray * properties = NULL;
	/* If not, we'll need to build ourselves one */
	if (item == NULL) {
		prop_idle_item_t myitem;
		myitem.id = item_id;
		myitem.array = g_array_new(FALSE, FALSE, sizeof(prop_idle_prop_t));

		g_array_append_val(priv->prop_array, myitem);
		properties = myitem.array;
	} else {
		properties = item->array;
	}

	/* Check to see if this property is in the list */
	prop_idle_prop_t * prop = NULL;
	for (i = 0; i < properties->len; i++) {
		prop_idle_prop_t * iprop = &g_array_index(properties, prop_idle_prop_t, i);
		if (g_strcmp0(iprop->property, property) == 0) {
			prop = iprop;
			break;
		}
	}

	/* If it's the default value we want to treat it like a clearing
	   of the value so that it doesn't get sent over dbus and waste
	   bandwidth */
	if (dbusmenu_menuitem_property_is_default(mi, property)) {
		variant = NULL;
	}

	/* If so, we need to swap the value */
	if (prop != NULL) {
		g_variant_unref(prop->variant);
		prop->variant = variant;
	} else {
	/* else we need to add it */
		prop_idle_prop_t myprop;
		myprop.property = g_strdup(property);
		myprop.variant = variant;

		g_array_append_val(properties, myprop);
	}
	if (variant != NULL) {
		g_variant_ref_sink(variant);
	}

	/* Check to see if the idle is already queued, and queue it
	   if not. */
	if (priv->property_idle == 0) {
		priv->property_idle = g_idle_add(menuitem_property_idle, server);
	}

	return;
}

/* Adds the signals for this entry to the list and looks at
   the children of this entry to add the signals we need
   as well.  We like signals. */
static void
added_check_children (gpointer data, gpointer user_data)
{
	DbusmenuMenuitem * mi = (DbusmenuMenuitem *)data;
	DbusmenuServer * server = (DbusmenuServer *)user_data;

	menuitem_signals_create(mi, server);
	g_list_foreach(dbusmenu_menuitem_get_children(mi), added_check_children, server);

	return;
}

/* Callback for when a child is added.  We need to connect everything
   up and signal that the layout has changed. */
static void
menuitem_child_added (DbusmenuMenuitem * parent, DbusmenuMenuitem * child, guint pos, DbusmenuServer * server)
{
	menuitem_signals_create(child, server);
	g_list_foreach(dbusmenu_menuitem_get_children(child), added_check_children, server);

	layout_update_signal(server);
	return;
}

static void 
menuitem_child_removed (DbusmenuMenuitem * parent, DbusmenuMenuitem * child, DbusmenuServer * server)
{
	menuitem_signals_remove(child, server);
	layout_update_signal(server);
	return;
}

static void 
menuitem_child_moved (DbusmenuMenuitem * parent, DbusmenuMenuitem * child, guint newpos, guint oldpos, DbusmenuServer * server)
{
	layout_update_signal(server);
	return;
}

/* Called when a menu item emits its activated signal so it
   gets passed across the bus. */
static void 
menuitem_shown (DbusmenuMenuitem * mi, guint timestamp, DbusmenuServer * server)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	g_signal_emit(G_OBJECT(server), signals[ITEM_ACTIVATION], 0, dbusmenu_menuitem_get_id(mi), timestamp, TRUE);

	if (priv->dbusobject != NULL && priv->bus != NULL) {
		g_dbus_connection_emit_signal(priv->bus,
		                              NULL,
		                              priv->dbusobject,
		                              DBUSMENU_INTERFACE,
		                              "ItemActivationRequested",
		                              g_variant_new("(iu)", dbusmenu_menuitem_get_id(mi), timestamp),
		                              NULL);
	}

	return;
}

/* Connects all the signals that we're interested in
   coming from a menuitem */
static void
menuitem_signals_create (DbusmenuMenuitem * mi, gpointer data)
{
	g_signal_connect(G_OBJECT(mi), DBUSMENU_MENUITEM_SIGNAL_CHILD_ADDED, G_CALLBACK(menuitem_child_added), data);
	g_signal_connect(G_OBJECT(mi), DBUSMENU_MENUITEM_SIGNAL_CHILD_REMOVED, G_CALLBACK(menuitem_child_removed), data);
	g_signal_connect(G_OBJECT(mi), DBUSMENU_MENUITEM_SIGNAL_CHILD_MOVED, G_CALLBACK(menuitem_child_moved), data);
	g_signal_connect(G_OBJECT(mi), DBUSMENU_MENUITEM_SIGNAL_PROPERTY_CHANGED, G_CALLBACK(menuitem_property_changed), data);
	g_signal_connect(G_OBJECT(mi), DBUSMENU_MENUITEM_SIGNAL_SHOW_TO_USER, G_CALLBACK(menuitem_shown), data);
	return;
}

/* Removes all the signals that we're interested in
   coming from a menuitem */
static void
menuitem_signals_remove (DbusmenuMenuitem * mi, gpointer data)
{
	g_signal_handlers_disconnect_by_func(G_OBJECT(mi), G_CALLBACK(menuitem_child_added), data);
	g_signal_handlers_disconnect_by_func(G_OBJECT(mi), G_CALLBACK(menuitem_child_removed), data);
	g_signal_handlers_disconnect_by_func(G_OBJECT(mi), G_CALLBACK(menuitem_child_moved), data);
	g_signal_handlers_disconnect_by_func(G_OBJECT(mi), G_CALLBACK(menuitem_property_changed), data);
	return;
}

static GQuark
error_quark (void)
{
	static GQuark quark = 0;
	if (quark == 0) {
		quark = g_quark_from_static_string (G_LOG_DOMAIN);
	}
	return quark;
}

/* DBus interface */
static void
bus_get_layout (DbusmenuServer * server, GVariant * params, GDBusMethodInvocation * invocation)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	/* Input */
	gint parent = g_variant_get_int32(g_variant_get_child_value(params, 0));
	gint recurse = g_variant_get_int32(g_variant_get_child_value(params, 1));
	const gchar ** props = g_variant_get_strv(g_variant_get_child_value(params, 2), NULL);

	/* Output */
	guint revision = priv->layout_revision;
	GVariant * items = NULL;

	if (priv->root != NULL) {
		items = dbusmenu_menuitem_build_variant(priv->root, props, recurse);
	}

	/* What happens if we don't have anything? */
	if (items == NULL) {
		if (parent == 0) {
			/* We should always have a root, so we'll make up one for
			   right now. */
			items = g_variant_parse(G_VARIANT_TYPE("(ia{sv}av)"), "(0, [], [])", NULL, NULL, NULL);
		} else {
			/* If we were looking for a specific ID that's an error that
			   we should send back, so let's do that. */
			g_dbus_method_invocation_return_error(invocation,
				                                  error_quark(),
				                                  INVALID_MENUITEM_ID,
				                                  "The ID supplied %d does not refer to a menu item we have",
				                                  parent);
			return;
		}
	}

	/* Build the final variant tuple */
	GVariantBuilder tuplebuilder;
	g_variant_builder_init(&tuplebuilder, G_VARIANT_TYPE_TUPLE);

	g_variant_builder_add_value(&tuplebuilder, g_variant_new_uint32(revision));
	g_variant_builder_add_value(&tuplebuilder, items);

	GVariant * retval = g_variant_builder_end(&tuplebuilder);
	// g_debug("Sending layout type: %s", g_variant_get_type_string(retval));
	g_dbus_method_invocation_return_value(invocation,
	                                      retval);
	return;
}

/* Get a single property off of a single menuitem */
static void
bus_get_property (DbusmenuServer * server, GVariant * params, GDBusMethodInvocation * invocation)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	if (priv->root == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            NO_VALID_LAYOUT,
			            "There currently isn't a layout in this server");
		return;
	}
	
	gint id = g_variant_get_int32(g_variant_get_child_value(params, 0));
	const gchar * property = g_variant_get_string(g_variant_get_child_value(params, 1), NULL);

	DbusmenuMenuitem * mi = dbusmenu_menuitem_find_id(priv->root, id);

	if (mi == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            INVALID_MENUITEM_ID,
			            "The ID supplied %d does not refer to a menu item we have",
			            id);
		return;
	}

	GVariant * variant = dbusmenu_menuitem_property_get_variant(mi, property);
	if (variant == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            INVALID_PROPERTY_NAME,
			            "The property '%s' does not exist on menuitem with ID of %d",
			            property,
			            id);
		return;
	}

	g_dbus_method_invocation_return_value(invocation, g_variant_new("(v)", variant));
	return;
}

/* Get some properties off of a single menuitem */
static void
bus_get_properties (DbusmenuServer * server, GVariant * params, GDBusMethodInvocation * invocation)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);
	
	if (priv->root == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            NO_VALID_LAYOUT,
			            "There currently isn't a layout in this server");
		return;
	}

	gint id = g_variant_get_int32(g_variant_get_child_value(params, 0));

	DbusmenuMenuitem * mi = dbusmenu_menuitem_find_id(priv->root, id);

	if (mi == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            INVALID_MENUITEM_ID,
			            "The ID supplied %d does not refer to a menu item we have",
			            id);
		return;
	}

	GVariant * dict = dbusmenu_menuitem_properties_variant(mi, NULL);

	g_dbus_method_invocation_return_value(invocation, g_variant_new("(a{sv})", dict));

	return;
}

/* Handles getting a bunch of properties from a variety of menu items
   to make one mega dbus message */
static void
bus_get_group_properties (DbusmenuServer * server, GVariant * params, GDBusMethodInvocation * invocation)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	if (priv->root == NULL) {
		GVariant * idlist = g_variant_get_child_value(params, 0);
		if (g_variant_n_children(idlist) == 1 && g_variant_get_int32(g_variant_get_child_value(idlist, 0)) == 0) {
			GVariant * final = g_variant_parse(g_variant_type_new("(a(ia{sv}))"), "([(0, {})],)", NULL, NULL, NULL);
			g_dbus_method_invocation_return_value(invocation, final);
			return;
		}

		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            NO_VALID_LAYOUT,
			            "There currently isn't a layout in this server");
		return;
	}

	GVariantIter ids;
	g_variant_iter_init(&ids, g_variant_get_child_value(params, 0));

	GVariantBuilder builder;
	gboolean builder_init = FALSE;

	gint id;
	while (g_variant_iter_next(&ids, "i", &id)) {
		DbusmenuMenuitem * mi = dbusmenu_menuitem_find_id(priv->root, id);
		if (mi == NULL) continue;

		if (!builder_init) {
			g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY);
			builder_init = TRUE;
		}

		GVariantBuilder wbuilder;
		g_variant_builder_init(&wbuilder, G_VARIANT_TYPE_TUPLE);
		g_variant_builder_add(&wbuilder, "i", id);
		GVariant * props = dbusmenu_menuitem_properties_variant(mi, NULL);

		if (props == NULL) {
			GError * error = NULL;
			props = g_variant_parse(g_variant_type_new("a{sv}"), "{}", NULL, NULL, &error);
			if (error != NULL) {
				g_warning("Unable to parse '{}' as a 'a{sv}': %s", error->message);
				g_error_free(error);
				props = NULL;
			}
		}

		g_variant_builder_add_value(&wbuilder, props);
		GVariant * mi_data = g_variant_builder_end(&wbuilder);

		g_variant_builder_add_value(&builder, mi_data);
	}

	GVariant * ret = NULL;
	
	if (builder_init) {
		ret = g_variant_builder_end(&builder);
	} else {
		GError * error = NULL;
		ret = g_variant_parse(g_variant_type_new("a(ia{sv})"), "[]", NULL, NULL, NULL);
		if (error != NULL) {
			g_warning("Unable to parse '[]' as a 'a(ia{sv})': %s", error->message);
			g_error_free(error);
			ret = NULL;
		}
	}

	GVariant * final = NULL;
	if (ret != NULL) {
		g_variant_builder_init(&builder, G_VARIANT_TYPE_TUPLE);
		g_variant_builder_add_value(&builder, ret);
		final = g_variant_builder_end(&builder);
	} else {
		g_warning("Error building property list, final variant is NULL");
	}

	g_dbus_method_invocation_return_value(invocation, final);

	return;
}

/* Turn a menuitem into an variant and attach it to the
   VariantBuilder we passed in */
static void
serialize_menuitem(gpointer data, gpointer user_data)
{
	DbusmenuMenuitem * mi = DBUSMENU_MENUITEM(data);
	GVariantBuilder * builder = (GVariantBuilder *)(user_data);
	GVariantBuilder tuple;
	
	g_variant_builder_init(&tuple, G_VARIANT_TYPE_TUPLE);

	gint id = dbusmenu_menuitem_get_id(mi);
	g_variant_builder_add_value(&tuple, g_variant_new_int32(id));

	GVariant * props = dbusmenu_menuitem_properties_variant(mi, NULL);
	g_variant_builder_add_value(&tuple, props);

	g_variant_builder_add_value(builder, g_variant_builder_end(&tuple));

	return;
}

/* Gets the children and their properties of the ID that is
   passed into the function */
static void
bus_get_children (DbusmenuServer * server, GVariant * params, GDBusMethodInvocation * invocation)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);
	gint id = g_variant_get_int32(g_variant_get_child_value(params, 0));

	if (priv->root == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            NO_VALID_LAYOUT,
			            "There currently isn't a layout in this server");
		return;
	}

	DbusmenuMenuitem * mi = dbusmenu_menuitem_find_id(priv->root, id);

	if (mi == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			                                  error_quark(),
			                                  INVALID_MENUITEM_ID,
			                                  "The ID supplied %d does not refer to a menu item we have",
			                                  id);
		return;
	}

	GList * children = dbusmenu_menuitem_get_children(mi);
	GVariant * ret = NULL;

	if (children != NULL) {
		GVariantBuilder builder;
		g_variant_builder_init(&builder, G_VARIANT_TYPE_ARRAY); 

		g_list_foreach(children, serialize_menuitem, &builder);

		GVariant * end = g_variant_builder_end(&builder);
		ret = g_variant_new_tuple(&end, 1);
	} else {
		GError * error = NULL;
		ret = g_variant_parse(g_variant_type_new("(a(ia{sv}))"), "([(0, {})],)", NULL, NULL, &error);
		if (error != NULL) {
			g_warning("Unable to parse '([(0, {})],)' as a '(a(ia{sv}))': %s", error->message);
			g_error_free(error);
			ret = NULL;
		}
	}

	g_dbus_method_invocation_return_value(invocation, ret);
	return;
}

/* Structure for holding the event data for the idle function
   to pick it up. */
typedef struct _idle_event_t idle_event_t;
struct _idle_event_t {
	DbusmenuMenuitem * mi;
	gchar * eventid;
	GVariant * variant;
	guint timestamp;
};

/* A handler for else where in the main loop so that the dbusmenu
   event response doesn't get blocked */
static gboolean
event_local_handler (gpointer user_data)
{
	idle_event_t * data = (idle_event_t *)user_data;

	dbusmenu_menuitem_handle_event(data->mi, data->eventid, data->variant, data->timestamp);

	g_object_unref(data->mi);
	g_free(data->eventid);
	g_variant_unref(data->variant);
	g_free(data);
	return FALSE;
}

/* Handles the events coming off of DBus */
static void
bus_event (DbusmenuServer * server, GVariant * params, GDBusMethodInvocation * invocation)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	if (priv->root == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            NO_VALID_LAYOUT,
			            "There currently isn't a layout in this server");
		return;
	}

	gint id = g_variant_get_int32(g_variant_get_child_value(params, 0));
	DbusmenuMenuitem * mi = dbusmenu_menuitem_find_id(priv->root, id);

	if (mi == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			                                  error_quark(),
			                                  INVALID_MENUITEM_ID,
			                                  "The ID supplied %d does not refer to a menu item we have",
			                                  id);
		return;
	}

	idle_event_t * event_data = g_new0(idle_event_t, 1);
	event_data->mi = mi;
	g_object_ref(event_data->mi);
	event_data->eventid = g_strdup(g_variant_get_string(g_variant_get_child_value(params, 1), NULL));
	event_data->timestamp = g_variant_get_uint32(g_variant_get_child_value(params, 3));
	event_data->variant = g_variant_get_child_value(params, 2);

	if (g_variant_is_of_type(event_data->variant, G_VARIANT_TYPE_VARIANT)) {
		event_data->variant = g_variant_get_variant(event_data->variant);
	}

	g_variant_ref_sink(event_data->variant);

	g_timeout_add(0, event_local_handler, event_data);

	g_dbus_method_invocation_return_value(invocation, NULL);
	return;
}

/* Recieve the About To Show function.  Pass it to our menu item. */
static void
bus_about_to_show (DbusmenuServer * server, GVariant * params, GDBusMethodInvocation * invocation)
{
	DbusmenuServerPrivate * priv = DBUSMENU_SERVER_GET_PRIVATE(server);

	if (priv->root == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			            error_quark(),
			            NO_VALID_LAYOUT,
			            "There currently isn't a layout in this server");
		return;
	}

	gint id = g_variant_get_int32(g_variant_get_child_value(params, 0));
	DbusmenuMenuitem * mi = dbusmenu_menuitem_find_id(priv->root, id);

	if (mi == NULL) {
		g_dbus_method_invocation_return_error(invocation,
			                                  error_quark(),
			                                  INVALID_MENUITEM_ID,
			                                  "The ID supplied %d does not refer to a menu item we have",
			                                  id);
		return;
	}

	dbusmenu_menuitem_send_about_to_show(mi, NULL, NULL);

	/* GTK+ does not support about-to-show concept for now */
	g_dbus_method_invocation_return_value(invocation,
	                                      g_variant_new("(b)", FALSE));
	return;
}

/* Public Interface */
/**
	dbusmenu_server_new:
	@object: The object name to show for this menu structure
		on DBus.  May be NULL.

	Creates a new #DbusmenuServer object with a specific object
	path on DBus.  If @object is set to NULL the default object
	name of "/com/canonical/dbusmenu" will be used.

	Return value: A brand new #DbusmenuServer
*/
DbusmenuServer *
dbusmenu_server_new (const gchar * object)
{
	if (object == NULL) {
		object = "/com/canonical/dbusmenu";
	}

	DbusmenuServer * self = g_object_new(DBUSMENU_TYPE_SERVER,
	                                     DBUSMENU_SERVER_PROP_DBUS_OBJECT, object,
	                                     NULL);

	return self;
}

/**
	dbusmenu_server_set_root:
	@self: The #DbusmenuServer object to set the root on
	@root: The new root #DbusmenuMenuitem tree

	This function contains all of the #GValue wrapping
	required to set the property #DbusmenuServer:root-node
	on the server @self.
*/
void
dbusmenu_server_set_root (DbusmenuServer * self, DbusmenuMenuitem * root)
{
	g_return_if_fail(DBUSMENU_IS_SERVER(self));
	g_return_if_fail(DBUSMENU_IS_MENUITEM(root));

	/* g_debug("Setting root object: 0x%X", (unsigned int)root); */
	GValue rootvalue = {0};
	g_value_init(&rootvalue, G_TYPE_OBJECT);
	g_value_set_object(&rootvalue, root);
	g_object_set_property(G_OBJECT(self), DBUSMENU_SERVER_PROP_ROOT_NODE, &rootvalue);
	g_object_unref(G_OBJECT(root));
	return;
}

/**
	dbusmenu_server_get_text_direction:
	@server: The #DbusmenuServer object to get the text direction from

	Returns the value of the text direction that is being exported
	over DBus for this server.  It should relate to the direction
	of the labels and other text fields that are being exported by
	this server.

	Return value: Text direction exported for this server.
*/
DbusmenuTextDirection
dbusmenu_server_get_text_direction (DbusmenuServer * server)
{
	g_return_val_if_fail(DBUSMENU_IS_SERVER(server), DBUSMENU_TEXT_DIRECTION_NONE);

	GValue val = {0};
	g_value_init(&val, DBUSMENU_TYPE_TEXT_DIRECTION);
	g_object_get_property(G_OBJECT(server), DBUSMENU_SERVER_PROP_TEXT_DIRECTION, &val);

	DbusmenuTextDirection retval = g_value_get_enum(&val);
	g_value_unset(&val);

	return retval;
}

/**
	dbusmenu_server_set_text_direction:
	@server: The #DbusmenuServer object to set the text direction on

	Sets the text direction that should be exported over DBus for
	this server.  If the value is set to #DBUSMENU_TEXT_DIRECTION_NONE
	the default detection will be used for setting the value and
	exported over DBus.
*/
void
dbusmenu_server_set_text_direction (DbusmenuServer * server, DbusmenuTextDirection dir)
{
	g_return_if_fail(DBUSMENU_IS_SERVER(server));
	g_return_if_fail(dir == DBUSMENU_TEXT_DIRECTION_NONE || dir == DBUSMENU_TEXT_DIRECTION_LTR || dir == DBUSMENU_TEXT_DIRECTION_RTL);

	GValue newval = {0};
	g_value_init(&newval, DBUSMENU_TYPE_TEXT_DIRECTION);
	g_value_set_enum(&newval, dir);
	g_object_set_property(G_OBJECT(server), DBUSMENU_SERVER_PROP_TEXT_DIRECTION, &newval);
	g_value_unset(&newval);
	return;
}

/**
	dbusmenu_server_get_status:
	@server: The #DbusmenuServer to get the status from

	Gets the current statust hat the server is sending out over
	DBus.

	Return value: The current status the server is sending
*/
DbusmenuStatus
dbusmenu_server_get_status (DbusmenuServer * server)
{
	g_return_val_if_fail(DBUSMENU_IS_SERVER(server), DBUSMENU_STATUS_NORMAL);

	GValue val = {0};
	g_value_init(&val, DBUSMENU_TYPE_STATUS);
	g_object_get_property(G_OBJECT(server), DBUSMENU_SERVER_PROP_STATUS, &val);

	DbusmenuStatus retval = g_value_get_enum(&val);
	g_value_unset(&val);

	return retval;
}

/**
	dbusmenu_server_set_status:
	@server: The #DbusmenuServer to set the status on

	Changes the status of the server.
*/
void
dbusmenu_server_set_status (DbusmenuServer * server, DbusmenuStatus status)
{
	g_return_if_fail(DBUSMENU_IS_SERVER(server));

	GValue val = {0};
	g_value_init(&val, DBUSMENU_TYPE_STATUS);
	g_value_set_enum(&val, status);
	g_object_set_property(G_OBJECT(server), DBUSMENU_SERVER_PROP_STATUS, &val);
	g_value_unset(&val);

	return;
}