File: gdbus_connection_ref.h

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (889 lines) | stat: -rw-r--r-- 39,504 bytes parent folder | download | duplicates (5)
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
// Copyright 2024 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef REMOTING_HOST_LINUX_GDBUS_CONNECTION_REF_H_
#define REMOTING_HOST_LINUX_GDBUS_CONNECTION_REF_H_

#include <gio/gio.h>
#include <glib-object.h>
#include <glib.h>

#include <algorithm>
#include <memory>
#include <optional>
#include <string>
#include <tuple>
#include <utility>

#include "base/functional/bind.h"
#include "base/functional/callback_forward.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/memory/scoped_refptr.h"
#include "base/memory/weak_ptr.h"
#include "base/task/sequenced_task_runner.h"
#include "base/types/expected.h"
#include "remoting/host/base/loggable.h"
#include "remoting/host/linux/dbus_interfaces/org_freedesktop_DBus_Properties.h"
#include "remoting/host/linux/gdbus_fd_list.h"
#include "remoting/host/linux/gvariant_ref.h"
#include "remoting/host/linux/gvariant_type.h"
#include "ui/base/glib/scoped_gobject.h"

namespace remoting {

// A wrapper around a GDBusConnection providing Chromium-style async callbacks
// using GVariantRef for type-safe GVariant handling.
//
// Like with GDBusConnection, calls can be made from any thread. The reply
// callback will be invoke via the default task runner of the caller's virtual
// thread, as obtained by base::SequencedTaskRunner::GetCurrentDefault().
class GDBusConnectionRef {
 public:
  // Callback to receive the connection created by one of the Create* methods.
  using CreateCallback =
      base::OnceCallback<void(base::expected<GDBusConnectionRef, Loggable>)>;
  // Callback to receive the result of a method call.
  template <typename ReturnType>
  using CallCallback =
      base::OnceCallback<void(base::expected<ReturnType, Loggable>)>;
  // Callback to receive the result of a method call that returns one or more
  // file descriptors.
  template <typename ReturnType>
  using CallFdCallback = base::OnceCallback<void(
      base::expected<std::pair<ReturnType, GDBusFdList>, Loggable>)>;
  // Callback to receive subscribed signal messages.
  template <typename ArgType>
  using SignalCallback = base::RepeatingCallback<void(ArgType arguments)>;
  // Can be passed in lieu of SignalCallback when details of the source of the
  // signal are needed (e.g., when registering the same callback for multiple
  // signals).
  template <typename ArgType>
  using DetailedSignalCallback =
      base::RepeatingCallback<void(std::string sender,
                                   gvariant::ObjectPath object_path,
                                   std::string interface_name,
                                   std::string signal_name,
                                   ArgType arguments)>;

  // Returned from SignalSubscribe. Dropping will free the callback and cancel
  // the underlying subscription. Must be dropped on the sequence where it was
  // created.
  class SignalSubscription;

  // The only valid operation for a default-constructed GDBusConnectionRef is
  // assigning a connection to it.
  GDBusConnectionRef();
  GDBusConnectionRef(const GDBusConnectionRef& other);
  GDBusConnectionRef(GDBusConnectionRef&& other);
  GDBusConnectionRef& operator=(const GDBusConnectionRef& other);
  GDBusConnectionRef& operator=(GDBusConnectionRef&& other);
  ~GDBusConnectionRef();

  // Create from an existing connection.
  explicit GDBusConnectionRef(ScopedGObject<GDBusConnection> connection);

  // Asynchronously tries to create an instance for the session bus and invokes
  // callback with the result.
  static void CreateForSessionBus(CreateCallback callback);

  // Asynchronously tries to create an instance for the system bus and invokes
  // callback with the result.
  static void CreateForSystemBus(CreateCallback callback);

  // Returns whether this instance is initialized for use (not default
  // constructed or moved from).
  bool is_initialized() const;

  // Obtains the underlying GDBusConnection pointer.
  inline GDBusConnection* raw() const { return connection_.get(); }

  // Dynamically-checked overloads. Type mismatches reported at run time.

