atspi-common 0.9.0

Primitive types used for sending and receiving Linux accessibility events.
Documentation
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
use crate::AtspiError;
use serde::{
	ser::{SerializeMap, SerializeStruct},
	Deserialize, Serialize,
};
use zbus_lockstep_macros::validate;
use zvariant::{ObjectPath, OwnedValue, Type, Value};

/// Event body as used exclusively by 'Qt' toolkit.
///
/// Signature:  "siiv(so)"
#[derive(Debug, Serialize, Deserialize, PartialEq, Type)]
pub struct EventBodyQtOwned {
	/// kind variant, used for specifying an event triple "object:state-changed:focused",
	/// the "focus" part of this event is what is contained within the kind.
	#[serde(rename = "type")]
	pub kind: String,

	/// Generic detail1 value described by AT-SPI.
	pub detail1: i32,

	/// Generic detail2 value described by AT-SPI.
	pub detail2: i32,

	/// Generic `any_data` value described by AT-SPI.
	/// This can be any type.
	pub any_data: OwnedValue,

	/// Not in use.
	/// See: [`QtProperties`].
	#[serde(skip_deserializing)]
	pub(crate) properties: QtProperties,
}

impl Clone for EventBodyQtOwned {
	/// # Safety  
	///
	/// This implementation of [`Clone`] *can panic!* although chances are slim.
	///
	/// If the following conditions are met:
	/// 1. the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and
	/// 2. the maximum number of open files for the process is exceeded.
	///
	/// Then this function panic.  
	/// None of the types in [`crate::events`] use [`std::os::fd::OwnedFd`].
	/// Events on the AT-SPI bus *could, theoretically* send a file descriptor, but nothing in the current
	/// specification describes that.  
	/// See [`zvariant::Value::try_clone`] for more information.
	fn clone(&self) -> Self {
		let cloned_any_data = self.any_data.try_clone().unwrap_or_else(|err| {
			panic!("Failure cloning 'any_data' field: {err:?}");
		});

		Self {
			kind: self.kind.clone(),
			detail1: self.detail1,
			detail2: self.detail2,
			any_data: cloned_any_data,
			properties: QtProperties,
		}
	}
}

/// Unit struct placeholder for `EventBodyQtOwned.properties`
///
/// AT-SPI2 never reads or writes to `properties`.  
/// `QtProperties` has the appropriate implementations for `Serialize` and `Deserialize`  
/// to make it serialize as an a valid tuple and valid bytes deserialize as placeholder.
#[derive(Debug, Copy, Clone, Deserialize, Type, Default, PartialEq)]
#[zvariant(signature = "(so)")]
pub(crate) struct QtProperties;

impl Serialize for QtProperties {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::ser::Serializer,
	{
		let mut structure = serializer.serialize_struct("ObjectRef", 2)?;
		structure.serialize_field("name", ":0.0")?;
		structure.serialize_field("path", &ObjectPath::from_static_str_unchecked("/"))?;
		structure.end()
	}
}

impl Default for EventBodyQtOwned {
	fn default() -> Self {
		Self {
			kind: String::new(),
			detail1: 0,
			detail2: 0,
			any_data: 0_u32.into(),
			properties: QtProperties,
		}
	}
}

/// Unit struct placeholder for `EventBody.properties`
///
/// AT-SPI2 never reads or writes to `EventBody.properties`.  
/// `Properties` has the appropriate implementations for `Serialize` and `Deserialize`  
/// to make it serialize as an a valid dictionary and valid bytes deserialize as placeholder.
#[derive(Debug, Copy, Clone, Type, Default, Deserialize, PartialEq)]
#[zvariant(signature = "a{sv}")]
pub(crate) struct Properties;

impl Serialize for Properties {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::ser::Serializer,
	{
		serializer.serialize_map(Some(0))?.end()
	}
}

