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
//! A [StatusNotifierHost](https://www.freedesktop.org/wiki/Specifications/StatusNotifierItem/)
//! for building system trays and similar applications.
//!
//! [`Host`] connects to the session bus, registers a `StatusNotifierHost` (and a built-in
//! `StatusNotifierWatcher` if not already present), and keeps track of every registered item along
//! with its menu. Changes are delivered as [`Event`]s through [`Host::process_events`], and items
//! are interacted with through the `item_*` and `menu_*` methods.
//!
//! See the `blocking` and `polling` examples for usage.
use std::collections::{HashMap, HashSet};
use std::os::fd::{AsFd, AsRawFd, BorrowedFd, RawFd};
use std::process;
use std::time::{Duration, Instant};
use dbus::MessageType;
use dbus::arg::{AppendAll, RefArg, Variant};
use dbus::channel::{BusType, Channel};
use dbus::message::Message;
const DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER: u32 = 1;
const DBUS_NAME_FLAG_DO_NOT_QUEUE: u32 = 4;
/// The tooltip of an [`Item`].
#[derive(Default, Debug, Clone, PartialEq)]
pub struct ToolTip {
/// The freedesktop-compliant name of the tooltip's icon.
pub icon_name: String,
/// The tooltip's icon as raw image data, possibly in multiple sizes.
pub icon_pixmap: Vec<Pixmap>,
/// The title of the tooltip.
pub title: String,
/// Descriptive text for the tooltip. May contain a subset of HTML markup.
pub description: String,
}
/// An icon image provided by an item.
#[derive(Default, Clone, PartialEq)]
pub struct Pixmap {
/// The width and height of the image in pixels.
pub dimensions: [i32; 2],
/// The raw image data in ARGB32 format, in network (big-endian) byte order.
pub image_data: Vec<u8>,
}
impl std::fmt::Debug for Pixmap {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Pixmap")
.field("dimensions", &self.dimensions)
.finish_non_exhaustive()
}
}
/// A `StatusNotifierItem` and its menu.
///
/// Most fields correspond directly to the properties of the `org.kde.StatusNotifierItem`
/// interface. Fields an item doesn't provide are left with their default (empty) values.
#[derive(Debug, Default, Clone, PartialEq)]
pub struct Item {
/// The bus name the item is reachable at, used to identify it in the [`Host`] methods.
pub bus_name: String,
/// The category of the item, e.g. `ApplicationStatus`, `Communications`, `SystemServices`
/// or `Hardware`.
pub category: String,
/// A name unique to the application, e.g. its name.
pub id: String,
/// A human readable name of the item.
pub title: String,
/// The status of the item: `Passive`, `Active` or `NeedsAttention`.
pub status: String,
/// The windowing-system dependent id of the application's window, or `0` if there is none.
pub window_id: u64,
/// An additional path to search for the item's icons.
pub icon_theme_path: String,
/// The freedesktop-compliant name of the main icon.
pub icon_name: String,
/// The main icon as raw image data, possibly in multiple sizes.
pub icon_pixmap: Vec<Pixmap>,
/// The name of an icon overlayed on top of the main icon.
pub overlay_icon_name: String,
/// The overlay icon as raw image data, possibly in multiple sizes.
pub overlay_icon_pixmap: Vec<Pixmap>,
/// The name of the icon used when the status is `NeedsAttention`.
pub attention_icon_name: String,
/// The attention icon as raw image data, possibly in multiple sizes.
pub attention_icon_pixmap: Vec<Pixmap>,
/// The name of an animation used when the status is `NeedsAttention`.
pub attention_movie_name: String,
/// The tooltip of the item.
pub tool_tip: ToolTip,
/// Whether the item only supports a context menu; activation should open the menu instead.
pub item_is_menu: bool,
/// The root of the item's menu tree, [`MenuNode::Empty`] if the item has no menu.
pub menu: MenuNode,
}
/// PNG image data for the icon of a [`MenuNode::Item`].
#[derive(Clone, PartialEq)]
pub struct IconData(pub Vec<u8>);
impl std::fmt::Debug for IconData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if self.0.is_empty() {
write!(f, "IconData(empty)")
} else {
write!(f, "IconData({} bytes)", self.0.len())
}
}
}
/// A node in the menu tree of an [`Item`].
///
/// Nodes are identified by their `id`, which is used with the `menu_*` methods of [`Host`].
#[derive(Debug, Clone, Default, PartialEq)]
pub enum MenuNode {
/// The item doesn't have a menu, or the menu hasn't been retrieved yet.
#[default]
Empty,
/// A (sub)menu containing other nodes.
Menu {
/// The id of the node.
id: i32,
/// The displayed text of the menu.
label: String,
/// Whether the menu can be opened.
enabled: bool,
/// Whether the menu should be shown.
visible: bool,
/// The nodes contained in the menu.
children: Vec<Self>,
},
/// An entry of a menu.
Item {
/// The id of the node.
id: i32,
/// The displayed text of the entry.
label: String,
/// Whether the entry can be clicked.
enabled: bool,
/// Whether the entry should be shown.
visible: bool,
/// The freedesktop-compliant name of the entry's icon.
icon_name: String,
/// PNG data of the entry's icon.
icon_data: IconData,
/// How the entry can be toggled.
toggle_type: ToggleType,
/// The current toggle state of the entry.
toggle_state: ToggleState,
},
/// A separator between entries.
Separator {
/// The id of the node.
id: i32,
/// Whether the separator should be shown.
visible: bool,
},
}
/// How a [`MenuNode::Item`] can be toggled.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToggleType {
/// The entry can't be toggled.
None,
/// The entry can be toggled independently, like a checkbox.
Checkmark,
/// The entry is part of a group where only one entry is toggled at a time, like a radio
/// button.
Radio,
}
/// The toggle state of a [`MenuNode::Item`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToggleState {
/// The entry is toggled on.
On,
/// The entry is toggled off.
Off,
/// The state is indeterminate, or the entry can't be toggled.
Unknown,
}
struct IntlItem {
menu_path: String,
menu_revision: u32,
item_op: Option<Item>,
}
/// A change of an [`Item`], delivered through the `event_fn` of [`Host::process_events`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Event {
/// The item was registered and its properties retrieved.
///
/// **Note**: The item's menu will not be fetched at the time of this event, but all other
/// item properties *should be* present.
Added,
/// The item was removed.
Removed,
/// [`Item::title`] was updated.
UpdatedTitle,
/// [`Item::status`] was updated.
UpdatedStatus,
/// [`Item::icon_theme_path`] was updated.
UpdatedIconThemePath,
/// [`Item::icon_name`] was updated.
UpdatedIconName,
/// [`Item::icon_pixmap`] was updated.
UpdatedIconPixmap,
/// [`Item::attention_icon_name`] was updated.
UpdatedAttentionIconName,
/// [`Item::attention_icon_pixmap`] was updated.
UpdatedAttentionIconPixmap,
/// [`Item::overlay_icon_name`] was updated.
UpdatedOverlayIconName,
/// [`Item::overlay_icon_pixmap`] was updated.
UpdatedOverlayIconPixmap,
/// [`Item::tool_tip`] was updated.
UpdatedToolTip,
/// [`Item::menu`] was updated.
UpdatedMenu,
}
struct Watcher {
hosts: HashSet<String>,
items: HashSet<String>,
}
enum ReplyTo {
RegisterHost,
NotifierItems,
ItemGetAll {
item_name: String,
},
ItemGet {
item_name: String,
property: &'static str,
},
MenuGetLayout {
item_name: String,
parent_id: i32,
},
ItemMethod {
item_name: String,
},
MenuEvent {
item_name: String,
},
}
/// The main object representing a `StatusNotifierHost`.
///
/// A `Host` connects to the session bus and keeps track of every registered `StatusNotifierItem`
/// along with its menu. Item state is kept up to date, and changes are delivered as [`Event`]s,
/// by calling [`Host::process_events`].
///
/// `Host` implements [`AsFd`], so instead of polling, the underlying connection can be registered
/// with `poll`/`epoll`-style event loops to wait for activity (see the `polling` example).
///
/// **Note**: The built-in `StatusNotifierWatcher` will only be used if there isn't a
/// `StatusNotifierWatcher` already registered.
pub struct Host {
channel: Channel,
bus_name: String,
items: HashMap<String, IntlItem>,
intl_watcher_op: Option<Watcher>,
pending_replies: HashMap<u32, (Instant, ReplyTo)>,
}
/// The error type used throughout the library.
///
/// [`operation`](Error::operation) tracks where the error originated and [`kind`](Error::kind)
/// what went wrong.
#[derive(Debug)]
pub struct Error {
/// The operation the error originated from.
pub operation: Operation,
/// What went wrong.
pub kind: ErrorKind,
/// The bus name of the remote peer involved, when known.
pub peer: Option<String>,
}
impl Error {
fn new(operation: Operation, kind: ErrorKind) -> Self {
Self {
operation,
kind,
peer: None,
}
}
fn with_peer<P>(operation: Operation, kind: ErrorKind, peer: P) -> Self
where
P: Into<String>,
{
Self {
operation,
kind,
peer: Some(peer.into()),
}
}
}
impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "error while {}", self.operation)?;
if let Some(peer) = self.peer.as_deref() {
write!(f, " ({peer})")?;
}
write!(f, ": {}", self.kind)
}
}
impl std::error::Error for Error {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match &self.kind {
ErrorKind::Dbus(e) => Some(e),
_ => None,
}
}
}
/// The operation an [`Error`] originated from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Operation {
/// Connecting to or communicating with the session bus.
Connect,
/// Requesting a bus name.
RequestName,
/// Adding a signal match rule.
AddMatch,
/// Registering this host with the `StatusNotifierWatcher`.
RegisterHost,
/// Retrieving the registered items from the `StatusNotifierWatcher`.
GetItems,
/// Retrieving the properties of an item.
ItemGet,
/// Calling a method of an item.
ItemMethod,
/// Processing a signal sent by an item.
ItemSignal,
/// Sending a menu event to an item.
MenuEvent,
/// Retrieving the menu layout of an item.
MenuGetLayout,
/// Handling a registration request sent to the internal watcher.
WatcherRegister,
/// Handling a property request sent to the internal watcher.
WatcherGet,
/// Handling or emitting a signal of the internal watcher.
WatcherSignal,
/// Processing a reply to a previously sent message.
Reply,
}
impl std::fmt::Display for Operation {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Connect => "communicating with the session bus",
Self::RequestName => "requesting a bus name",
Self::AddMatch => "adding a signal match rule",
Self::RegisterHost => "registering the host",
Self::GetItems => "retrieving the registered items",
Self::ItemGet => "retrieving item properties",
Self::ItemMethod => "calling an item method",
Self::ItemSignal => "processing an item signal",
Self::MenuEvent => "sending a menu event",
Self::MenuGetLayout => "retrieving a menu layout",
Self::WatcherRegister => "handling a watcher registration",
Self::WatcherGet => "handling a watcher property request",
Self::WatcherSignal => "handling a watcher signal",
Self::Reply => "processing a reply",
})
}
}
/// What went wrong for an [`Error`].
#[derive(Debug)]
pub enum ErrorKind {
/// A message could not be sent.
SendFailed,
/// A message contained invalid or unexpected data.
InvalidData,
/// A reply wasn't received in time.
Timeout,
/// The remote peer replied with an error.
Dbus(dbus::Error),
/// The connection to the session bus was lost.
Disconnected,
/// A `StatusNotifierHost` is already registered on the session bus.
HostAlreadyExists,
/// The external `StatusNotifierWatcher` is no longer available.
WatcherLost,
/// The given item bus name isn't known.
UnknownItem,
/// The given menu node doesn't exist in the item's menu.
UnknownMenuNode,
/// The given menu node is disabled.
MenuNodeDisabled,
}
impl std::fmt::Display for ErrorKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::SendFailed => f.write_str("the message could not be sent"),
Self::InvalidData => f.write_str("invalid or unexpected data was received"),
Self::Timeout => f.write_str("the reply wasn't received in time"),
Self::Dbus(e) => write!(f, "{e}"),
Self::Disconnected => f.write_str("the connection was lost"),
Self::HostAlreadyExists => f.write_str("a StatusNotifierHost is already registered"),
Self::WatcherLost => f.write_str("the StatusNotifierWatcher is no longer available"),
Self::UnknownItem => f.write_str("the item doesn't exist"),
Self::UnknownMenuNode => f.write_str("the menu node doesn't exist"),
Self::MenuNodeDisabled => f.write_str("the menu node is disabled"),
}
}
}
/// The direction of a [`Host::item_scroll`] request.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ScrollOrientation {
/// Scroll horizontally.
Horizontal,
/// Scroll vertically.
Vertical,
}
impl Host {
/// Connect to the session bus and register a `StatusNotifierHost`.
///
/// If no `StatusNotifierWatcher` is present on the bus, the built-in one is registered and
/// used (see [`Host::using_intl_watcher`]).
///
/// # Errors
///
/// Returns an error if connecting to the session bus fails, if another `StatusNotifierHost`
/// is already registered ([`ErrorKind::HostAlreadyExists`]), or if any of the setup messages
/// can't be sent.
pub fn new() -> Result<Self, Error> {
let mut channel = Channel::get_private(BusType::Session)
.map_err(|e| Error::new(Operation::Connect, ErrorKind::Dbus(e)))?;
let bus_msg = channel
.pop_message()
.ok_or_else(|| Error::new(Operation::Connect, ErrorKind::InvalidData))?;
let bus_name: String = bus_msg
.read1()
.map_err(|_| Error::new(Operation::Connect, ErrorKind::InvalidData))?;
let host_name = format!("org.kde.StatusNotifierHost-{}", process::id());
let req_host_msg = channel
.send_with_reply_and_block(
Message::call_with_args(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"RequestName",
(&host_name, DBUS_NAME_FLAG_DO_NOT_QUEUE),
),
Duration::from_secs(3),
)
.map_err(|e| Error::new(Operation::RequestName, ErrorKind::Dbus(e)))?;
let req_host_reply: u32 = req_host_msg
.read1()
.map_err(|_| Error::new(Operation::RequestName, ErrorKind::InvalidData))?;
if req_host_reply != DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER {
return Err(Error::new(
Operation::RequestName,
ErrorKind::HostAlreadyExists,
));
}
let req_watcher_msg = channel
.send_with_reply_and_block(
Message::call_with_args(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"RequestName",
("org.kde.StatusNotifierWatcher", DBUS_NAME_FLAG_DO_NOT_QUEUE),
),
Duration::from_secs(3),
)
.map_err(|e| Error::new(Operation::RequestName, ErrorKind::Dbus(e)))?;
let req_watcher_reply: u32 = req_watcher_msg
.read1()
.map_err(|_| Error::new(Operation::RequestName, ErrorKind::InvalidData))?;
let use_intl_watcher = req_watcher_reply == DBUS_REQUEST_NAME_REPLY_PRIMARY_OWNER;
for match_rule in [
"type='signal',interface='org.kde.StatusNotifierWatcher'",
"type='signal',interface='org.kde.StatusNotifierItem'",
"type='signal',interface='org.freedesktop.DBus',member='NameOwnerChanged'",
"type='signal',interface='com.canonical.dbusmenu'",
] {
channel
.send_with_reply_and_block(
Message::call_with_args(
"org.freedesktop.DBus",
"/org/freedesktop/DBus",
"org.freedesktop.DBus",
"AddMatch",
(match_rule,),
),
Duration::from_secs(3),
)
.map_err(|e| Error::new(Operation::AddMatch, ErrorKind::Dbus(e)))?;
}
channel.set_watch_enabled(true);
let mut host = Self {
channel,
bus_name,
items: HashMap::new(),
intl_watcher_op: None,
pending_replies: HashMap::new(),
};
if use_intl_watcher {
host.intl_watcher_op = Some(Watcher {
hosts: HashSet::new(),
items: HashSet::new(),
});
}
let serial = host
.channel
.send(Message::call_with_args(
"org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
"RegisterStatusNotifierHost",
((&host.bus_name),),
))
.map_err(|()| Error::new(Operation::RegisterHost, ErrorKind::SendFailed))?;
host.pending_replies
.insert(serial, (Instant::now(), ReplyTo::RegisterHost));
Ok(host)
}
/// Get an [`Item`] from the item's bus name.
///
/// Returns `None` if the item doesn't exist or its properties haven't been retrieved yet.
pub fn get_item<N>(&self, item_name: N) -> Option<&Item>
where
N: AsRef<str>,
{
self.items
.get(item_name.as_ref())
.and_then(|intl_item| intl_item.item_op.as_ref())
}
/// Get all existing [`Item`]'s.
pub fn get_all_items(&self) -> impl Iterator<Item = (&String, &Item)> {
self.items.iter().filter_map(|(item_name, intl_item)| {
intl_item.item_op.as_ref().map(|item| (item_name, item))
})
}
/// Call the `Activate` method of the `StatusNotifierItem` interface.
///
/// This is the primary action of an item, typically triggered by a left click. `x` and `y`
/// are the screen coordinates of the triggering input event.
///
/// # Errors
///
/// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
/// - [`ErrorKind::Disconnected`] if the message couldn't be sent
///
/// **Note**: An error reply from the item itself is delivered later through the `error_fn`
// of [`Host::process_events`].
pub fn item_activate<N>(&mut self, item_name: N, x: i32, y: i32) -> Result<(), Error>
where
N: AsRef<str>,
{
self.item_method(item_name.as_ref(), "Activate", (x, y))
}
/// Call the `ContextMenu` method of the `StatusNotifierItem` interface.
///
/// This asks the item to show its own context menu at the screen coordinates `x` and `y`,
/// typically triggered by a right click.
///
/// # Errors
///
/// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
/// - [`ErrorKind::Disconnected`] if the message couldn't be sent
///
/// **Note**: An error reply from the item itself is delivered later through the `error_fn`
// of [`Host::process_events`].
pub fn item_context_menu<N>(&mut self, item_name: N, x: i32, y: i32) -> Result<(), Error>
where
N: AsRef<str>,
{
self.item_method(item_name.as_ref(), "ContextMenu", (x, y))
}
/// Call the `SecondaryActivate` method of the `StatusNotifierItem` interface.
///
/// This is the secondary action of an item, typically triggered by a middle click. `x` and
/// `y` are the screen coordinates of the triggering input event.
///
/// # Errors
///
/// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
/// - [`ErrorKind::Disconnected`] if the message couldn't be sent
///
/// **Note**: An error reply from the item itself is delivered later through the `error_fn`
// of [`Host::process_events`].
pub fn item_secondary_activate<N>(&mut self, item_name: N, x: i32, y: i32) -> Result<(), Error>
where
N: AsRef<str>,
{
self.item_method(item_name.as_ref(), "SecondaryActivate", (x, y))
}
/// Call the `Scroll` method of the `StatusNotifierItem` interface.
///
/// This reports scroll wheel input over the item, `delta` being the amount scrolled in the
/// given [`ScrollOrientation`].
///
/// # Errors
///
/// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
/// - [`ErrorKind::Disconnected`] if the message couldn't be sent
///
/// **Note**: An error reply from the item itself is delivered later through the `error_fn`
// of [`Host::process_events`].
pub fn item_scroll<N>(
&mut self,
item_name: N,
delta: i32,
orientation: ScrollOrientation,
) -> Result<(), Error>
where
N: AsRef<str>,
{
self.item_method(
item_name.as_ref(),
"Scroll",
(
delta,
match orientation {
ScrollOrientation::Horizontal => "horizontal",
ScrollOrientation::Vertical => "vertical",
},
),
)
}
fn item_method<A>(&mut self, item_name: &str, method: &str, args: A) -> Result<(), Error>
where
A: AppendAll,
{
if self.get_item(item_name).is_none() {
return Err(Error::with_peer(
Operation::ItemMethod,
ErrorKind::UnknownItem,
item_name,
));
}
let serial = self
.channel
.send(Message::call_with_args(
item_name,
"/StatusNotifierItem",
"org.kde.StatusNotifierItem",
method,
args,
))
.map_err(|()| {
Error::with_peer(Operation::ItemMethod, ErrorKind::Disconnected, item_name)
})?;
self.pending_replies.insert(
serial,
(
Instant::now(),
ReplyTo::ItemMethod {
item_name: item_name.to_string(),
},
),
);
Ok(())
}
/// Send the `clicked` event of the `dbusmenu` interface to a menu node.
///
/// This activates the [`MenuNode`] with `node_id`, e.g. after the user clicked the entry.
///
/// # Errors
///
/// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
/// - [`ErrorKind::UnknownMenuNode`] if `node_id` isn't part of the item's menu
/// - [`ErrorKind::MenuNodeDisabled`] if the node isn't enabled
/// - [`ErrorKind::Disconnected`] if the message couldn't be sent
///
/// **Note**: An error reply from the item itself is delivered later through the `error_fn` of
/// [`Host::process_events`].
pub fn menu_clicked<N>(&mut self, item_name: N, node_id: i32) -> Result<(), Error>
where
N: AsRef<str>,
{
self.menu_event(item_name.as_ref(), node_id, "clicked")
}
/// Send the `hovered` event of the `dbusmenu` interface to a menu node.
///
/// This tells the item that the pointer moved onto the [`MenuNode`] with `node_id`.
///
/// # Errors
///
/// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
/// - [`ErrorKind::UnknownMenuNode`] if `node_id` isn't part of the item's menu
/// - [`ErrorKind::MenuNodeDisabled`] if the node isn't enabled
/// - [`ErrorKind::Disconnected`] if the message couldn't be sent
///
/// **Note**: An error reply from the item itself is delivered later through the `error_fn` of
/// [`Host::process_events`].
pub fn menu_hovered<N>(&mut self, item_name: N, node_id: i32) -> Result<(), Error>
where
N: AsRef<str>,
{
self.menu_event(item_name.as_ref(), node_id, "hovered")
}
/// Send the `opened` event of the `dbusmenu` interface to a menu node.
///
/// This tells the item that the (sub)menu with `node_id` was shown to the user.
///
/// # Errors
///
/// # Errors
///
/// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
/// - [`ErrorKind::UnknownMenuNode`] if `node_id` isn't part of the item's menu
/// - [`ErrorKind::MenuNodeDisabled`] if the node isn't enabled
/// - [`ErrorKind::Disconnected`] if the message couldn't be sent
///
/// **Note**: An error reply from the item itself is delivered later through the `error_fn` of
/// [`Host::process_events`].
pub fn menu_opened<N>(&mut self, item_name: N, node_id: i32) -> Result<(), Error>
where
N: AsRef<str>,
{
self.menu_event(item_name.as_ref(), node_id, "opened")
}
/// Send the `closed` event of the `dbusmenu` interface to a menu node.
///
/// This tells the item that the (sub)menu with `node_id` was closed.
///
/// # Errors
///
/// - [`ErrorKind::UnknownItem`] if `item_name` isn't a known item
/// - [`ErrorKind::UnknownMenuNode`] if `node_id` isn't part of the item's menu
/// - [`ErrorKind::MenuNodeDisabled`] if the node isn't enabled
/// - [`ErrorKind::Disconnected`] if the message couldn't be sent
///
/// **Note**: An error reply from the item itself is delivered later through the `error_fn` of
/// [`Host::process_events`].
pub fn menu_closed<N>(&mut self, item_name: N, node_id: i32) -> Result<(), Error>
where
N: AsRef<str>,
{
self.menu_event(item_name.as_ref(), node_id, "closed")
}
fn menu_event(&mut self, item_name: &str, node_id: i32, event: &str) -> Result<(), Error> {
let Some(intl_item) = self.items.get(item_name) else {
return Err(Error::with_peer(
Operation::MenuEvent,
ErrorKind::UnknownItem,
item_name,
));
};
let Some(item) = intl_item.item_op.as_ref() else {
return Err(Error::with_peer(
Operation::MenuEvent,
ErrorKind::UnknownItem,
item_name,
));
};
if intl_item.menu_path.is_empty() {
return Err(Error::with_peer(
Operation::MenuEvent,
ErrorKind::UnknownMenuNode,
item_name,
));
}
let mut check_nodes = vec![&item.menu];
let mut node_exists = false;
let mut node_enabled = false;
while let Some(node) = check_nodes.pop() {
match node {
MenuNode::Empty
| MenuNode::Separator {
..
} => continue,
MenuNode::Menu {
id,
children,
enabled,
..
} => {
if *id == node_id {
node_exists = true;
node_enabled = *enabled;
break;
}
check_nodes.extend(children.iter())
},
MenuNode::Item {
id,
enabled,
..
} => {
if *id == node_id {
node_exists = true;
node_enabled = *enabled;
break;
}
},
}
}
if !node_exists {
return Err(Error::with_peer(
Operation::MenuEvent,
ErrorKind::UnknownMenuNode,
item_name,
));
}
if event == "clicked" && !node_enabled {
return Err(Error::with_peer(
Operation::MenuEvent,
ErrorKind::MenuNodeDisabled,
item_name,
));
}
let serial = self
.channel
.send(Message::call_with_args(
item_name,
&intl_item.menu_path,
"com.canonical.dbusmenu",
"Event",
(node_id, event, Variant(""), 0_u32),
))
.map_err(|()| {
Error::with_peer(Operation::MenuEvent, ErrorKind::Disconnected, item_name)
})?;
self.pending_replies.insert(
serial,
(
Instant::now(),
ReplyTo::MenuEvent {
item_name: item_name.to_string(),
},
),
);
Ok(())
}
/// Check if the internal `StatusNotifierWatcher` is being used.
pub fn using_intl_watcher(&self) -> bool {
self.intl_watcher_op.is_some()
}
/// Process pending [`Event`]s and [`Error`]s.
///
/// - `event_fn` callback is used for events of an [`Item`].
/// - `error_fn` callback is used for [`Error`]s that occur that are non-fatal.
/// - The method itself will return an `Err(..)` if the error is fatal.
/// - `timeout` field is used to configure the blocking behavior.
/// - `None` will block until there is an event or an error to be processed.
/// - `Some(Duration::ZERO)` will not block (primarily used for polling).
///
/// **Note**: This method will return `Ok(true)` when there are pending writes to the `Fd`.
/// This *should* be relatively rare, so it can be ignored for initial implementations, but
/// should be considered when writing more robust implementations.
pub fn process_events<EventFn, ErrorFn>(
&mut self,
mut event_fn: EventFn,
mut error_fn: ErrorFn,
timeout: Option<Duration>,
) -> Result<bool, Error>
where
EventFn: FnMut(String, &Item, Event),
ErrorFn: FnMut(Error),
{
if self.channel.read_write(timeout).is_err() {
return Err(Error::new(Operation::Connect, ErrorKind::Disconnected));
}
struct MsgMatch<'a> {
ty: MessageType,
sender: Option<&'a str>,
destination: Option<&'a str>,
interface: Option<&'a str>,
member: Option<&'a str>,
}
while let Some(mut message) = self.channel.pop_message() {
match (MsgMatch {
ty: message.msg_type(),
sender: message.sender().as_deref(),
destination: message.destination().as_deref(),
interface: message.interface().as_deref(),
member: message.member().as_deref(),
}) {
MsgMatch {
ty: MessageType::MethodCall,
sender: Some(sender),
destination: Some("org.kde.StatusNotifierWatcher"),
interface: Some("org.kde.StatusNotifierWatcher"),
member: Some("RegisterStatusNotifierHost"),
} => {
let Some(watcher) = self.intl_watcher_op.as_mut() else {
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.UnknownObject",
));
continue;
};
let Ok(host_name) = message.read1::<String>() else {
error_fn(Error::with_peer(
Operation::WatcherRegister,
ErrorKind::InvalidData,
sender,
));
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.InvalidArgs",
));
continue;
};
let is_host_new = watcher.hosts.insert(host_name.clone());
if self.channel.send(message.method_return()).is_err() {
error_fn(Error::with_peer(
Operation::WatcherRegister,
ErrorKind::SendFailed,
sender,
));
}
if is_host_new && watcher.hosts.len() == 1 {
send_signal(
&self.channel,
Message::new_signal(
"/StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
"StatusNotifierHostRegistered",
)
.unwrap(),
&mut error_fn,
Error::new(Operation::WatcherSignal, ErrorKind::SendFailed),
);
}
},
MsgMatch {
ty: MessageType::MethodCall,
sender: Some(sender),
destination: Some("org.kde.StatusNotifierWatcher"),
interface: Some("org.kde.StatusNotifierWatcher"),
member: Some("RegisterStatusNotifierItem"),
} => {
let Some(watcher) = self.intl_watcher_op.as_mut() else {
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.UnknownObject",
));
continue;
};
let Ok(item_name) = message.read1::<String>() else {
error_fn(Error::with_peer(
Operation::WatcherRegister,
ErrorKind::InvalidData,
sender,
));
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.InvalidArgs",
));
continue;
};
let is_item_new = watcher.items.insert(item_name.clone());
if self.channel.send(message.method_return()).is_err() {
error_fn(Error::with_peer(
Operation::WatcherRegister,
ErrorKind::SendFailed,
sender,
));
}
if is_item_new {
send_signal(
&self.channel,
Message::new_signal(
"/StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
"StatusNotifierItemRegistered",
)
.unwrap()
.append1(item_name),
&mut error_fn,
Error::new(Operation::WatcherSignal, ErrorKind::SendFailed),
);
}
},
MsgMatch {
ty: MessageType::MethodCall,
sender: Some(sender),
interface: Some("org.freedesktop.DBus.Properties"),
member: Some("GetAll"),
..
} => {
let Ok(interface) = message.read1::<String>() else {
error_fn(Error::with_peer(
Operation::WatcherGet,
ErrorKind::InvalidData,
sender,
));
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.InvalidArgs",
));
continue;
};
match interface.as_str() {
"org.kde.StatusNotifierWatcher" => {
let Some(watcher) = self.intl_watcher_op.as_mut() else {
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.UnknownObject",
));
continue;
};
let host_registered = !watcher.hosts.is_empty();
let items: Vec<String> = watcher.items.iter().cloned().collect();
let mut dict: HashMap<&str, Variant<Box<dyn RefArg>>> = HashMap::new();
dict.insert("RegisteredStatusNotifierItems", Variant(Box::new(items)));
dict.insert(
"IsStatusNotifierHostRegistered",
Variant(Box::new(host_registered)),
);
dict.insert("ProtocolVersion", Variant(Box::new(0_i32)));
if self
.channel
.send(message.method_return().append1(dict))
.is_err()
{
error_fn(Error::with_peer(
Operation::WatcherGet,
ErrorKind::SendFailed,
sender,
));
}
},
_ => {
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.UnknownInterface",
));
},
}
},
MsgMatch {
ty: MessageType::MethodCall,
sender: Some(sender),
interface: Some("org.freedesktop.DBus.Properties"),
member: Some("Get"),
..
} => {
let Ok((interface, property)) = message.read2::<String, String>() else {
error_fn(Error::with_peer(
Operation::WatcherGet,
ErrorKind::InvalidData,
sender,
));
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.InvalidArgs",
));
continue;
};
match interface.as_str() {
"org.kde.StatusNotifierWatcher" => {
let Some(watcher) = self.intl_watcher_op.as_mut() else {
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.UnknownObject",
));
continue;
};
let reply = match property.as_str() {
"RegisteredStatusNotifierItems" => {
let items = watcher.items.iter().collect::<Vec<_>>();
message.method_return().append1(Variant(items))
},
"IsStatusNotifierHostRegistered" => {
message
.method_return()
.append1(Variant(!watcher.hosts.is_empty()))
},
"ProtocolVersion" => {
message.method_return().append1(Variant(0_i32))
},
_ => {
reply_error(
&message,
"org.freedesktop.DBus.Error.UnknownProperty",
)
},
};
if self.channel.send(reply).is_err() {
error_fn(Error::with_peer(
Operation::WatcherGet,
ErrorKind::SendFailed,
sender,
));
}
},
_ => {
let _ = self.channel.send(reply_error(
&message,
"org.freedesktop.DBus.Error.UnknownInterface",
));
},
}
},
MsgMatch {
ty: MessageType::Signal,
sender: Some(sender),
interface: Some("org.kde.StatusNotifierWatcher"),
member: Some("StatusNotifierItemRegistered"),
..
} => {
let Ok(item_name) = message.read1::<String>() else {
error_fn(Error::with_peer(
Operation::WatcherSignal,
ErrorKind::InvalidData,
sender,
));
continue;
};
if self.items.contains_key(&item_name) {
error_fn(Error::with_peer(
Operation::WatcherSignal,
ErrorKind::InvalidData,
sender,
));
continue;
}
self.items.insert(
item_name.clone(),
IntlItem {
menu_path: String::new(),
menu_revision: 0,
item_op: None,
},
);
match self.channel.send(msg_item_get_all(&item_name)) {
Ok(serial) => {
self.pending_replies.insert(
serial,
(
Instant::now(),
ReplyTo::ItemGetAll {
item_name: item_name.clone(),
},
),
);
},
Err(()) => {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::SendFailed,
item_name.clone(),
));
},
}
},
MsgMatch {
ty: MessageType::Signal,
sender: Some(sender),
interface: Some("org.kde.StatusNotifierWatcher"),
member: Some("StatusNotifierItemUnregistered"),
..
} => {
let Ok(item_name) = message.read1::<String>() else {
error_fn(Error::with_peer(
Operation::WatcherSignal,
ErrorKind::InvalidData,
sender,
));
continue;
};
let Some(item) = self.items.remove(&item_name) else {
error_fn(Error::with_peer(
Operation::WatcherSignal,
ErrorKind::InvalidData,
sender,
));
continue;
};
if let Some(item) = item.item_op {
event_fn(item_name, &item, Event::Removed);
}
},
MsgMatch {
ty: MessageType::Signal,
sender: Some(sender),
interface: Some("org.kde.StatusNotifierItem"),
member: Some(member),
..
} => {
if !self.items.contains_key(sender) {
// Note: signals may be received before the item is registered with the
// watcher. All properies will be fetched when it is registered.
continue;
}
let get_properties = match member {
"NewTitle" => vec!["Title"],
"NewIcon" => vec!["IconName", "IconPixmap"],
"NewAttentionIcon" => vec!["AttentionIconName", "AttentionIconPixmap"],
"NewOverlayIcon" => vec!["OverlayIconName", "OverlayIconPixmap"],
"NewToolTip" => vec!["ToolTip"],
"NewStatus" => {
let Ok(status) = message.read1::<String>() else {
error_fn(Error::with_peer(
Operation::ItemSignal,
ErrorKind::InvalidData,
sender,
));
continue;
};
let intl_item = self.items.get_mut(sender).expect("unreachable");
let Some(item) = intl_item.item_op.as_mut() else {
error_fn(Error::with_peer(
Operation::ItemSignal,
ErrorKind::InvalidData,
sender,
));
continue;
};
item.status = status;
event_fn(sender.to_string(), item, Event::UpdatedStatus);
continue;
},
"NewIconThemePath" => vec!["IconThemePath"],
_ => {
error_fn(Error::with_peer(
Operation::ItemSignal,
ErrorKind::InvalidData,
sender,
));
continue;
},
};
for property in get_properties {
match self.channel.send(msg_item_get_prop(sender, property)) {
Ok(serial) => {
self.pending_replies.insert(
serial,
(
Instant::now(),
ReplyTo::ItemGet {
item_name: sender.to_string(),
property,
},
),
);
},
Err(()) => {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::SendFailed,
sender,
));
},
}
}
},
MsgMatch {
ty: MessageType::Signal,
sender: Some(sender),
interface: Some("com.canonical.dbusmenu"),
member: Some("ItemsPropertiesUpdated"),
..
} => {
type UpdatedProps = Vec<(i32, HashMap<String, Variant<Box<dyn RefArg>>>)>;
type RemovedProps = Vec<(i32, Vec<String>)>;
let Ok((updated_props, removed_props)) =
message.read2::<UpdatedProps, RemovedProps>()
else {
error_fn(Error::with_peer(
Operation::ItemSignal,
ErrorKind::InvalidData,
sender,
));
continue;
};
let Some(intl_item) = self.items.get_mut(sender) else {
continue;
};
if intl_item.menu_path.is_empty() {
continue;
}
let Some(item) = intl_item.item_op.as_mut() else {
continue;
};
let mut menu_updated = false;
for (node_id, node_properties) in updated_props {
let Some((node, _depth)) = find_menu_node(&mut item.menu, node_id, 0)
else {
continue;
};
for (p_name, p_value_arg) in node_properties {
match p_name.as_str() {
"visible" => {
let Some(p_value) = p_value_arg.as_i64() else {
continue;
};
match node {
MenuNode::Empty => continue,
MenuNode::Menu {
visible, ..
}
| MenuNode::Item {
visible, ..
}
| MenuNode::Separator {
visible, ..
} => {
*visible = p_value == 1;
},
}
},
"enabled" => {
let Some(p_value) = p_value_arg.as_i64() else {
continue;
};
match node {
MenuNode::Menu {
enabled, ..
}
| MenuNode::Item {
enabled, ..
} => {
*enabled = p_value == 1;
},
_ => continue,
}
},
"label" => {
let Some(p_value) = p_value_arg.as_str() else {
continue;
};
match node {
MenuNode::Menu {
label, ..
}
| MenuNode::Item {
label, ..
} => {
*label = p_value.to_string();
},
_ => continue,
}
},
"icon-name" => {
let Some(p_value) = p_value_arg.as_str() else {
continue;
};
let MenuNode::Item {
icon_name, ..
} = node
else {
continue;
};
*icon_name = p_value.to_string();
},
"icon-data" => {
let Some(new_icon_data) = parse_icon_data_arg(&p_value_arg)
else {
continue;
};
let MenuNode::Item {
icon_data, ..
} = node
else {
continue;
};
*icon_data = new_icon_data;
},
"toggle-state" => {
let Some(new_toggle_state) =
parse_toggle_state_arg(&p_value_arg)
else {
continue;
};
let MenuNode::Item {
toggle_state, ..
} = node
else {
continue;
};
*toggle_state = new_toggle_state;
},
"toggle-type" => {
let Some(new_toggle_type) = parse_toggle_type_arg(&p_value_arg)
else {
continue;
};
let MenuNode::Item {
toggle_type, ..
} = node
else {
continue;
};
*toggle_type = new_toggle_type;
},
_ => continue,
}
menu_updated = true;
}
}
for (node_id, removed_props) in removed_props {
let Some((node, _depth)) = find_menu_node(&mut item.menu, node_id, 0)
else {
continue;
};
for p_name in removed_props {
match p_name.as_str() {
"label" => {
match node {
MenuNode::Menu {
label, ..
}
| MenuNode::Item {
label, ..
} => {
*label = String::new();
},
_ => continue,
}
},
"enabled" => {
match node {
MenuNode::Menu {
enabled, ..
}
| MenuNode::Item {
enabled, ..
} => {
*enabled = true;
},
_ => continue,
}
},
"visible" => {
match node {
MenuNode::Empty => continue,
MenuNode::Menu {
visible, ..
}
| MenuNode::Item {
visible, ..
}
| MenuNode::Separator {
visible, ..
} => {
*visible = true;
},
}
},
"icon-name" => {
let MenuNode::Item {
icon_name, ..
} = node
else {
continue;
};
icon_name.clear();
},
"icon-data" => {
let MenuNode::Item {
icon_data, ..
} = node
else {
continue;
};
icon_data.0.clear();
},
"toggle-type" => {
let MenuNode::Item {
toggle_type, ..
} = node
else {
continue;
};
*toggle_type = ToggleType::None;
},
"toggle-state" => {
let MenuNode::Item {
toggle_state, ..
} = node
else {
continue;
};
*toggle_state = ToggleState::Unknown;
},
_ => continue,
}
menu_updated = true;
}
}
if menu_updated {
event_fn(sender.to_string(), item, Event::UpdatedMenu);
}
},
MsgMatch {
ty: MessageType::Signal,
sender: Some(sender),
interface: Some("com.canonical.dbusmenu"),
member: Some("LayoutUpdated"),
..
} => {
let Ok((_revision, parent_id)) = message.read2::<u32, i32>() else {
error_fn(Error::with_peer(
Operation::ItemSignal,
ErrorKind::InvalidData,
sender,
));
continue;
};
let Some(intl_item) = self.items.get_mut(sender) else {
continue;
};
if intl_item.menu_path.is_empty() {
continue;
}
let args: (i32, i32, &[&str]) = (parent_id, -1, &[]);
match self.channel.send(Message::call_with_args(
sender,
&intl_item.menu_path,
"com.canonical.dbusmenu",
"GetLayout",
args,
)) {
Ok(serial) => {
self.pending_replies.insert(
serial,
(
Instant::now(),
ReplyTo::MenuGetLayout {
item_name: sender.to_string(),
parent_id,
},
),
);
},
Err(()) => {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::SendFailed,
sender,
))
},
}
},
MsgMatch {
ty: MessageType::Signal,
interface: Some("org.freedesktop.DBus"),
member: Some("NameOwnerChanged"),
..
} => {
let Ok((name, _old_owner, new_owner)) =
message.read3::<String, String, String>()
else {
continue;
};
if !new_owner.is_empty() {
if name == "org.kde.StatusNotifierWatcher" && self.intl_watcher_op.is_none()
{
match self
.channel
.send(Message::call_with_args(
"org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
"RegisterStatusNotifierHost",
((&self.bus_name),),
))
.map_err(|()| {
Error::new(Operation::RegisterHost, ErrorKind::SendFailed)
}) {
Ok(serial) => {
self.pending_replies
.insert(serial, (Instant::now(), ReplyTo::RegisterHost));
},
Err(e) => error_fn(e),
}
}
continue;
}
let Some(watcher) = self.intl_watcher_op.as_mut() else {
if name == "org.kde.StatusNotifierWatcher" {
for (item_name, intl_item) in self.items.drain() {
if let Some(item) = intl_item.item_op {
event_fn(item_name, &item, Event::Removed);
}
}
error_fn(Error::new(Operation::RegisterHost, ErrorKind::WatcherLost));
}
continue;
};
if watcher.hosts.remove(&name) && watcher.hosts.is_empty() {
send_signal(
&self.channel,
Message::new_signal(
"/StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
"StatusNotifierHostUnregistered",
)
.unwrap(),
&mut error_fn,
Error::new(Operation::WatcherSignal, ErrorKind::SendFailed),
);
}
if watcher.items.remove(&name) {
send_signal(
&self.channel,
Message::new_signal(
"/StatusNotifierWatcher",
"org.kde.StatusNotifierWatcher",
"StatusNotifierItemUnregistered",
)
.unwrap()
.append1(&name),
&mut error_fn,
Error::new(Operation::WatcherSignal, ErrorKind::SendFailed),
);
}
},
MsgMatch {
sender: Some(sender),
ty: MessageType::MethodReturn,
..
} => {
let Some(reply_serial) = message.get_reply_serial() else {
error_fn(Error::with_peer(
Operation::Reply,
ErrorKind::InvalidData,
sender,
));
continue;
};
let Some((_, reply_to)) = self.pending_replies.remove(&reply_serial) else {
error_fn(Error::with_peer(
Operation::Reply,
ErrorKind::InvalidData,
sender,
));
continue;
};
match reply_to {
ReplyTo::RegisterHost => {
if self.intl_watcher_op.is_some() {
continue;
}
match self
.channel
.send(Message::call_with_args(
"org.kde.StatusNotifierWatcher",
"/StatusNotifierWatcher",
"org.freedesktop.DBus.Properties",
"Get",
(
"org.kde.StatusNotifierWatcher",
"RegisteredStatusNotifierItems",
),
))
.map_err(|()| {
Error::new(Operation::GetItems, ErrorKind::SendFailed)
}) {
Ok(serial) => {
self.pending_replies
.insert(serial, (Instant::now(), ReplyTo::NotifierItems));
},
Err(e) => error_fn(e),
}
},
ReplyTo::NotifierItems => {
let Ok(items) = message.read1::<Variant<Vec<String>>>() else {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::InvalidData,
message.sender().unwrap().to_string(),
));
continue;
};
for item_name in items.0 {
self.items.insert(
item_name.clone(),
IntlItem {
menu_path: String::new(),
menu_revision: 0,
item_op: None,
},
);
match self.channel.send(msg_item_get_all(&item_name)) {
Ok(serial) => {
self.pending_replies.insert(
serial,
(
Instant::now(),
ReplyTo::ItemGetAll {
item_name: item_name.clone(),
},
),
);
},
Err(()) => {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::SendFailed,
item_name.clone(),
));
},
}
}
},
ReplyTo::ItemGetAll {
item_name,
} => {
let Some(intl_item) = self.items.get_mut(&item_name) else {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::InvalidData,
item_name,
));
continue;
};
let Ok(mut fields) =
message.read1::<HashMap<String, Variant<Box<dyn RefArg>>>>()
else {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::InvalidData,
item_name,
));
continue;
};
let mut item = Item {
bus_name: item_name.clone(),
..Item::default()
};
macro_rules! parse_string_fields {
(
$item:expr,
$fields:expr,
{ $($field:ident => $key:expr),* $(,)? }
) => {
$(
$item.$field = $fields
.remove($key)
.and_then(|arg| arg.as_str().map(|s| s.to_string()))
.unwrap_or_default();
)*
};
}
parse_string_fields!(
item,
fields,
{
category => "Category",
id => "Id",
title => "Title",
status => "Status",
icon_theme_path => "IconThemePath",
icon_name => "IconName",
overlay_icon_name => "OverlayIconName",
attention_icon_name => "AttentionIconName",
attention_movie_name => "AttentionMovieName",
}
);
parse_string_fields!(intl_item, fields, { menu_path => "Menu" });
item.window_id = fields
.remove("WindowId")
.and_then(|arg| arg.as_u64())
.unwrap_or_default();
item.item_is_menu = fields
.remove("ItemIsMenu")
.and_then(|arg| arg.as_i64().map(|val| val == 1))
.unwrap_or_default();
macro_rules! parse_pixmap_fields {
(
$item:expr,
$fields:expr,
{ $($field:ident => $key:expr),* $(,)? }
) => {
$(
$item.$field = $fields
.remove($key)
.map(|arg| parse_pixmap_arg(&arg.0))
.unwrap_or_default();
)*
};
}
parse_pixmap_fields!(
item,
fields,
{
icon_pixmap => "IconPixmap",
overlay_icon_pixmap => "OverlayIconPixmap",
attention_icon_pixmap => "AttentionIconPixmap",
}
);
item.tool_tip = fields
.remove("ToolTip")
.map(|arg| parse_tool_tip_arg(&arg.0))
.unwrap_or_default();
if !intl_item.menu_path.is_empty() {
let args: (i32, i32, &[&str]) = (0, -1, &[]);
match self.channel.send(Message::call_with_args(
&item_name,
&intl_item.menu_path,
"com.canonical.dbusmenu",
"GetLayout",
args,
)) {
Ok(serial) => {
self.pending_replies.insert(
serial,
(
Instant::now(),
ReplyTo::MenuGetLayout {
item_name: item_name.clone(),
parent_id: 0,
},
),
);
},
Err(()) => {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::SendFailed,
item_name.clone(),
));
},
}
}
if intl_item.item_op.replace(item).is_none() {
event_fn(
item_name,
intl_item.item_op.as_ref().expect("unreachable"),
Event::Added,
);
}
},
ReplyTo::ItemGet {
item_name,
property,
} => {
let Some(intl_item) = self.items.get_mut(&item_name) else {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::InvalidData,
item_name,
));
continue;
};
let Some(item) = intl_item.item_op.as_mut() else {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::InvalidData,
item_name,
));
continue;
};
match property {
"Title" => {
if let Ok(title) = message.read1::<Variant<String>>()
&& title.0 != item.title
{
item.title = title.0;
event_fn(item_name, item, Event::UpdatedTitle);
}
},
"IconThemePath" => {
if let Ok(path) = message.read1::<Variant<String>>()
&& path.0 != item.icon_theme_path
{
item.icon_theme_path = path.0;
event_fn(item_name, item, Event::UpdatedIconThemePath);
}
},
"IconName" => {
if let Ok(name) = message.read1::<Variant<String>>()
&& name.0 != item.icon_name
{
item.icon_name = name.0;
event_fn(item_name, item, Event::UpdatedIconName);
}
},
"IconPixmap" => {
if let Some(pixmap) = message
.read1::<Variant<Box<dyn RefArg>>>()
.ok()
.map(|arg| parse_pixmap_arg(&arg.0))
&& pixmap != item.icon_pixmap
{
item.icon_pixmap = pixmap;
event_fn(item_name, item, Event::UpdatedIconPixmap);
}
},
"AttentionIconName" => {
if let Ok(name) = message.read1::<Variant<String>>()
&& name.0 != item.attention_icon_name
{
item.attention_icon_name = name.0;
event_fn(item_name, item, Event::UpdatedAttentionIconName);
}
},
"AttentionIconPixmap" => {
if let Some(pixmap) = message
.read1::<Variant<Box<dyn RefArg>>>()
.ok()
.map(|arg| parse_pixmap_arg(&arg.0))
&& pixmap != item.attention_icon_pixmap
{
item.attention_icon_pixmap = pixmap;
event_fn(
item_name,
item,
Event::UpdatedAttentionIconPixmap,
);
}
},
"OverlayIconName" => {
if let Ok(name) = message.read1::<Variant<String>>()
&& name.0 != item.overlay_icon_name
{
item.overlay_icon_name = name.0;
event_fn(item_name, item, Event::UpdatedOverlayIconName);
}
},
"OverlayIconPixmap" => {
if let Some(pixmap) = message
.read1::<Variant<Box<dyn RefArg>>>()
.ok()
.map(|arg| parse_pixmap_arg(&arg.0))
&& pixmap != item.overlay_icon_pixmap
{
item.overlay_icon_pixmap = pixmap;
event_fn(item_name, item, Event::UpdatedOverlayIconPixmap);
}
},
"ToolTip" => {
if let Some(tool_tip) = message
.read1::<Variant<Box<dyn RefArg>>>()
.ok()
.map(|arg| parse_tool_tip_arg(&arg.0))
&& tool_tip != item.tool_tip
{
item.tool_tip = tool_tip;
event_fn(item_name, item, Event::UpdatedToolTip);
}
},
_ => (),
}
},
ReplyTo::MenuGetLayout {
item_name,
parent_id,
} => {
let Some(intl_item) = self.items.get_mut(&item_name) else {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::InvalidData,
item_name,
));
continue;
};
let Some(item) = intl_item.item_op.as_mut() else {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::InvalidData,
item_name,
));
continue;
};
let (node, depth) = match parent_id {
0 => (&mut item.menu, 0),
_ => {
match find_menu_node(&mut item.menu, parent_id, 0) {
Some(some) => some,
None => {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::InvalidData,
item_name,
));
continue;
},
}
},
};
let (Some(revision), Some(arg)) =
message.get2::<u32, Box<dyn RefArg>>()
else {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::InvalidData,
item_name,
));
continue;
};
let Ok(new_node) = parse_menu(arg.as_ref(), depth) else {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::InvalidData,
item_name,
));
continue;
};
*node = new_node;
intl_item.menu_revision = revision;
event_fn(item_name, item, Event::UpdatedMenu);
},
ReplyTo::ItemMethod {
..
}
| ReplyTo::MenuEvent {
..
} => (),
}
},
MsgMatch {
sender: Some(sender),
ty: MessageType::Error,
..
} => {
let Some(reply_serial) = message.get_reply_serial() else {
error_fn(Error::with_peer(
Operation::Reply,
ErrorKind::InvalidData,
sender,
));
continue;
};
let Some((_, reply_to)) = self.pending_replies.remove(&reply_serial) else {
error_fn(Error::with_peer(
Operation::Reply,
ErrorKind::InvalidData,
sender,
));
continue;
};
let Err(e) = message.as_result() else {
continue;
};
match reply_to {
ReplyTo::RegisterHost => {
error_fn(Error::new(Operation::RegisterHost, ErrorKind::Dbus(e)));
},
ReplyTo::NotifierItems => {
error_fn(Error::new(Operation::GetItems, ErrorKind::Dbus(e)));
},
ReplyTo::ItemGetAll {
item_name,
}
| ReplyTo::ItemGet {
item_name, ..
} => {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::Dbus(e),
item_name,
));
},
ReplyTo::MenuGetLayout {
item_name, ..
} => {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::Dbus(e),
item_name,
));
},
ReplyTo::ItemMethod {
item_name,
} => {
error_fn(Error::with_peer(
Operation::ItemMethod,
ErrorKind::Dbus(e),
item_name,
));
},
ReplyTo::MenuEvent {
item_name,
} => {
error_fn(Error::with_peer(
Operation::MenuEvent,
ErrorKind::Dbus(e),
item_name,
));
},
}
},
MsgMatch {
ty: MessageType::MethodCall,
..
} => {
let _ = self
.channel
.send(reply_error(&message, "org.freedesktop.DBus.Error.Failed"));
},
_ => (),
}
}
self.pending_replies.retain(|_, (inst_sent, reply_to)| {
if inst_sent.elapsed() > Duration::from_millis(500) {
match reply_to {
ReplyTo::RegisterHost => {
error_fn(Error::new(Operation::RegisterHost, ErrorKind::Timeout));
},
ReplyTo::NotifierItems => {
error_fn(Error::new(Operation::GetItems, ErrorKind::Timeout));
},
ReplyTo::ItemGetAll {
item_name,
}
| ReplyTo::ItemGet {
item_name, ..
} => {
error_fn(Error::with_peer(
Operation::ItemGet,
ErrorKind::Timeout,
item_name.clone(),
));
},
ReplyTo::MenuGetLayout {
item_name, ..
} => {
error_fn(Error::with_peer(
Operation::MenuGetLayout,
ErrorKind::Timeout,
item_name.clone(),
));
},
ReplyTo::ItemMethod {
item_name,
} => {
error_fn(Error::with_peer(
Operation::ItemMethod,
ErrorKind::Timeout,
item_name.clone(),
));
},
ReplyTo::MenuEvent {
item_name,
} => {
error_fn(Error::with_peer(
Operation::MenuEvent,
ErrorKind::Timeout,
item_name.clone(),
));
},
}
false
} else {
true
}
});
Ok(self.channel.watch().write)
}
}
impl AsRawFd for Host {
fn as_raw_fd(&self) -> RawFd {
self.channel.watch().fd
}
}
impl AsFd for Host {
fn as_fd(&self) -> BorrowedFd<'_> {
unsafe { BorrowedFd::borrow_raw(self.channel.watch().fd) }
}
}
fn reply_error(message: &Message, error: &str) -> Message {
message.error(&dbus::strings::ErrorName::new(error).unwrap(), c"")
}
fn msg_item_get_all<I>(item_name: &I) -> Message
where
I: AsRef<str>,
{
Message::call_with_args(
item_name.as_ref(),
"/StatusNotifierItem",
"org.freedesktop.DBus.Properties",
"GetAll",
("org.kde.StatusNotifierItem",),
)
}
fn msg_item_get_prop(item_name: &str, property: &'static str) -> Message {
Message::call_with_args(
item_name,
"/StatusNotifierItem",
"org.freedesktop.DBus.Properties",
"Get",
("org.kde.StatusNotifierItem", property),
)
}
fn send_signal(
channel: &Channel,
message: Message,
error_fn: &mut impl FnMut(Error),
error: Error,
) {
if channel.send(message).is_err() {
error_fn(error);
}
}
fn parse_pixmap_arg(value: &dyn RefArg) -> Vec<Pixmap> {
let mut pixmaps = Vec::new();
let Some(iter) = value.as_iter() else {
return pixmaps;
};
for item in iter {
let Some(mut fields) = item.as_iter() else {
continue;
};
let Some(width) = fields.next().and_then(RefArg::as_i64) else {
continue;
};
let Some(height) = fields.next().and_then(RefArg::as_i64) else {
continue;
};
let Some(bytes_arg) = fields.next() else {
continue;
};
let Some(byte_iter) = bytes_arg.as_iter() else {
continue;
};
let bytes: Vec<u8> = byte_iter
.filter_map(|b| b.as_u64().map(|v| v as u8))
.collect();
if width < 1
|| width > i32::MAX as i64
|| height < 1
|| height > i32::MAX as i64
|| width as usize * height as usize * 4 != bytes.len()
{
continue;
}
pixmaps.push(Pixmap {
dimensions: [width as i32, height as i32],
image_data: bytes,
});
}
pixmaps
}
fn parse_tool_tip_arg(value: &dyn RefArg) -> ToolTip {
let Some(mut iter) = value.as_iter() else {
return ToolTip::default();
};
let Some(icon_name) = iter
.next()
.and_then(|arg| arg.as_str())
.map(|arg| arg.to_string())
else {
return ToolTip::default();
};
let Some(icon_pixmap) = iter.next().map(|arg| parse_pixmap_arg(&arg)) else {
return ToolTip::default();
};
let Some(title) = iter
.next()
.and_then(|arg| arg.as_str())
.map(|arg| arg.to_string())
else {
return ToolTip::default();
};
let Some(description) = iter
.next()
.and_then(|arg| arg.as_str())
.map(|arg| arg.to_string())
else {
return ToolTip::default();
};
ToolTip {
icon_name,
icon_pixmap,
title,
description,
}
}
fn find_menu_node(
node: &mut MenuNode,
find_id: i32,
depth: usize,
) -> Option<(&mut MenuNode, usize)> {
match node {
MenuNode::Empty => None,
MenuNode::Menu {
id, ..
} if *id == find_id => Some((node, depth)),
MenuNode::Menu {
children, ..
} => {
children
.iter_mut()
.find_map(|child| find_menu_node(child, find_id, depth + 1))
},
MenuNode::Item {
id, ..
}
| MenuNode::Separator {
id, ..
} if *id == find_id => Some((node, depth)),
_ => None,
}
}
fn parse_menu(arg: &dyn RefArg, depth: usize) -> Result<MenuNode, ()> {
if depth > 8 {
return Err(());
}
let mut struct_iter = arg.as_iter().ok_or(())?;
let menu_id = struct_iter.next().ok_or(())?.as_i64().ok_or(())? as i32;
let mut property_iter = struct_iter.next().ok_or(())?.as_iter().ok_or(())?;
let mut is_submenu = false;
let mut is_separator = false;
let mut visible = true;
let mut enabled = true;
let mut label = String::new();
let mut icon_name = String::new();
let mut icon_data = IconData(Vec::new());
let mut toggle_state = ToggleState::Unknown;
let mut toggle_type = ToggleType::None;
while let Some(p_name_arg) = property_iter.next() {
let Some(p_name) = p_name_arg.as_str() else {
continue;
};
let Some(p_value_arg) = property_iter.next() else {
continue;
};
match p_name {
"children-display" => {
let Some(p_value) = p_value_arg.as_str() else {
continue;
};
if p_value != "submenu" {
continue;
}
is_submenu = true;
},
"visible" => {
let Some(p_value) = p_value_arg.as_i64() else {
continue;
};
visible = p_value == 1;
},
"enabled" => {
let Some(p_value) = p_value_arg.as_i64() else {
continue;
};
enabled = p_value == 1;
},
"type" => {
let Some(p_value) = p_value_arg.as_str() else {
continue;
};
if p_value != "separator" {
continue;
}
is_separator = true;
},
"label" => {
let Some(p_value) = p_value_arg.as_str() else {
continue;
};
label = p_value.to_string();
},
"icon-name" => {
let Some(p_value) = p_value_arg.as_str() else {
continue;
};
icon_name = p_value.to_string();
},
"icon-data" => {
let Some(new_icon_data) = parse_icon_data_arg(&p_value_arg) else {
continue;
};
icon_data = new_icon_data;
},
"toggle-state" => {
let Some(new_toggle_state) = parse_toggle_state_arg(&p_value_arg) else {
continue;
};
toggle_state = new_toggle_state;
},
"toggle-type" => {
let Some(new_toggle_type) = parse_toggle_type_arg(&p_value_arg) else {
continue;
};
toggle_type = new_toggle_type;
},
_ => (),
}
}
if depth == 0 || is_submenu {
let mut children = Vec::new();
let submenu_iter = struct_iter.next().ok_or(())?.as_iter().ok_or(())?;
for menu_variant in submenu_iter {
if let Some(mut menu_variant_iter) = menu_variant.as_iter()
&& let Some(menu_struct) = menu_variant_iter.next()
&& let Ok(submenu) = parse_menu(menu_struct, depth + 1)
{
children.push(submenu);
}
}
Ok(MenuNode::Menu {
id: menu_id,
label,
enabled,
visible,
children,
})
} else if is_separator {
Ok(MenuNode::Separator {
id: menu_id,
visible,
})
} else {
Ok(MenuNode::Item {
id: menu_id,
label,
enabled,
visible,
icon_name,
icon_data,
toggle_type,
toggle_state,
})
}
}
fn parse_icon_data_arg(arg: &dyn RefArg) -> Option<IconData> {
let mut bytes_variant_iter = arg.as_iter()?;
let bytes_array = bytes_variant_iter.next()?;
let bytes_iter = bytes_array.as_iter()?;
let mut icon_data = Vec::new();
for byte_arg in bytes_iter {
let byte_u64 = byte_arg.as_u64()?;
if byte_u64 > 255 {
return None;
}
icon_data.push(byte_u64 as u8);
}
Some(IconData(icon_data))
}
fn parse_toggle_state_arg(arg: &dyn RefArg) -> Option<ToggleState> {
Some(match arg.as_i64()? {
0 => ToggleState::Off,
1 => ToggleState::On,
_ => ToggleState::Unknown,
})
}
fn parse_toggle_type_arg(arg: &dyn RefArg) -> Option<ToggleType> {
match arg.as_str()? {
"checkmark" => Some(ToggleType::Checkmark),
"radio" => Some(ToggleType::Radio),
_ => None,
}
}