  // Asynchronously invoke the provided method, checking types at run time.
  //
  // bus_name - The owner of the object on which to call the method. May be a
  //     unique or well-known bus name. If this is a direct peer connection
  //     rather than a bus connection, pass nullptr.
  // object_path - The remote object on which to call the method.
  // interface_name - The interface the method is a part of.
  // method_name - The name of the method to call.
  // arguments - The arguments to pass to the method. The method call will fail
  //     if the arguments don't match the actual parameters expected by the
  //     method.
  // callback - A callback to invoke with the result of the method call, or an
  //     error if something goes wrong. If the actual return type can't be
  //     converted to ReturnType, an error will be returned (but note that in
  //     this case, the method was still executed.) A ReturnType of
  //     GVariantRef<"r"> can accept any return value.
  // flags - See https://docs.gtk.org/gio/flags.DBusCallFlags.html
  // timeout_msec - Timeout for the call in milliseconds. Pass -1 to use the
  //     default, or G_MAXINT for no timeout.
  template <typename ArgType, typename ReturnType>
  void Call(const char* bus_name,
            gvariant::ObjectPathCStr object_path,
            const char* interface_name,
            const char* method_name,
            const ArgType& arguments,
            CallCallback<ReturnType> callback,
            GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
            gint timeout_msec = -1) const
    requires requires(GVariantRef<"r"> variant) {
      GVariantRef<"r">::TryFrom(arguments);
      variant.TryInto<ReturnType>();
    };

  // Variant of dynamically-checked Call that can return one or more file
  // descriptors in the response.
  template <typename ArgType, typename ReturnType>
  void Call(const char* bus_name,
            gvariant::ObjectPathCStr object_path,
            const char* interface_name,
            const char* method_name,
            const ArgType& arguments,
            CallFdCallback<ReturnType> callback,
            GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
            gint timeout_msec = -1) const
    requires requires(GVariantRef<"r"> variant) {
      GVariantRef<"r">::TryFrom(arguments);
      variant.TryInto<ReturnType>();
    };

  // Variant of dynamically-checked Call that can accept one or more file
  // descriptors to be sent along with the call.
  template <typename ArgType, typename ReturnType>
  void Call(const char* bus_name,
            gvariant::ObjectPathCStr object_path,
            const char* interface_name,
            const char* method_name,
            const ArgType& arguments,
            GDBusFdList fds,
            CallCallback<ReturnType> callback,
            GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
            gint timeout_msec = -1) const
    requires requires(GVariantRef<"r"> variant) {
      GVariantRef<"r">::TryFrom(arguments);
      variant.TryInto<ReturnType>();
    };

  // Variant of dynamically-checked Call that can accept one or more file
  // descriptors to be sent along with the call and can return one or more file
  // descriptors in the response.
  template <typename ArgType, typename ReturnType>
  void Call(const char* bus_name,
            gvariant::ObjectPathCStr object_path,
            const char* interface_name,
            const char* method_name,
            const ArgType& arguments,
            GDBusFdList fds,
            CallFdCallback<ReturnType> callback,
            GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
            gint timeout_msec = -1) const
    requires requires(GVariantRef<"r"> variant) {
      GVariantRef<"r">::TryFrom(arguments);
      variant.TryInto<ReturnType>();
    };

  // Asynchronously retrieve the specified property value.
  //
  // bus_name - The owner of the object from which to retrieve the property. May
  //     be a unique or well-known bus name. If this is a direct peer connection
  //     rather than a bus connection, pass nullptr.
  // object_path - The remote object from which to retrieve the property.
  // interface_name - The interface the property is a part of.
  // property_name - The name of the property to retrieve.
  // callback - A callback to invoke with the retrieved property value, or an
  //     error if something goes wrong. If the property value cannot be
  //     converted to ValueType, an error will be returned. Accept a
  //     GVariantRef<> to handle any value type.
  template <typename ValueType>
  void GetProperty(const char* bus_name,
                   gvariant::ObjectPathCStr object_path,
                   const char* interface_name,
                   const char* property_name,
                   CallCallback<ValueType> callback,
                   GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
                   gint timeout_msec = -1) const
    requires requires(GVariantRef<> variant) { variant.TryInto<ValueType>(); };

  // Asynchronously set the specified property value.
  //
  // bus_name - The owner of the object on which to set the property. May be a
  //     unique or well-known bus name. If this is a direct peer connection
  //     rather than a bus connection, pass nullptr.
  // object_path - The remote object on which to set the property.
  // interface_name - The interface the property is a part of.
  // property_name - The name of the property to set.
  // value - The new property value. An error will be returned if the value is
  //     incompatible with the property.
  // callback - A callback to invoke when the property has been set, or an error
  //     if something goes wrong.
  template <typename ValueType>
  void SetProperty(const char* bus_name,
                   gvariant::ObjectPathCStr object_path,
                   const char* interface_name,
                   const char* property_name,
                   const ValueType& value,
                   CallCallback<void> callback,
                   GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
                   gint timeout_msec = -1) const
    requires requires() { GVariantRef<>::TryFrom(value); };