/// AT-SPI2 protocol native event body type.
///
/// All of the various signals in the AT-SPI2 protocol share this shape.
/// Most toolkits and implementors emit this type, except for `Qt`, which has has its
/// own type: [`EventBodyQtOwned`].
///
/// Signature `(siiva{sv})`,
#[validate(signal: "PropertyChange")]
#[derive(Debug, Serialize, Deserialize, PartialEq, Type)]
pub struct EventBodyOwned {
	/// kind variant, used for specifying an event triple "object:state-changed:focused",
	/// the "focus" part of this event is what is contained within the kind.
	#[serde(rename = "type")]
	pub kind: String,

	/// Generic detail1 value described by AT-SPI.
	pub detail1: i32,

	/// Generic detail2 value described by AT-SPI.
	pub detail2: i32,

	/// Generic `any_data` value described by AT-SPI.
	/// This can be any type.
	///
	pub any_data: OwnedValue,

	/// Not in use.
	/// See: [`Properties`].
	pub(crate) properties: Properties,
}

impl Default for EventBodyOwned {
	fn default() -> Self {
		Self {
			kind: String::new(),
			detail1: 0,
			detail2: 0,
			any_data: 0_u32.into(),
			properties: Properties,
		}
	}
}

impl Clone for EventBodyOwned {
	/// # Safety  
	///
	/// This implementation of [`Clone`] *can panic!* although chances are slim.
	///
	/// If the following conditions are met:
	/// 1. the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and
	/// 2. the maximum number of open files for the process is exceeded.
	///
	/// Then this function panic.  
	/// None of the types in [`crate::events`] use [`std::os::fd::OwnedFd`].
	/// Events on the AT-SPI bus *could, theoretically* send a file descriptor, but nothing in the current
	/// specification describes that.  
	/// See [`zvariant::Value::try_clone`] for more information.
	fn clone(&self) -> Self {
		let cloned_any_data = self.any_data.try_clone().unwrap_or_else(|err| {
			panic!("Failure cloning 'any_data' field: {err:?}");
		});

		Self {
			kind: self.kind.clone(),
			detail1: self.detail1,
			detail2: self.detail2,
			any_data: cloned_any_data,
			properties: Properties,
		}
	}
}

#[derive(Debug, Serialize, Deserialize, PartialEq, Type)]
pub struct EventBodyBorrowed<'a> {
	/// kind variant, used for specifying an event triple "object:state-changed:focused",
	/// the "focus" part of this event is what is contained within the kind.
	#[serde(rename = "type")]
	#[serde(borrow)]
	pub kind: &'a str,

	/// Generic detail1 value described by AT-SPI.
	pub detail1: i32,

	/// Generic detail2 value described by AT-SPI.
	pub detail2: i32,

	/// Generic `any_data` value described by AT-SPI.
	/// This can be any type.
	#[serde(borrow)]
	pub any_data: Value<'a>,

	/// Not in use.
	/// See: [`Properties`].
	#[serde(skip_deserializing)]
	pub(crate) properties: Properties,
}

impl Default for EventBodyBorrowed<'_> {
	fn default() -> Self {
		Self {
			kind: "",
			detail1: 0,
			detail2: 0,
			any_data: Value::new(0_u32),
			properties: Properties,
		}
	}
}

impl EventBodyBorrowed<'_> {
	/// Convert this borrowed event body to an owned event body.
	///
	/// # Errors
	///
	/// This will error if the following conditions are met:
	/// 1. the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and
	/// 2. the maximum number of open files for the process is exceeded.
	///
	/// Chances are slim because none of the types in [`crate::events`] use [`std::os::fd::OwnedFd`].  
	/// See [`zvariant::Value::try_clone`] for more information.
	pub fn to_fully_owned(&self) -> Result<EventBodyOwned, AtspiError> {
		let owned_any_data = self.any_data.try_to_owned()?;

		Ok(EventBodyOwned {
			kind: self.kind.into(),
			detail1: self.detail1,
			detail2: self.detail2,
			any_data: owned_any_data,
			properties: Properties,
		})
	}
}

