Upload upstream chromium 76.0.3809.146
[platform/framework/web/chromium-efl.git] / base / fuchsia / scoped_service_binding.h
1 // Copyright 2018 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #ifndef BASE_FUCHSIA_SCOPED_SERVICE_BINDING_H_
6 #define BASE_FUCHSIA_SCOPED_SERVICE_BINDING_H_
7
8 #include <lib/fidl/cpp/binding_set.h>
9
10 #include "base/bind.h"
11 #include "base/fuchsia/service_directory.h"
12
13 namespace base {
14 namespace fuchsia {
15
16 template <typename Interface>
17 class ScopedServiceBinding {
18  public:
19   // |service_directory| and |impl| must outlive the binding.
20   ScopedServiceBinding(ServiceDirectory* service_directory, Interface* impl)
21       : directory_(service_directory), impl_(impl) {
22     directory_->AddService(
23         BindRepeating(&ScopedServiceBinding::BindClient, Unretained(this)));
24   }
25
26   ~ScopedServiceBinding() { directory_->RemoveService(Interface::Name_); }
27
28   void SetOnLastClientCallback(base::OnceClosure on_last_client_callback) {
29     on_last_client_callback_ = std::move(on_last_client_callback);
30     bindings_.set_empty_set_handler(
31         fit::bind_member(this, &ScopedServiceBinding::OnBindingSetEmpty));
32   }
33
34   bool has_clients() const { return bindings_.size() != 0; }
35
36  private:
37   void BindClient(fidl::InterfaceRequest<Interface> request) {
38     bindings_.AddBinding(impl_, std::move(request));
39   }
40
41   void OnBindingSetEmpty() {
42     bindings_.set_empty_set_handler(nullptr);
43     std::move(on_last_client_callback_).Run();
44   }
45
46   ServiceDirectory* const directory_;
47   Interface* const impl_;
48   fidl::BindingSet<Interface> bindings_;
49   base::OnceClosure on_last_client_callback_;
50
51   DISALLOW_COPY_AND_ASSIGN(ScopedServiceBinding);
52 };
53
54 }  // namespace fuchsia
55 }  // namespace base
56
57 #endif  // BASE_FUCHSIA_SCOPED_SERVICE_BINDING_H_