  // Subscribe to matching signals from the sender.
  //
  // bus_name - The sender from which to receive signals. May be a unique or
  //     well-known bus name. If this is a direct peer connection rather than a
  //     bus connection, pass nullptr.
  // object_path - The remote object from which to receive signals. May be
  //     std::nullopt to receive signals from all objects owned by the sender.
  // interface_name - The interface from which to receive signals. May be
  //     nullptr to receive signals from all interfaces.
  // signal_name - The name of the signals to receive. May be nullptr to
  //     receive signals with any name.
  // callback - The callback to invoke when a signal is received. Only signals
  //     convertible to ArgType will be delivered. Accept a GVariantRef<"r"> to
  //     receive signals of any type.
  //
  // Returns a subscription object, which must be dropped on the same sequence.
  // Dropping the returned object will unsubscribe from the signal and no more
  // signals will be sent.
  template <typename ArgType>
  std::unique_ptr<SignalSubscription> SignalSubscribe(
      const char* bus_name,
      std::optional<gvariant::ObjectPathCStr> object_path,
      const char* interface_name,
      const char* signal_name,
      SignalCallback<ArgType> callback)
    requires requires(GVariantRef<"r"> variant) { variant.TryInto<ArgType>(); };

  // Variant of subscribe that provides sender information for the signal. In
  // addition to the signal data, provides the callback with the following
  // information:
  //
  // sender - The unique bus name of the sender of the signal. Note that this
  //     will be the unique name of the sender even if the subscription was
  //     created using the well-known name. If this is a direct peer connection,
  //     sender will be an empty string.
  // object_path - The remote object that was the source of the signal.
  // interface_name - The interface that was the source of the signal.
  // signal_name - The name of the signal.
  //
  // This additional information is mostly useful when the same callback is used
  // for multiple signals.
  template <typename ArgType>
  std::unique_ptr<SignalSubscription> SignalSubscribe(
      const char* bus_name,
      std::optional<gvariant::ObjectPathCStr> object_path,
      const char* interface_name,
      const char* signal_name,
      DetailedSignalCallback<ArgType> callback)
    requires requires(GVariantRef<"r"> variant) { variant.TryInto<ArgType>(); };

  // Statically-checked overloads. Types checked against provided spec at
  // compile time. (The call may still fail for a variety of other reasons,
  // including the spec not matching the actual implementation on the bus.)

  // Asynchronously invoke the method declared by the provided MethodSpec.
  //
  // bus_name - The owner of the object on which to call the method. May be a
  //     unique or well-known bus name. If this is a direct peer connection
  //     rather than a bus connection, pass nullptr.
  // object_path - The remote object on which to call the method.
  // arguments - The arguments to pass to the method. Must be infallibly
  //     convertible to the input type declared by MethodSpec.
  // callback - A callback to invoke with the result of the method call, or an
  //     error if something goes wrong. The output type declared by MethodSpec
  //     must be infallibly convertible to ReturnType.
  // flags - See https://docs.gtk.org/gio/flags.DBusCallFlags.html
  // timeout_msec - Timeout for the call in milliseconds. Pass -1 to use the
  //     default, or G_MAXINT for no timeout.
  template <typename MethodSpec, typename ArgType, typename ReturnType>
  void Call(const char* bus_name,
            gvariant::ObjectPathCStr object_path,
            const ArgType& arguments,
            CallCallback<ReturnType> callback,
            GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
            gint timeout_msec = -1) const
    requires requires(GVariantRef<MethodSpec::kOutType> variant) {
      GVariantRef<MethodSpec::kInType>::From(arguments);
      variant.template Into<ReturnType>();
    };

  // Variant of statically-checked Call that can return one or more file
  // descriptors in the response.
  template <typename MethodSpec, typename ArgType, typename ReturnType>
  void Call(const char* bus_name,
            gvariant::ObjectPathCStr object_path,
            const ArgType& arguments,
            CallFdCallback<ReturnType> callback,
            GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
            gint timeout_msec = -1) const
    requires requires(GVariantRef<MethodSpec::kOutType> variant) {
      GVariantRef<MethodSpec::kInType>::From(arguments);
      variant.template Into<ReturnType>();
    };