impl Clone for EventBodyBorrowed<'_> {
	/// # Safety  
	///
	/// This implementation of [`Clone`] *can panic!* although chances are slim.
	///
	/// If the following conditions are met:
	/// 1. the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and  
	/// 2. the maximum number of open files for the process is exceeded.
	///
	/// Then this function panic.  
	/// None of the types in [`crate::events`] use [`std::os::fd::OwnedFd`].
	/// Events on the AT-SPI bus *could, theoretically* send a file descriptor, but nothing in the current
	/// specification describes that.  
	/// See [`zvariant::Value::try_clone`] for more information.
	fn clone(&self) -> Self {
		let cloned_any_data = self.any_data.try_clone().unwrap_or_else(|err| {
			panic!("Failure cloning 'any_data' field: {err:?}");
		});

		Self {
			kind: self.kind,
			detail1: self.detail1,
			detail2: self.detail2,
			any_data: cloned_any_data,
			properties: Properties,
		}
	}
}

#[derive(Debug, Type, Deserialize, PartialEq)]
pub struct EventBodyQtBorrowed<'m> {
	/// kind variant, used for specifying an event triple "object:state-changed:focused",
	/// the "focus" part of this event is what is contained within the kind.
	#[serde(rename = "type")]
	pub kind: &'m str,

	/// Generic detail1 value described by AT-SPI.
	pub detail1: i32,

	/// Generic detail2 value described by AT-SPI.
	pub detail2: i32,

	/// Generic `any_data` value described by AT-SPI.
	/// This can be any type.
	#[serde(borrow)]
	pub any_data: Value<'m>,

	/// Not in use.
	/// See: [`QtProperties`].
	#[serde(skip_deserializing)]
	pub(crate) properties: QtProperties,
}

impl Default for EventBodyQtBorrowed<'_> {
	fn default() -> Self {
		Self {
			kind: "",
			detail1: 0,
			detail2: 0,
			any_data: Value::new(0_u32),
			properties: QtProperties,
		}
	}
}

impl Clone for EventBodyQtBorrowed<'_> {
	/// # Safety  
	///
	/// This implementation of [`Clone`] *can panic!* although chances are slim.
	///
	/// If the following conditions are met:
	/// 1. the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and
	/// 2. the maximum number of open files for the process is exceeded.
	///
	/// Then this function panics.  
	/// None of the types in [`crate::events`] use [`std::os::fd::OwnedFd`].
	/// Events on the AT-SPI bus *could, theoretically* send a file descriptor, but nothing in the current
	/// specification describes that.  
	/// See [`zvariant::Value::try_clone`] for more information.
	fn clone(&self) -> Self {
		let cloned_any_data = self.any_data.try_clone().unwrap_or_else(|err| {
			panic!("Failure cloning 'any_data' field: {err:?}");
		});

		Self {
			kind: self.kind,
			detail1: self.detail1,
			detail2: self.detail2,
			any_data: cloned_any_data,
			properties: QtProperties,
		}
	}
}

impl EventBodyQtBorrowed<'_> {
	/// Convert partially borrowed Qt event body to an owned event body.
	///
	/// # Errors
	///
	/// This will error if the following conditions are met:
	/// 1. the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and
	/// 2. the maximum number of open files for the process is exceeded.
	pub fn try_to_owned(&self) -> Result<EventBodyQtOwned, AtspiError> {
		let any_data = self.any_data.try_to_owned()?;

		Ok(EventBodyQtOwned {
			kind: self.kind.to_owned(),
			detail1: self.detail1,
			detail2: self.detail2,
			any_data,
			properties: self.properties,
		})
	}
}

impl<'de> From<EventBodyQtBorrowed<'de>> for EventBodyBorrowed<'de> {
	fn from(borrow: EventBodyQtBorrowed<'de>) -> Self {
		let EventBodyQtBorrowed { kind, detail1, detail2, any_data, properties: _ } = borrow;

		Self { kind, detail1, detail2, any_data, properties: Properties }
	}
}

