-
Notifications
You must be signed in to change notification settings - Fork 128
/
dbus.d
2133 lines (1927 loc) · 73.9 KB
/
dbus.d
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
/++
A module mostly copied from https://github.com/trishume/ddbus to help access the C dbus library on Linux.
+/
module arsd.dbus;
pragma(lib, "dbus-1");
import core.time : Duration;
import std.meta;
import std.string;
import std.typecons;
import std.exception;
import std.traits;
import std.conv;
import std.range;
import std.algorithm;
import core.memory;
import std.array;
import std.format;
import std.meta : AliasSeq, staticIndexOf;
import std.range;
import std.traits;
import std.variant : VariantN;
/++
Flags for use with dbusMarshaling UDA
Default is to include public fields only
+/
enum MarshalingFlag : ubyte {
includePrivateFields = 1 << 0, /// Automatically include private fields
manualOnly = 1 << 7 /// Only include fields with explicit
/// `@Yes.DBusMarshal`. This overrides any
/// `include` flags.
}
/++
UDA for specifying DBus marshaling options on structs
+/
auto dbusMarshaling(Args)(Args args ...)
if (allSatisfy!(isMarshalingFlag, Args)) {
return BitFlags!MarshalingFlag(args);
}
private template isAllowedField(alias field) {
private enum flags = marshalingFlags!(__traits(parent, field));
private alias getUDAs!(field, Flag!"DBusMarshal") UDAs;
static if (UDAs.length != 0) {
static assert (UDAs.length == 1,
"Only one UDA of type Flag!\"DBusMarshal\" allowed on struct field.");
static assert (is(typeof(UDAs[0]) == Flag!"DBusMarshal"),
"Did you intend to add UDA Yes.DBusMarshal or No.DBusMarshal?");
enum isAllowedField = cast(bool) UDAs[0];
} else static if (!(flags & MarshalingFlag.manualOnly)) {
static if (__traits(getProtection, field) == "public")
enum isAllowedField = true;
else static if (cast(bool) (flags & MarshalingFlag.includePrivateFields))
enum isAllowedField = true;
else
enum isAllowedField = false;
} else
enum isAllowedField = false;
}
private template isMarshalingFlag(T) {
enum isMarshalingFlag = is(T == MarshalingFlag);
}
private template marshalingFlags(S) if (is(S == struct)) {
private alias getUDAs!(S, BitFlags!MarshalingFlag) UDAs;
static if (UDAs.length == 0)
enum marshalingFlags = BitFlags!MarshalingFlag.init;
else {
static assert (UDAs.length == 1,
"Only one @dbusMarshaling UDA allowed on type.");
static assert (is(typeof(UDAs[0]) == BitFlags!MarshalingFlag),
"Huh? Did you intend to use @dbusMarshaling UDA?");
enum marshalingFlags = UDAs[0];
}
}
struct DictionaryEntry(K, V) {
K key;
V value;
}
auto byDictionaryEntries(K, V)(V[K] aa) {
return aa.byKeyValue.map!(pair => DictionaryEntry!(K, V)(pair.key, pair.value));
}
template VariantType(T) {
alias VariantType = TemplateArgsOf!(T)[0];
}
template allCanDBus(TS...) {
static if (TS.length == 0) {
enum allCanDBus = true;
} else static if(!canDBus!(TS[0])) {
enum allCanDBus = false;
} else {
enum allCanDBus = allCanDBus!(TS[1..$]);
}
}
/++
AliasSeq of all basic types in terms of the DBus typesystem
+/
private // Don't add to the API yet, 'cause I intend to move it later
alias BasicTypes = AliasSeq!(
bool,
byte,
short,
ushort,
int,
uint,
long,
ulong,
double,
string,
ObjectPath
);
template basicDBus(T) {
static if(staticIndexOf!(T, BasicTypes) >= 0) {
enum basicDBus = true;
} else static if(is(T B == enum)) {
enum basicDBus = basicDBus!B;
} else static if(isInstanceOf!(BitFlags, T)) {
alias TemplateArgsOf!T[0] E;
enum basicDBus = basicDBus!E;
} else {
enum basicDBus = false;
}
}
template canDBus(T) {
static if(basicDBus!T || is(T == DBusAny)) {
enum canDBus = true;
} else static if(isInstanceOf!(Variant, T)) {
enum canDBus = canDBus!(VariantType!T);
} else static if(isInstanceOf!(VariantN, T)) {
// Phobos-style variants are supported if limited to DBus compatible types.
enum canDBus = (T.AllowedTypes.length > 0) && allCanDBus!(T.AllowedTypes);
} else static if(isTuple!T) {
enum canDBus = allCanDBus!(T.Types);
} else static if(isInputRange!T) {
static if(is(ElementType!T == DictionaryEntry!(K, V), K, V)) {
enum canDBus = basicDBus!K && canDBus!V;
} else {
enum canDBus = canDBus!(ElementType!T);
}
} else static if(isAssociativeArray!T) {
enum canDBus = basicDBus!(KeyType!T) && canDBus!(ValueType!T);
} else static if(is(T == struct) && !isInstanceOf!(DictionaryEntry, T)) {
enum canDBus = allCanDBus!(AllowedFieldTypes!T);
} else {
enum canDBus = false;
}
}
string typeSig(T)() if(canDBus!T) {
static if(is(T == byte)) {
return "y";
} else static if(is(T == bool)) {
return "b";
} else static if(is(T == short)) {
return "n";
} else static if(is(T == ushort)) {
return "q";
} else static if(is(T == int)) {
return "i";
} else static if(is(T == uint)) {
return "u";
} else static if(is(T == long)) {
return "x";
} else static if(is(T == ulong)) {
return "t";
} else static if(is(T == double)) {
return "d";
} else static if(is(T == string)) {
return "s";
} else static if(is(T == ObjectPath)) {
return "o";
} else static if(isInstanceOf!(Variant, T) || isInstanceOf!(VariantN, T)) {
return "v";
} else static if(is(T B == enum)) {
return typeSig!B;
} else static if(isInstanceOf!(BitFlags, T)) {
alias TemplateArgsOf!T[0] E;
return typeSig!E;
} else static if(is(T == DBusAny)) {
static assert(false, "Cannot determine type signature of DBusAny. Change to Variant!DBusAny if a variant was desired.");
} else static if(isTuple!T) {
string sig = "(";
foreach(i, S; T.Types) {
sig ~= typeSig!S();
}
sig ~= ")";
return sig;
} else static if(isInputRange!T) {
return "a" ~ typeSig!(ElementType!T)();
} else static if(isAssociativeArray!T) {
return "a{" ~ typeSig!(KeyType!T) ~ typeSig!(ValueType!T) ~ "}";
} else static if(is(T == struct)) {
string sig = "(";
foreach(i, S; AllowedFieldTypes!T) {
sig ~= typeSig!S();
}
sig ~= ")";
return sig;
}
}
string typeSig(T)() if(isInstanceOf!(DictionaryEntry, T)) {
alias typeof(T.key) K;
alias typeof(T.value) V;
return "{" ~ typeSig!K ~ typeSig!V ~ '}';
}
string[] typeSigReturn(T)() if(canDBus!T) {
static if(is(T == Tuple!TS, TS...))
return typeSigArr!TS;
else
return [typeSig!T];
}
string typeSigAll(TS...)() if(allCanDBus!TS) {
string sig = "";
foreach(i,T; TS) {
sig ~= typeSig!T();
}
return sig;
}
string[] typeSigArr(TS...)() if(allCanDBus!TS) {
string[] sig = [];
foreach(i,T; TS) {
sig ~= typeSig!T();
}
return sig;
}
int typeCode(T)() if(canDBus!T) {
int code = typeSig!T()[0];
return (code != '(') ? code : 'r';
}
int typeCode(T)() if(isInstanceOf!(DictionaryEntry, T) && canDBus!(T[])) {
return 'e';
}
private template AllowedFieldTypes(S) if (is(S == struct)) {
static alias TypeOf(alias sym) = typeof(sym);
alias AllowedFieldTypes =
staticMap!(TypeOf, Filter!(isAllowedField, S.tupleof));
}
struct ObjectPath {
private string _value;
this(string objPath) pure @safe {
enforce(isValid(objPath));
_value = objPath;
}
string toString() const {
return _value;
}
/++
Returns the string representation of this ObjectPath.
+/
string value() const pure @nogc nothrow @safe {
return _value;
}
size_t toHash() const pure @nogc nothrow @trusted {
return hashOf(_value);
}
bool opEquals(ref const typeof(this) b) const pure @nogc nothrow @safe {
return _value == b._value;
}
ObjectPath opBinary(string op : "~")(string rhs) const pure @safe {
if (!rhs.startsWith("/"))
return opBinary!"~"(ObjectPath("/" ~ rhs));
else
return opBinary!"~"(ObjectPath(rhs));
}
ObjectPath opBinary(string op : "~")(ObjectPath rhs) const pure @safe
in {
assert(ObjectPath.isValid(_value) && ObjectPath.isValid(rhs._value));
} out (v) {
assert(ObjectPath.isValid(v._value));
} do {
ObjectPath ret;
if (_value == "/")
ret._value = rhs._value;
else
ret._value = _value ~ rhs._value;
return ret;
}
void opOpAssign(string op : "~")(string rhs) pure @safe {
_value = opBinary!"~"(rhs)._value;
}
void opOpAssign(string op : "~")(ObjectPath rhs) pure @safe {
_value = opBinary!"~"(rhs)._value;
}
/++
Returns: `false` for empty strings or strings that don't match the
pattern `(/[0-9A-Za-z_]+)+|/`.
+/
static bool isValid(string objPath) pure @nogc nothrow @safe {
import std.ascii : isAlphaNum;
if (!objPath.length)
return false;
if (objPath == "/")
return true;
if (objPath[0] != '/' || objPath[$ - 1] == '/')
return false;
// .representation to avoid unicode exceptions -> @nogc & nothrow
return objPath.representation.splitter('/').drop(1)
.all!(a =>
a.length &&
a.all!(c =>
c.isAlphaNum || c == '_'
)
);
}
}
/// Structure allowing typeless parameters
struct DBusAny {
/// DBus type of the value (never 'v'), see typeSig!T
int type;
/// Child signature for Arrays & Tuples
string signature;
/// If true, this value will get serialized as variant value, otherwise it is serialized like it wasn't in a DBusAny wrapper.
/// Same functionality as Variant!T but with dynamic types if true.
bool explicitVariant;
union
{
///
byte int8;
///
short int16;
///
ushort uint16;
///
int int32;
///
uint uint32;
///
long int64;
///
ulong uint64;
///
double float64;
///
string str;
///
bool boolean;
///
ObjectPath obj;
///
DBusAny[] array;
///
alias tuple = array;
///
DictionaryEntry!(DBusAny, DBusAny)* entry;
///
ubyte[] binaryData;
}
/// Manually creates a DBusAny object using a type, signature and implicit specifier.
this(int type, string signature, bool explicit) {
this.type = type;
this.signature = signature;
this.explicitVariant = explicit;
}
/// Automatically creates a DBusAny object with fitting parameters from a D type or Variant!T.
/// Pass a `Variant!T` to make this an explicit variant.
this(T)(T value) {
static if(is(T == byte) || is(T == ubyte)) {
this(typeCode!byte, null, false);
int8 = cast(byte) value;
} else static if(is(T == short)) {
this(typeCode!short, null, false);
int16 = cast(short) value;
} else static if(is(T == ushort)) {
this(typeCode!ushort, null, false);
uint16 = cast(ushort) value;
} else static if(is(T == int)) {
this(typeCode!int, null, false);
int32 = cast(int) value;
} else static if(is(T == uint)) {
this(typeCode!uint, null, false);
uint32 = cast(uint) value;
} else static if(is(T == long)) {
this(typeCode!long, null, false);
int64 = cast(long) value;
} else static if(is(T == ulong)) {
this(typeCode!ulong, null, false);
uint64 = cast(ulong) value;
} else static if(is(T == double)) {
this(typeCode!double, null, false);
float64 = cast(double) value;
} else static if(isSomeString!T) {
this(typeCode!string, null, false);
str = value.to!string;
} else static if(is(T == bool)) {
this(typeCode!bool, null, false);
boolean = cast(bool) value;
} else static if(is(T == ObjectPath)) {
this(typeCode!ObjectPath, null, false);
obj = value;
} else static if(is(T == Variant!R, R)) {
static if(is(R == DBusAny)) {
type = value.data.type;
signature = value.data.signature;
explicitVariant = true;
if(type == 'a' || type == 'r') {
if(signature == ['y'])
binaryData = value.data.binaryData;
else
array = value.data.array;
} else if(type == 's')
str = value.data.str;
else if(type == 'e')
entry = value.data.entry;
else
uint64 = value.data.uint64;
} else {
this(value.data);
explicitVariant = true;
}
} else static if(is(T : DictionaryEntry!(K, V), K, V)) {
this('e', null, false);
entry = new DictionaryEntry!(DBusAny, DBusAny)();
static if(is(K == DBusAny))
entry.key = value.key;
else
entry.key = DBusAny(value.key);
static if(is(V == DBusAny))
entry.value = value.value;
else
entry.value = DBusAny(value.value);
} else static if(is(T == ubyte[]) || is(T == byte[])) {
this('a', ['y'], false);
binaryData = cast(ubyte[]) value;
} else static if(isInputRange!T) {
this.type = 'a';
static assert(!is(ElementType!T == DBusAny), "Array must consist of the same type, use Variant!DBusAny or DBusAny(tuple(...)) instead");
static assert(.typeSig!(ElementType!T) != "y");
this.signature = .typeSig!(ElementType!T);
this.explicitVariant = false;
foreach(elem; value)
array ~= DBusAny(elem);
} else static if(isTuple!T) {
this.type = 'r';
this.signature = ['('];
this.explicitVariant = false;
foreach(index, R; value.Types) {
auto var = DBusAny(value[index]);
tuple ~= var;
if(var.explicitVariant)
this.signature ~= 'v';
else {
if (var.type != 'r')
this.signature ~= cast(char) var.type;
if(var.type == 'a' || var.type == 'r')
this.signature ~= var.signature;
}
}
this.signature ~= ')';
} else static if(isAssociativeArray!T) {
this(value.byDictionaryEntries);
} else static assert(false, T.stringof ~ " not convertible to a Variant");
}
///
string toString() const {
string valueStr;
switch(type) {
case typeCode!byte:
valueStr = int8.to!string;
break;
case typeCode!short:
valueStr = int16.to!string;
break;
case typeCode!ushort:
valueStr = uint16.to!string;
break;
case typeCode!int:
valueStr = int32.to!string;
break;
case typeCode!uint:
valueStr = uint32.to!string;
break;
case typeCode!long:
valueStr = int64.to!string;
break;
case typeCode!ulong:
valueStr = uint64.to!string;
break;
case typeCode!double:
valueStr = float64.to!string;
break;
case typeCode!string:
valueStr = '"' ~ str ~ '"';
break;
case typeCode!ObjectPath:
valueStr = '"' ~ obj.to!string ~ '"';
break;
case typeCode!bool:
valueStr = boolean ? "true" : "false";
break;
case 'a':
import std.digest : toHexString;
if(signature == ['y'])
valueStr = "binary(" ~ binaryData.toHexString ~ ')';
else
valueStr = '[' ~ array.map!(a => a.toString).join(", ") ~ ']';
break;
case 'r':
valueStr = '(' ~ tuple.map!(a => a.toString).join(", ") ~ ')';
break;
case 'e':
valueStr = entry.key.toString ~ ": " ~ entry.value.toString;
break;
default:
valueStr = "unknown";
break;
}
return "DBusAny(" ~ cast(char) type
~ ", \"" ~ signature.idup
~ "\", " ~ (explicitVariant ? "explicit" : "implicit")
~ ", " ~ valueStr ~ ")";
}
/++
Get the value stored in the DBusAny object.
Parameters:
T = The requested type. The currently stored value must match the
requested type exactly.
Returns:
The current value of the DBusAny object.
Throws:
TypeMismatchException if the DBus type of the current value of the
DBusAny object is not the same as the DBus type used to represent T.
+/
T get(T)() @property const
if(staticIndexOf!(T, BasicTypes) >= 0)
{
enforce(type == typeCode!T,
new TypeMismatchException(
"Cannot get a " ~ T.stringof ~ " from a DBusAny with"
~ " a value of DBus type '" ~ typeSig ~ "'.", typeCode!T, type));
static if(isIntegral!T) {
enum memberName =
(isUnsigned!T ? "uint" : "int") ~ (T.sizeof * 8).to!string;
return __traits(getMember, this, memberName);
} else static if(is(T == double)) {
return float64;
} else static if(is(T == string)) {
return str;
} else static if(is(T == ObjectPath)) {
return obj;
} else static if(is(T == bool)) {
return boolean;
} else {
static assert(false);
}
}
/// ditto
T get(T)() @property const
if(is(T == const(DBusAny)[]))
{
enforce((type == 'a' && signature != "y") || type == 'r',
new TypeMismatchException(
"Cannot get a " ~ T.stringof ~ " from a DBusAny with"
~ " a value of DBus type '" ~ this.typeSig ~ "'.",
typeCode!T, type));
return array;
}
/// ditto
T get(T)() @property const
if (is(T == const(ubyte)[]))
{
enforce(type == 'a' && signature == "y",
new TypeMismatchException(
"Cannot get a " ~ T.stringof ~ " from a DBusAny with"
~ " a value of DBus type '" ~ this.typeSig ~ "'.",
typeCode!T, type));
return binaryData;
}
/// If the value is an array of DictionaryEntries this will return a HashMap
DBusAny[DBusAny] toAA() {
enforce(type == 'a' && signature && signature[0] == '{');
DBusAny[DBusAny] aa;
foreach(val; array) {
enforce(val.type == 'e');
aa[val.entry.key] = val.entry.value;
}
return aa;
}
/++
Get the DBus type signature of the value stored in the DBusAny object.
Returns:
The type signature of the value stored in this DBusAny object.
+/
string typeSig() @property const pure nothrow @safe
{
if(type == 'a') {
return "a" ~ signature;
} else if(type == 'r') {
return signature;
} else if(type == 'e') {
return () @trusted {
return "{" ~ entry.key.signature ~ entry.value.signature ~ "}";
} ();
} else {
return [ cast(char) type ];
}
}
/// Converts a basic type, a tuple or an array to the D type with type checking. Tuples can get converted to an array too.
T to(T)() {
static if(is(T == Variant!R, R)) {
static if(is(R == DBusAny)) {
auto v = to!R;
v.explicitVariant = false;
return Variant!R(v);
} else
return Variant!R(to!R);
} else static if(is(T == DBusAny)) {
return this;
} else static if(isIntegral!T || isFloatingPoint!T) {
switch(type) {
case typeCode!byte:
return cast(T) int8;
case typeCode!short:
return cast(T) int16;
case typeCode!ushort:
return cast(T) uint16;
case typeCode!int:
return cast(T) int32;
case typeCode!uint:
return cast(T) uint32;
case typeCode!long:
return cast(T) int64;
case typeCode!ulong:
return cast(T) uint64;
case typeCode!double:
return cast(T) float64;
default:
throw new Exception("Can't convert type " ~ cast(char) type ~ " to " ~ T.stringof);
}
} else static if(is(T == bool)) {
if(type == 'b')
return boolean;
else
throw new Exception("Can't convert type " ~ cast(char) type ~ " to " ~ T.stringof);
} else static if(isSomeString!T) {
if(type == 's')
return str.to!T;
else if(type == 'o')
return obj.toString();
else
throw new Exception("Can't convert type " ~ cast(char) type ~ " to " ~ T.stringof);
} else static if(is(T == ObjectPath)) {
if(type == 'o')
return obj;
else
throw new Exception("Can't convert type " ~ cast(char) type ~ " to " ~ T.stringof);
} else static if(isDynamicArray!T) {
if(type != 'a' && type != 'r')
throw new Exception("Can't convert type " ~ cast(char) type ~ " to an array");
T ret;
if(signature == ['y']) {
static if(isIntegral!(ElementType!T))
foreach(elem; binaryData)
ret ~= elem.to!(ElementType!T);
} else
foreach(elem; array)
ret ~= elem.to!(ElementType!T);
return ret;
} else static if(isTuple!T) {
if(type != 'r')
throw new Exception("Can't convert type " ~ cast(char) type ~ " to " ~ T.stringof);
T ret;
enforce(ret.Types.length == tuple.length, "Tuple length mismatch");
foreach(index, T; ret.Types)
ret[index] = tuple[index].to!T;
return ret;
} else static if(isAssociativeArray!T) {
if(type != 'a' || !signature || signature[0] != '{')
throw new Exception("Can't convert type " ~ cast(char) type ~ " to " ~ T.stringof);
T ret;
foreach(pair; array) {
enforce(pair.type == 'e');
ret[pair.entry.key.to!(KeyType!T)] = pair.entry.value.to!(ValueType!T);
}
return ret;
} else static assert(false, "Can't convert variant to " ~ T.stringof);
}
bool opEquals(ref in DBusAny b) const {
if(b.type != type || b.explicitVariant != explicitVariant)
return false;
if((type == 'a' || type == 'r') && b.signature != signature)
return false;
if(type == 'a' && signature == ['y'])
return binaryData == b.binaryData;
if(type == 'a')
return array == b.array;
else if(type == 'r')
return tuple == b.tuple;
else if(type == 's')
return str == b.str;
else if(type == 'o')
return obj == b.obj;
else if(type == 'e')
return entry == b.entry || (entry && b.entry && *entry == *b.entry);
else
return uint64 == b.uint64;
}
}
/// Marks the data as variant on serialization
struct Variant(T) {
///
T data;
}
Variant!T variant(T)(T data) {
return Variant!T(data);
}
enum MessageType {
Invalid = 0,
Call, Return, Error, Signal
}
void emitSignal(Args...)(Connection conn, string path, string iface, string name, Args args) {
Message msg = Message(null, path, iface, name, true);
msg.build(args);
conn.send(msg);
}
struct Message {
DBusMessage *msg;
this(string dest, string path, string iface, string method, bool signal = false) {
if(signal)
msg = dbus_message_new_signal(path.toStringz(), iface.toStringz(), method.toStringz());
else
msg = dbus_message_new_method_call(dest.toStringz(), path.toStringz(), iface.toStringz(), method.toStringz());
}
this(DBusMessage *m) {
msg = m;
}
this(this) {
dbus_message_ref(msg);
}
~this() {
dbus_message_unref(msg);
}
void build(TS...)(TS args) if(allCanDBus!TS) {
DBusMessageIter iter;
dbus_message_iter_init_append(msg, &iter);
buildIter(&iter, args);
}
/**
Reads the first argument of the message.
Note that this creates a new iterator every time so calling it multiple times will always
read the first argument. This is suitable for single item returns.
To read multiple arguments use readTuple.
*/
T read(T)() if(canDBus!T) {
DBusMessageIter iter;
dbus_message_iter_init(msg, &iter);
return readIter!T(&iter);
}
alias read to;
Tup readTuple(Tup)() if(isTuple!Tup && allCanDBus!(Tup.Types)) {
DBusMessageIter iter;
dbus_message_iter_init(msg, &iter);
Tup ret;
readIterTuple(&iter, ret);
return ret;
}
Message createReturn() {
return Message(dbus_message_new_method_return(msg));
}
MessageType type() {
return cast(MessageType)dbus_message_get_type(msg);
}
bool isCall() {
return type() == MessageType.Call;
}
// Various string members
// TODO: make a mixin to avoid this copy-paste
string signature() {
const(char)* cStr = dbus_message_get_signature(msg);
assert(cStr != null);
return cStr.fromStringz().idup;
}
string path() {
const(char)* cStr = dbus_message_get_path(msg);
assert(cStr != null);
return cStr.fromStringz().idup;
}
string iface() {
const(char)* cStr = dbus_message_get_interface(msg);
assert(cStr != null);
return cStr.fromStringz().idup;
}
string member() {
const(char)* cStr = dbus_message_get_member(msg);
assert(cStr != null);
return cStr.fromStringz().idup;
}
string sender() {
const(char)* cStr = dbus_message_get_sender(msg);
assert(cStr != null);
return cStr.fromStringz().idup;
}
}
struct Connection {
DBusConnection *conn;
this(DBusConnection *connection) {
conn = connection;
}
this(this) {
dbus_connection_ref(conn);
}
~this() {
dbus_connection_unref(conn);
}
void close() {
dbus_connection_close(conn);
}
void send(Message msg) {
dbus_connection_send(conn,msg.msg, null);
}
void sendBlocking(Message msg) {
send(msg);
dbus_connection_flush(conn);
}
Message sendWithReplyBlocking(Message msg, int timeout = -1) {
DBusMessage *dbusMsg = msg.msg;
dbus_message_ref(dbusMsg);
DBusMessage *reply = wrapErrors((err) {
auto ret = dbus_connection_send_with_reply_and_block(conn,dbusMsg,timeout,err);
dbus_message_unref(dbusMsg);
return ret;
});
return Message(reply);
}
Message sendWithReplyBlocking(Message msg, Duration timeout) {
return sendWithReplyBlocking(msg, timeout.total!"msecs"().to!int);
}
}
Connection connectToBus(DBusBusType bus = DBusBusType.DBUS_BUS_SESSION) {
DBusConnection *conn = wrapErrors((err) { return dbus_bus_get(bus,err); });
return Connection(conn);
}
class PathIface {
this(Connection conn, string dest, ObjectPath path, string iface) {
this(conn, dest, path.value, iface);
}
this(Connection conn, string dest, string path, string iface) {
this.conn = conn;
this.dest = dest.toStringz();
this.path = path.toStringz();
this.iface = iface.toStringz();
}
Ret call(Ret, Args...)(string meth, Args args) if(allCanDBus!Args && canDBus!Ret) {
Message msg = Message(dbus_message_new_method_call(dest,path,iface,meth.toStringz()));
msg.build(args);
Message ret = conn.sendWithReplyBlocking(msg);
return ret.read!Ret();
}
Message opDispatch(string meth, Args...)(Args args) {
Message msg = Message(dbus_message_new_method_call(dest,path,iface,meth.toStringz()));
msg.build(args);
return conn.sendWithReplyBlocking(msg);
}
Connection conn;
const(char)* dest;
const(char)* path;
const(char)* iface;
}
enum SignalMethod;
/**
Registers all *possible* methods of an object in a router.
It will not register methods that use types that ddbus can't handle.
The implementation is rather hacky and uses the compiles trait to check for things
working so if some methods randomly don't seem to be added, you should probably use
setHandler on the router directly. It is also not efficient and creates a closure for every method.
TODO: replace this with something that generates a wrapper class who's methods take and return messages
and basically do what MessageRouter.setHandler does but avoiding duplication. Then this DBusWrapper!Class
could be instantiated with any object efficiently and placed in the router table with minimal duplication.
*/
void registerMethods(T : Object)(MessageRouter router, string path, string iface, T obj) {
MessagePattern patt = MessagePattern(path,iface,"",false);
foreach(member; __traits(allMembers, T)) {
static if (__traits(compiles, __traits(getOverloads, obj, member))
&& __traits(getOverloads, obj, member).length > 0
&& __traits(compiles, router.setHandler(patt, &__traits(getOverloads,obj,member)[0]))) {
patt.method = member;
patt.signal = hasUDA!(__traits(getOverloads,obj,member)[0], SignalMethod);
router.setHandler(patt, &__traits(getOverloads,obj,member)[0]);
}
}
}
struct MessagePattern {
string path;
string iface;
string method;
bool signal;
this(Message msg) {
path = msg.path();
iface = msg.iface();
method = msg.member();
signal = (msg.type() == MessageType.Signal);
}
this(string path, string iface, string method, bool signal = false) {
this.path = path;
this.iface = iface;
this.method = method;
this.signal = signal;
}
size_t toHash() const @safe nothrow {
size_t hash = 0;
auto stringHash = &(typeid(path).getHash);
hash += stringHash(&path);
hash += stringHash(&iface);
hash += stringHash(&method);