  // Variant of statically-checked Call that can accept one or more file
  // descriptors to be sent along with the call.
  template <typename MethodSpec, typename ArgType, typename ReturnType>
  void Call(const char* bus_name,
            gvariant::ObjectPathCStr object_path,
            const ArgType& arguments,
            GDBusFdList fds,
            CallCallback<ReturnType> callback,
            GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
            gint timeout_msec = -1) const
    requires requires(GVariantRef<MethodSpec::kOutType> variant) {
      GVariantRef<MethodSpec::kInType>::From(arguments);
      variant.template Into<ReturnType>();
    };

  // Variant of statically-checked Call that can accept one or more file
  // descriptors to be sent along with the call and can return one or more file
  // descriptors in the response.
  template <typename MethodSpec, typename ArgType, typename ReturnType>
  void Call(const char* bus_name,
            gvariant::ObjectPathCStr object_path,
            const ArgType& arguments,
            GDBusFdList fds,
            CallFdCallback<ReturnType> callback,
            GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
            gint timeout_msec = -1) const
    requires requires(GVariantRef<MethodSpec::kOutType> variant) {
      GVariantRef<MethodSpec::kInType>::From(arguments);
      variant.template Into<ReturnType>();
    };

  // Asynchronously retrieve the property declared by the provided PropertySpec.
  //
  // bus_name - The owner of the object from which to retrieve the property. May
  //     be a unique or well-known bus name. If this is a direct peer connection
  //     rather than a bus connection, pass nullptr.
  // object_path - The remote object from which to retrieve the property.
  // callback - A callback to invoke with the retrieved property value, or an
  //     error if something goes wrong. The property type declared by
  //     PropertySpec must be infallibly convertible to ValueType.
  template <typename PropertySpec, typename ValueType>
  void GetProperty(const char* bus_name,
                   gvariant::ObjectPathCStr object_path,
                   CallCallback<ValueType> callback,
                   GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
                   gint timeout_msec = -1) const
    requires(PropertySpec::kReadable &&
             requires(GVariantRef<PropertySpec::kType> variant) {
               variant.template Into<ValueType>();
             });

  // Asynchronously set the property declared by the provided PropertySpec.
  //
  // bus_name - The owner of the object on which to set the property. May be a
  //     unique or well-known bus name. If this is a direct peer connection
  //     rather than a bus connection, pass nullptr.
  // object_path - The remote object on which to set the property.
  // interface_name - The interface the property is a part of.
  // property_name - The name of the property to set.
  // value - The new property value. Must be infallibly convertible to the type
  //     declared by PropertySpec.
  // callback - A callback to invoke when the property has been set, or an error
  //     if something goes wrong.
  template <typename PropertySpec, typename ValueType>
  void SetProperty(const char* bus_name,
                   gvariant::ObjectPathCStr object_path,
                   const ValueType& value,
                   CallCallback<void> callback,
                   GDBusCallFlags flags = G_DBUS_CALL_FLAGS_NONE,
                   gint timeout_msec = -1) const
    requires(PropertySpec::kWritable &&
             requires() { GVariantRef<PropertySpec::kType>::From(value); });

  // Subscribe to signals matching the provided SignalSpec.
  //
  // bus_name - The sender from which to receive signals. May be a unique or
  //     well-known bus name. If this is a direct peer connection rather than a
  //     bus connection, pass nullptr.
  // object_path - The remote object from which to receive signals. May be
  //     nullptr to receive signals from all objects owned by the sender.
  // callback - The callback to invoke when a signal is received. The signal
  //     type declared by SignalSpec must be infallibly convertible to ArgType.
  //
  // Returns a subscription object, which must be dropped on the same sequence.
  // Dropping the returned object will unsubscribe from the signal and no more
  // signals will be sent.
  template <typename SignalSpec, typename ArgType>
  std::unique_ptr<SignalSubscription> SignalSubscribe(
      const char* bus_name,
      std::optional<gvariant::ObjectPathCStr> object_path,
      SignalCallback<ArgType> callback)
    requires requires(GVariantRef<SignalSpec::kType> variant) {
      variant.template Into<ArgType>();
    };