impl From<EventBodyQtOwned> for EventBodyOwned {
	fn from(body: EventBodyQtOwned) -> Self {
		Self {
			kind: body.kind,
			detail1: body.detail1,
			detail2: body.detail2,
			any_data: body.any_data,
			properties: Properties,
		}
	}
}

/// Common event body that can be either owned or borrowed.
///
/// This is useful for APIs that can return either owned or borrowed event bodies.  
/// Having this type allows to be generic over the event body type.
#[derive(Debug, Clone, PartialEq)]
pub enum EventBody<'a> {
	Owned(EventBodyOwned),
	Borrowed(EventBodyBorrowed<'a>),
}

impl Default for EventBody<'_> {
	fn default() -> Self {
		Self::Borrowed(EventBodyBorrowed::default())
	}
}

impl<'a> EventBody<'_> {
	/// Non-consuming conversion to an owned event body.
	///
	/// Does cloning.
	///
	/// # Errors
	/// The borrowed variant will error if the following conditions are met:  
	/// 1. the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and  
	/// 2. the maximum number of open files for the process is exceeded.
	pub fn as_owned(&self) -> Result<EventBodyOwned, AtspiError> {
		match self {
			Self::Owned(owned) => Ok(owned.clone()),
			Self::Borrowed(borrowed) => borrowed.to_fully_owned(),
		}
	}

	/// Consuming conversion to an owned event body.
	///
	/// Does cloning.
	///
	/// # Errors
	/// The borrowed variant will error if the following conditions are met:  
	/// 1. the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and  
	/// 2. the maximum number of open files for the process is exceeded.
	pub fn into_owned(self) -> Result<EventBodyOwned, AtspiError> {
		match self {
			Self::Owned(owned) => Ok(owned),
			Self::Borrowed(borrowed) => borrowed.to_fully_owned(),
		}
	}

	/// The `kind` field as `&str`.
	///
	/// With both variants, this method returns a reference to the `kind` field.
	#[must_use]
	pub fn kind(&'a self) -> &'a str {
		match self {
			Self::Owned(owned) => owned.kind.as_str(),
			Self::Borrowed(borrowed) => borrowed.kind,
		}
	}

	/// Take or convert the `kind` field as `String`.
	///
	/// With the owned variant, this method takes the `kind` field and replaces it with an empty string.
	/// With the borrowed variant, this method clones and allocates the `kind` field.
	pub fn take_kind(&mut self) -> String {
		match self {
			Self::Owned(owned) => std::mem::take(&mut owned.kind),
			Self::Borrowed(borrowed) => borrowed.kind.to_owned(),
		}
	}

	#[must_use]
	pub fn detail1(&self) -> i32 {
		match self {
			Self::Owned(owned) => owned.detail1,
			Self::Borrowed(borrowed) => borrowed.detail1,
		}
	}

	#[must_use]
	pub fn detail2(&self) -> i32 {
		match self {
			Self::Owned(owned) => owned.detail2,
			Self::Borrowed(borrowed) => borrowed.detail2,
		}
	}

	/// The `any_data` field as `&Value`.
	/// With both variants, this method returns a reference to the `any_data` field.
	#[must_use]
	pub fn any_data(&'a self) -> &'a Value<'a> {
		match self {
			Self::Owned(owned) => &owned.any_data,
			Self::Borrowed(borrowed) => &borrowed.any_data,
		}
	}

	/// Take or convert the `any_data` field as `OwnedValue`.
	/// With the owned variant, this method takes the `any_data` field and replaces it with a default value.
	/// As `Value` does not have a default value, we will replace with `0_u32`, a nbon-allocating value.
	///
	/// With the borrowed variant, this method clones and allocates the `any_data` field.
	///
	/// # Panics
	/// This method will panic if the `any_data` field contains an [`std::os::fd::OwnedFd`] type, and
	/// the maximum number of open files for the process is exceeded.
	///
	/// None of the types in [`crate::events`] use [`std::os::fd::OwnedFd`].
	/// Events on the AT-SPI bus *could, theoretically* send a file descriptor, but nothing in the current
	/// specification describes that.
	pub fn take_any_data(&mut self) -> OwnedValue {
		match self {
			Self::Owned(owned) => std::mem::replace(&mut owned.any_data, 0_u32.into()),
			Self::Borrowed(borrowed) => borrowed.any_data.try_to_owned().expect("cloning 'any_data' field should not fail because we do not expect it to hold an fd"),
		}
	}
}

impl Type for EventBody<'_> {
	const SIGNATURE: &'static zvariant::Signature = EventBodyOwned::SIGNATURE;
}

impl<'de> Deserialize<'de> for EventBody<'de> {
	fn deserialize<D>(deserializer: D) -> Result<EventBody<'de>, D::Error>
	where
		D: serde::de::Deserializer<'de>,
	{
		let borrowed = EventBodyBorrowed::deserialize(deserializer)?;
		Ok(borrowed.into())
	}
}

impl Serialize for EventBody<'_> {
	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
	where
		S: serde::ser::Serializer,
	{
		match self {
			EventBody::Owned(owned) => owned.serialize(serializer),
			EventBody::Borrowed(borrowed) => borrowed.serialize(serializer),
		}
	}
}

impl From<EventBodyOwned> for EventBody<'_> {
	fn from(owned: EventBodyOwned) -> Self {
		EventBody::Owned(owned)
	}
}

impl<'b> From<EventBodyBorrowed<'b>> for EventBody<'b> {
	fn from(borrowed: EventBodyBorrowed<'b>) -> Self {
		EventBody::Borrowed(borrowed)
	}
}

impl From<EventBodyQtOwned> for EventBody<'_> {
	fn from(qt_owned: EventBodyQtOwned) -> Self {
		EventBody::Owned(qt_owned.into())
	}
}

impl<'a> From<EventBodyQtBorrowed<'a>> for EventBody<'a> {
	fn from(qt_borrowed: EventBodyQtBorrowed<'a>) -> Self {
		EventBody::Borrowed(qt_borrowed.into())
	}
}

impl From<EventBodyOwned> for EventBodyQtOwned {
	fn from(owned: EventBodyOwned) -> Self {
		Self {
			kind: owned.kind,
			detail1: owned.detail1,
			detail2: owned.detail2,
			any_data: owned.any_data,
			properties: QtProperties,
		}
	}
}

impl<'a> From<EventBodyBorrowed<'a>> for EventBodyQtOwned {
	fn from(borrowed: EventBodyBorrowed<'a>) -> Self {
		Self {
			kind: borrowed.kind.to_owned(),
			detail1: borrowed.detail1,
			detail2: borrowed.detail2,
			any_data: borrowed
				.any_data
				.try_to_owned()
				.expect("converting borrowed to owned should not fail"),
			properties: QtProperties,
		}
	}
}

impl From<EventBody<'_>> for EventBodyQtOwned {
	fn from(event: EventBody) -> Self {
		match event {
			EventBody::Owned(owned) => owned.into(),
			EventBody::Borrowed(borrowed) => borrowed.into(),
		}
	}
}

impl PartialEq<EventBodyOwned> for EventBodyQtOwned {
	fn eq(&self, other: &EventBodyOwned) -> bool {
		self.kind == other.kind
			&& self.detail1 == other.detail1
			&& self.detail2 == other.detail2
			&& self.any_data == other.any_data
	}
}

impl PartialEq<EventBodyQtOwned> for EventBodyOwned {
	fn eq(&self, other: &EventBodyQtOwned) -> bool {
		self.kind == other.kind
			&& self.detail1 == other.detail1
			&& self.detail2 == other.detail2
			&& self.any_data == other.any_data
	}
}

impl PartialEq<EventBodyBorrowed<'_>> for EventBodyQtBorrowed<'_> {
	fn eq(&self, other: &EventBodyBorrowed<'_>) -> bool {
		self.kind == other.kind
			&& self.detail1 == other.detail1
			&& self.detail2 == other.detail2
			&& self.any_data == other.any_data
	}
}