  // Variant of subscribe that provides sender information for the signal. In
  // addition to the signal data, provides the callback with the following
  // information:
  //
  // sender - The unique bus name of the sender of the signal. Note that this
  //     will be the unique name of the sender even if the subscription was
  //     created using the well-known name. If this is a direct peer connection,
  //     sender will be an empty string.
  // object_path - The remote object that was the source of the signal.
  // interface_name - The interface that was the source of the signal.
  // signal_name - The name of the signal.
  //
  // This additional information is mostly useful when the same callback is used
  // for multiple signals.
  template <typename SignalSpec, typename ArgType>
  std::unique_ptr<SignalSubscription> SignalSubscribe(
      const char* bus_name,
      std::optional<gvariant::ObjectPathCStr> object_path,
      DetailedSignalCallback<ArgType> callback)
    requires requires(GVariantRef<SignalSpec::kType> variant) {
      variant.template Into<ArgType>();
    };

 private:
  static void CreateForBus(GBusType bus, CreateCallback callback);

  // Common logic for all Calls.
  void CallInternal(const char* bus_name,
                    gvariant::ObjectPathCStr object_path,
                    const char* interface_name,
                    const char* method_name,
                    const GVariantRef<"r">& arguments,
                    GDBusFdList fds,
                    CallFdCallback<GVariantRef<"r">> callback,
                    GDBusCallFlags flags,
                    gint timeout_msec) const;

  // Convert CallCallback to a CallFdCallback that discards (and thus closes)
  // any returned file descriptors.
  template <typename ReturnType>
  static CallFdCallback<ReturnType> IgnoreFds(
      CallCallback<ReturnType>&& callback);

  ScopedGObject<GDBusConnection> connection_;
};

// Represents an active signal subscription.
class GDBusConnectionRef::SignalSubscription {
 public:
  // Unsubscribes from the signal.
  ~SignalSubscription();

 private:
  // Subscribes to the signal with the given callback.
  SignalSubscription(GDBusConnectionRef connection,
                     const char* sender,
                     std::optional<gvariant::ObjectPathCStr> object_path,
                     const char* interface_name,
                     const char* signal_name,
                     DetailedSignalCallback<GVariantRef<"r">> callback);

  // Called when a signal arrives. Invokes the provided callback.
  void OnSignal(std::string sender,
                gvariant::ObjectPath object_path,
                std::string interface_name,
                std::string signal_name,
                GVariantRef<"r"> arguments);

  GDBusConnectionRef connection_;
  DetailedSignalCallback<GVariantRef<"r">> callback_;
  guint subscription_id_;
  base::WeakPtrFactory<SignalSubscription> weak_factory_;