impl PartialEq<EventBodyQtBorrowed<'_>> for EventBodyBorrowed<'_> {
	fn eq(&self, other: &EventBodyQtBorrowed<'_>) -> bool {
		self.kind == other.kind
			&& self.detail1 == other.detail1
			&& self.detail2 == other.detail2
			&& self.any_data == other.any_data
	}
}

#[cfg(test)]
mod test {
	use super::*;
	use crate::ObjectRef;
	use std::collections::HashMap;
	use zvariant::{serialized::Context, LE};
	use zvariant::{Array, ObjectPath, Value};

	#[test]
	fn owned_event_body_clone() {
		let event = EventBodyOwned::default();
		let cloned = event.clone();

		assert_eq!(event, cloned);
	}

	#[test]
	fn event_body_qt_clone() {
		let event = EventBodyQtOwned::default();
		let cloned = event.clone();

		assert_eq!(event, cloned);
	}

	#[test]
	fn event_body_borrowed_clone() {
		let event = EventBodyBorrowed::default();
		let cloned = event.clone();

		assert_eq!(event, cloned);
	}

	#[test]
	fn event_body_qt_borrowed_clone() {
		let event = EventBodyQtBorrowed::default();
		let cloned = event.clone();

		assert_eq!(event, cloned);
	}

	#[test]
	fn owned_event_body_default() {
		let event = EventBodyOwned::default();

		assert_eq!(event.kind, "");
		assert_eq!(event.detail1, 0);
		assert_eq!(event.detail2, 0);
		assert_eq!(event.any_data, 0_u32.into());
	}

	#[test]
	fn qt_event_body_default() {
		let event = EventBodyQtOwned::default();

		assert_eq!(event.kind, "");
		assert_eq!(event.detail1, 0);
		assert_eq!(event.detail2, 0);
		assert_eq!(event.any_data, 0_u32.into());
		assert_eq!(event.properties, QtProperties);
	}

	#[test]
	fn event_body_borrowed_default() {
		let event = EventBodyBorrowed::default();

		assert_eq!(event.kind, "");
		assert_eq!(event.detail1, 0);
		assert_eq!(event.detail2, 0);
		assert_eq!(event.any_data, Value::new(0_u32));
	}

	#[test]
	fn qt_event_body_borrowed_default() {
		let event = EventBodyQtBorrowed::default();

		assert_eq!(event.kind, "");
		assert_eq!(event.detail1, 0);
		assert_eq!(event.detail2, 0);
		assert_eq!(event.any_data, Value::new(0_u32));
		assert_eq!(event.properties, QtProperties);
	}

	#[test]
	fn event_body_default() {
		let event = EventBody::default();

		assert_eq!(event, EventBody::Borrowed(EventBodyBorrowed::default()));
	}

	#[test]
	fn qt_to_owned() {
		let qt = EventBodyQtOwned::default();
		let owned: EventBodyOwned = EventBodyQtOwned::default().into();

		assert_eq!(owned, qt);
	}

	#[test]
	fn borrowed_to_qt() {
		let borrowed: EventBodyBorrowed = EventBodyQtBorrowed::default().into();

		assert_eq!(borrowed, EventBodyBorrowed::default());
	}

	#[test]
	fn event_body_deserialize_as_owned() {
		let event = EventBodyOwned::default();

		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<EventBodyOwned>(ctxt, &event).unwrap();

		let (deserialized, _) = bytes.deserialize::<EventBodyOwned>().unwrap();

		assert_eq!(deserialized, event);
	}

	#[test]
	fn owned_event_body_deserialize_as_borrowed() {
		let event = EventBodyOwned::default();

		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<EventBodyOwned>(ctxt, &event).unwrap();

		let (deserialized, _) = bytes.deserialize::<EventBodyBorrowed>().unwrap();

		assert_eq!(deserialized, EventBodyBorrowed::default());
		assert_eq!(deserialized.kind, event.kind.as_str());
		assert_eq!(deserialized.detail1, event.detail1);
		assert_eq!(deserialized.detail2, event.detail2);
		assert_eq!(deserialized.any_data, *event.any_data);
	}

	#[test]
	fn qt_owned_event_body_deserialize_as_borrowed() {
		let event = EventBodyQtOwned::default();

		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<EventBodyQtOwned>(ctxt, &event).unwrap();

		let (deserialized, _) = bytes.deserialize::<EventBodyBorrowed>().unwrap();

		assert_eq!(deserialized, EventBodyBorrowed::default());
		assert_eq!(deserialized.kind, event.kind.as_str());
		assert_eq!(deserialized.detail1, event.detail1);
		assert_eq!(deserialized.detail2, event.detail2);
		assert_eq!(deserialized.any_data, *event.any_data);
	}

	#[test]
	fn event_body_default_deserialize_as_event_body() {
		let event = EventBody::default();

		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<EventBody>(ctxt, &event).unwrap();

		let (deserialized, _) = bytes.deserialize::<EventBody>().unwrap();

		assert_eq!(deserialized, event);
	}

	#[test]
	fn event_body_owned_default_deserialize_as_event_body() {
		let event = EventBodyOwned::default();

		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<EventBodyOwned>(ctxt, &event).unwrap();

		let (deserialized, _) = bytes.deserialize::<EventBody>().unwrap();

		assert_eq!(deserialized.kind(), event.kind.as_str());
		assert_eq!(deserialized.detail1(), event.detail1);
		assert_eq!(deserialized.detail2(), event.detail2);
		assert_eq!(*deserialized.any_data(), *event.any_data);
	}

	#[test]
	fn complex_body_deserialize_as_event_body() {
		let boots = Array::from(vec!["these", "boots", "are", "made", "for", "walking"]);
		let boots = Value::from(boots);
		let event = (
			"object:state-changed:focused",
			1,
			2,
			boots.clone(),
			HashMap::from([("key", Value::from(55_u32)), ("key2", Value::from(56_u32))]),
		);

		let ctxt = Context::new_dbus(LE, 0);
		let bytes =
			zvariant::to_bytes::<(&str, i32, i32, Value, HashMap<&str, Value>)>(ctxt, &event)
				.unwrap();

		let (deserialized, _) = bytes.deserialize::<EventBody>().unwrap();

		assert_eq!(deserialized.kind(), "object:state-changed:focused");
		assert_eq!(deserialized.detail1(), 1);
		assert_eq!(deserialized.detail2(), 2);
		assert_eq!(*deserialized.any_data(), boots);
	}

	#[test]
	fn complex_body_deserialize_as_owned_event_body() {
		let boots = Array::from(vec!["these", "boots", "are", "made", "for", "walking"]);
		let boots = Value::from(boots);
		let event = (
			"object:state-changed:focused",
			1,
			2,
			boots.clone(),
			HashMap::from([("key", Value::from(55_u32)), ("key2", Value::from(56_u32))]),
		);

		let ctxt = Context::new_dbus(LE, 0);
		let bytes =
			zvariant::to_bytes::<(&str, i32, i32, Value, HashMap<&str, Value>)>(ctxt, &event)
				.unwrap();

		let (deserialized, _) = bytes.deserialize::<EventBodyOwned>().unwrap();

		assert_eq!(deserialized.kind, "object:state-changed:focused");
		assert_eq!(deserialized.detail1, 1);
		assert_eq!(deserialized.detail2, 2);
		assert_eq!(*deserialized.any_data, boots);
	}

	#[test]
	fn complex_body_deserialize_as_borrowed_event_body() {
		let boots = Array::from(vec!["these", "boots", "are", "made", "for", "walking"]);
		let boots = Value::from(boots);
		let event = (
			"object:state-changed:focused",
			1,
			2,
			boots.clone(),
			HashMap::from([("key", Value::from(55_u32)), ("key2", Value::from(56_u32))]),
		);

		let ctxt = Context::new_dbus(LE, 0);
		let bytes =
			zvariant::to_bytes::<(&str, i32, i32, Value, HashMap<&str, Value>)>(ctxt, &event)
				.unwrap();

		let (deserialized, _) = bytes.deserialize::<EventBodyBorrowed>().unwrap();

		assert_eq!(deserialized.kind, "object:state-changed:focused");
		assert_eq!(deserialized.detail1, 1);
		assert_eq!(deserialized.detail2, 2);
		assert_eq!(deserialized.any_data, boots);
	}