  friend class GDBusConnectionRef;
};

template <typename ArgType, typename ReturnType>
void GDBusConnectionRef::Call(const char* bus_name,
                              gvariant::ObjectPathCStr object_path,
                              const char* interface_name,
                              const char* method_name,
                              const ArgType& arguments,
                              CallCallback<ReturnType> callback,
                              GDBusCallFlags flags,
                              gint timeout_msec) const
  requires requires(GVariantRef<"r"> variant) {
    GVariantRef<"r">::TryFrom(arguments);
    variant.TryInto<ReturnType>();
  }
{
  Call(bus_name, object_path, interface_name, method_name, arguments,
       GDBusFdList(), IgnoreFds(std::move(callback)), flags, timeout_msec);
}

template <typename ArgType, typename ReturnType>
void GDBusConnectionRef::Call(const char* bus_name,
                              gvariant::ObjectPathCStr object_path,
                              const char* interface_name,
                              const char* method_name,
                              const ArgType& arguments,
                              CallFdCallback<ReturnType> callback,
                              GDBusCallFlags flags,
                              gint timeout_msec) const
  requires requires(GVariantRef<"r"> variant) {
    GVariantRef<"r">::TryFrom(arguments);
    variant.TryInto<ReturnType>();
  }
{
  Call(bus_name, object_path, interface_name, method_name, arguments,
       GDBusFdList(), std::move(callback), flags, timeout_msec);
}

template <typename ArgType, typename ReturnType>
void GDBusConnectionRef::Call(const char* bus_name,
                              gvariant::ObjectPathCStr object_path,
                              const char* interface_name,
                              const char* method_name,
                              const ArgType& arguments,
                              GDBusFdList fds,
                              CallCallback<ReturnType> callback,
                              GDBusCallFlags flags,
                              gint timeout_msec) const
  requires requires(GVariantRef<"r"> variant) {
    GVariantRef<"r">::TryFrom(arguments);
    variant.TryInto<ReturnType>();
  }
{
  Call(bus_name, object_path, interface_name, method_name, arguments,
       std::move(fds), IgnoreFds(std::move(callback)), flags, timeout_msec);
}

template <typename ArgType, typename ReturnType>
void GDBusConnectionRef::Call(const char* bus_name,
                              gvariant::ObjectPathCStr object_path,
                              const char* interface_name,
                              const char* method_name,
                              const ArgType& arguments,
                              GDBusFdList fds,
                              CallFdCallback<ReturnType> callback,
                              GDBusCallFlags flags,
                              gint timeout_msec) const
  requires requires(GVariantRef<"r"> variant) {
    GVariantRef<"r">::TryFrom(arguments);
    variant.TryInto<ReturnType>();
  }
{
  // First check that the provided arguments can be converted to a GVariant
  // tuple.
  auto arg_variant = GVariantRef<"r">::TryFrom(arguments);
  if (!arg_variant.has_value()) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE,
        base::BindOnce(
            std::move(callback),
            std::move(arg_variant)
                .error()
                .UnexpectedWithContext(
                    FROM_HERE, "While converting D-Bus call arguments")));
    return;
  }

  // Attempt to convert return value into the target type.
  auto convert_result = base::BindOnce(
      [](base::expected<std::pair<GVariantRef<"r">, GDBusFdList>, Loggable>
             result) {
        return std::move(result).and_then([](auto&& inner) {
          return inner.first.template TryInto<ReturnType>()
              .transform([&](ReturnType&& value) {
                return std::pair(std::move(value), std::move(inner.second));
              })
              .transform_error([](Loggable&& loggable) {
                loggable.AddContext(FROM_HERE,
                                    "While converting D-Bus call return value");
                return std::move(loggable);
              });
        });
      });

  CallInternal(bus_name, object_path, interface_name, method_name,
               arg_variant.value(), std::move(fds),
               std::move(convert_result).Then(std::move(callback)), flags,
               timeout_msec);
}

template <typename ValueType>
void GDBusConnectionRef::GetProperty(const char* bus_name,
                                     gvariant::ObjectPathCStr object_path,
                                     const char* interface_name,
                                     const char* property_name,
                                     CallCallback<ValueType> callback,
                                     GDBusCallFlags flags,
                                     gint timeout_msec) const
  requires requires(GVariantRef<> variant) { variant.TryInto<ValueType>(); }
{
  // Ensure interface and property names are valid UTF-8.
  auto args =
      GVariantRef<"(ss)">::TryFrom(std::tuple(interface_name, property_name));
  if (!args.has_value()) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE,
        base::BindOnce(
            std::move(callback),
            std::move(args).error().UnexpectedWithContext(
                FROM_HERE, "While checking D-Bus get-property args")));
    return;
  }

  // Unboxes the returned "v" value and attempts to convert it to the expected
  // type.
  auto convert_result =
      base::BindOnce([](base::expected<GVariantRef<"(v)">, Loggable> result) {
        return std::move(result)
            .transform_error([](Loggable&& loggable) {
              loggable.AddContext(FROM_HERE,
                                  "While getting D-Bus property value");
              return std::move(loggable);
            })
            .and_then([](GVariantRef<"(v)"> variant) {
              return variant.get<0>()
                  .get<0>()
                  .TryInto<ValueType>()
                  .transform_error([](Loggable&& loggable) {
                    loggable.AddContext(
                        FROM_HERE, "While converting D-Bus property value");
                    return std::move(loggable);
                  });
            });
      });

  Call<remoting::org_freedesktop_DBus_Properties::Get>(
      bus_name, object_path, args.value(),
      std::move(convert_result).Then(std::move(callback)), flags, timeout_msec);
}