	#[test]
	fn deserialize_message_from_complex_message_data() {
		let boots = Array::from(vec!["these", "boots", "are", "made", "for", "walking"]);
		let boots = Value::from(boots);
		let body = (
			"object:state-changed:focused",
			1,
			2,
			boots.clone(),
			HashMap::from([("key", Value::from(55_u32)), ("key2", Value::from(56_u32))]),
		);

		let message = zbus::Message::signal("/", "org.a11y.atspi.Object", "StateChange")
			.unwrap()
			.build(&body)
			.unwrap();

		let msg_body = message.body();

		let deserialized = msg_body.deserialize::<EventBodyOwned>().unwrap();

		assert_eq!(deserialized.kind, "object:state-changed:focused");
		assert_eq!(deserialized.detail1, 1);
		assert_eq!(deserialized.detail2, 2);
		assert_eq!(*deserialized.any_data, boots);
	}

	#[test]
	fn simple_data_deserialization() {
		let body = "hello";

		let message = zbus::Message::signal("/bus/driver/zeenix", "org.Zbus", "TicketCheck")
			.unwrap()
			.build(&body)
			.unwrap();

		let msg_body = message.body();
		let deserialized = msg_body.deserialize::<&str>().unwrap();

		assert_eq!(deserialized, body);
	}

	#[test]
	fn test_valid_hashmap_of_string_value_deserializes_as_properties() {
		let val = Value::from(0_u32);
		let key = "test";
		let map = HashMap::from([(key, val)]);

		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<HashMap<&str, Value>>(ctxt, &map).unwrap();

		let (properties, _) = bytes.deserialize::<Properties>().unwrap();

		assert_eq!(properties, Properties);
	}

	#[test]
	fn test_object_ref_deserializes_as_qt_properties() {
		let object_ref = ObjectRef::default();

		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<ObjectRef>(ctxt, &object_ref).unwrap();

		let (qt_props, _) = bytes.deserialize::<QtProperties>().unwrap();

		assert_eq!(qt_props, QtProperties);
	}

	#[test]
	fn test_properties_serializes_as_valid_hashmap() {
		let properties = Properties;
		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<Properties>(ctxt, &properties).unwrap();

		let (map, _) = bytes.deserialize::<HashMap<&str, Value>>().unwrap();

		assert_eq!(map, HashMap::new());
	}

	#[test]
	fn test_qt_properties_serializes_as_valid_string_objpath_tuple() {
		let qt_properties = QtProperties;
		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<QtProperties>(ctxt, &qt_properties).unwrap();

		let (tuple, _) = bytes.deserialize::<(&str, ObjectPath)>().unwrap();

		assert_eq!(tuple, (":0.0", ObjectPath::from_static_str_unchecked("/")));
	}

	#[test]
	fn test_qt_properties_serializes_as_valid_object_ref() {
		let qt_properties = QtProperties;
		let ctxt = Context::new_dbus(LE, 0);
		let bytes = zvariant::to_bytes::<QtProperties>(ctxt, &qt_properties).unwrap();

		let (objectref, _) = bytes.deserialize::<ObjectRef>().unwrap();

		assert_eq!(objectref.name, ":0.0");
		assert_eq!(objectref.path, ObjectPath::from_static_str_unchecked("/").into());
	}

	#[cfg(test)]
	mod signatures {
		#[test]
		fn test_event_body_signature_equals_borrowed_event_body_signature() {
			use super::*;
			use zvariant::Type;

			let borrowed = EventBodyBorrowed::SIGNATURE;
			let owned = EventBodyOwned::SIGNATURE;

			assert_eq!(borrowed, owned);
		}
	}
}