template <typename ValueType>
void GDBusConnectionRef::SetProperty(const char* bus_name,
                                     gvariant::ObjectPathCStr object_path,
                                     const char* interface_name,
                                     const char* property_name,
                                     const ValueType& value,
                                     CallCallback<void> callback,
                                     GDBusCallFlags flags,
                                     gint timeout_msec) const
  requires requires() { GVariantRef<>::TryFrom(value); }
{
  // Ensure interface and property names are valid UTF-8 and the value can be
  // converted to a GVariant.
  auto args = GVariantRef<"(ssv)">::TryFrom(std::tuple(
      interface_name, property_name, gvariant::Boxed<const ValueType&>{value}));
  if (!args.has_value()) {
    base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
        FROM_HERE,
        base::BindOnce(
            std::move(callback),
            std::move(args).error().UnexpectedWithContext(
                FROM_HERE, "While checking D-Bus set-property args")));
    return;
  }

  // Ignores the returned std::tuple() and returns void instead.
  auto convert_result =
      base::BindOnce([](base::expected<std::tuple<>, Loggable> result) {
        return std::move(result)
            .transform([](std::tuple<>) {})
            .transform_error([](Loggable&& loggable) {
              loggable.AddContext(FROM_HERE,
                                  "While setting D-Bus property value");
              return std::move(loggable);
            });
      });

  Call<remoting::org_freedesktop_DBus_Properties::Set>(
      bus_name, object_path, args.value(),
      std::move(convert_result).Then(std::move(callback)), flags, timeout_msec);
}

template <typename ArgType>
std::unique_ptr<GDBusConnectionRef::SignalSubscription>
GDBusConnectionRef::SignalSubscribe(
    const char* bus_name,
    std::optional<gvariant::ObjectPathCStr> object_path,
    const char* interface_name,
    const char* signal_name,
    SignalCallback<ArgType> callback)
  requires requires(GVariantRef<"r"> variant) { variant.TryInto<ArgType>(); }
{
  return SignalSubscribe(
      bus_name, object_path, interface_name, signal_name,
      base::IgnoreArgs<std::string, gvariant::ObjectPath, std::string,
                       std::string>(std::move(callback)));
}

template <typename ArgType>
std::unique_ptr<GDBusConnectionRef::SignalSubscription>
GDBusConnectionRef::SignalSubscribe(
    const char* bus_name,
    std::optional<gvariant::ObjectPathCStr> object_path,
    const char* interface_name,
    const char* signal_name,
    DetailedSignalCallback<ArgType> callback)
  requires requires(GVariantRef<"r"> variant) { variant.TryInto<ArgType>(); }
{
  // Attempts to convert return value into the target type and invokes the
  // provided callback if it matches. If the signal is of the wrong type, it is
  // ignored.
  auto callback_wrapper = base::BindRepeating(
      [](const DetailedSignalCallback<ArgType>& callback, std::string sender,
         gvariant::ObjectPath object_path, std::string interface_name,
         std::string signal_name, GVariantRef<"r"> arguments) {
        base::expected<ArgType, Loggable> try_result =
            arguments.TryInto<ArgType>();
        if (try_result.has_value()) {
          callback.Run(std::move(sender), std::move(object_path),
                       std::move(interface_name), std::move(signal_name),
                       std::move(try_result).value());
        }
      },
      std::move(callback));

  return std::unique_ptr<SignalSubscription>(
      new SignalSubscription(*this, bus_name, object_path, interface_name,
                             signal_name, std::move(callback_wrapper)));
}

template <typename MethodSpec, typename ArgType, typename ReturnType>
void GDBusConnectionRef::Call(const char* bus_name,
                              gvariant::ObjectPathCStr object_path,
                              const ArgType& arguments,
                              CallCallback<ReturnType> callback,
                              GDBusCallFlags flags,
                              gint timeout_msec) const
  requires requires(GVariantRef<MethodSpec::kOutType> variant) {
    GVariantRef<MethodSpec::kInType>::From(arguments);
    variant.template Into<ReturnType>();
  }
{
  Call(bus_name, object_path, MethodSpec::kInterfaceName,
       MethodSpec::kMethodName, arguments, std::move(callback), flags,
       timeout_msec);
}

template <typename MethodSpec, typename ArgType, typename ReturnType>
void GDBusConnectionRef::Call(const char* bus_name,
                              gvariant::ObjectPathCStr object_path,
                              const ArgType& arguments,
                              CallFdCallback<ReturnType> callback,
                              GDBusCallFlags flags,
                              gint timeout_msec) const
  requires requires(GVariantRef<MethodSpec::kOutType> variant) {
    GVariantRef<MethodSpec::kInType>::From(arguments);
    variant.template Into<ReturnType>();
  }
{
  Call(bus_name, object_path, MethodSpec::kInterfaceName,
       MethodSpec::kMethodName, arguments, std::move(callback), flags,
       timeout_msec);
}

template <typename MethodSpec, typename ArgType, typename ReturnType>
void GDBusConnectionRef::Call(const char* bus_name,
                              gvariant::ObjectPathCStr object_path,
                              const ArgType& arguments,
                              GDBusFdList fds,
                              CallCallback<ReturnType> callback,
                              GDBusCallFlags flags,
                              gint timeout_msec) const
  requires requires(GVariantRef<MethodSpec::kOutType> variant) {
    GVariantRef<MethodSpec::kInType>::From(arguments);
    variant.template Into<ReturnType>();
  }
{
  Call(bus_name, object_path, MethodSpec::kInterfaceName,
       MethodSpec::kMethodName, arguments, std::move(fds), std::move(callback),
       flags, timeout_msec);
}

template <typename MethodSpec, typename ArgType, typename ReturnType>
void GDBusConnectionRef::Call(const char* bus_name,
                              gvariant::ObjectPathCStr object_path,
                              const ArgType& arguments,
                              GDBusFdList fds,
                              CallFdCallback<ReturnType> callback,
                              GDBusCallFlags flags,
                              gint timeout_msec) const
  requires requires(GVariantRef<MethodSpec::kOutType> variant) {
    GVariantRef<MethodSpec::kInType>::From(arguments);
    variant.template Into<ReturnType>();
  }
{
  Call(bus_name, object_path, MethodSpec::kInterfaceName,
       MethodSpec::kMethodName, arguments, std::move(fds), std::move(callback),
       flags, timeout_msec);
}

template <typename PropertySpec, typename ValueType>
void GDBusConnectionRef::GetProperty(const char* bus_name,
                                     gvariant::ObjectPathCStr object_path,
                                     CallCallback<ValueType> callback,
                                     GDBusCallFlags flags,
                                     gint timeout_msec) const
  requires(PropertySpec::kReadable &&
           requires(GVariantRef<PropertySpec::kType> variant) {
             variant.template Into<ValueType>();
           })
{
  GetProperty(bus_name, object_path, PropertySpec::kInterfaceName,
              PropertySpec::kPropertyName, std::move(callback), flags,
              timeout_msec);
}

template <typename PropertySpec, typename ValueType>
void GDBusConnectionRef::SetProperty(const char* bus_name,
                                     gvariant::ObjectPathCStr object_path,
                                     const ValueType& value,
                                     CallCallback<void> callback,
                                     GDBusCallFlags flags,
                                     gint timeout_msec) const
  requires(PropertySpec::kWritable &&
           requires() { GVariantRef<PropertySpec::kType>::From(value); })
{
  SetProperty(bus_name, object_path, PropertySpec::kInterfaceName,
              PropertySpec::kPropertyName, value, std::move(callback), flags,
              timeout_msec);
}

template <typename SignalSpec, typename ArgType>
std::unique_ptr<GDBusConnectionRef::SignalSubscription>
GDBusConnectionRef::SignalSubscribe(
    const char* bus_name,
    std::optional<gvariant::ObjectPathCStr> object_path,
    SignalCallback<ArgType> callback)
  requires requires(GVariantRef<SignalSpec::kType> variant) {
    variant.template Into<ArgType>();
  }
{
  return SignalSubscribe(bus_name, object_path, SignalSpec::kInterfaceName,
                         SignalSpec::kSignalName, std::move(callback));
}

template <typename SignalSpec, typename ArgType>
std::unique_ptr<GDBusConnectionRef::SignalSubscription>
GDBusConnectionRef::SignalSubscribe(
    const char* bus_name,
    std::optional<gvariant::ObjectPathCStr> object_path,
    DetailedSignalCallback<ArgType> callback)
  requires requires(GVariantRef<SignalSpec::kType> variant) {
    variant.template Into<ArgType>();
  }
{
  return SignalSubscribe(bus_name, object_path, SignalSpec::kInterfaceName,
                         SignalSpec::kSignalName, std::move(callback));
}

// static
template <typename ReturnType>
GDBusConnectionRef::CallFdCallback<ReturnType> GDBusConnectionRef::IgnoreFds(
    CallCallback<ReturnType>&& callback) {
  auto drop_fds = base::BindOnce(
      [](base::expected<std::pair<ReturnType, GDBusFdList>, Loggable> result) {
        return result.transform(
            [](auto&& inner) { return std::move(inner).first; });
      });
  return std::move(drop_fds).Then(std::move(callback));
}

}  // namespace remoting

#endif  // REMOTING_HOST_LINUX_GDBUS_CONNECTION_REF_H_