Fix layout of the Connection Tab of the Origin Info Bubble.
[chromium-blink-merge.git] / mojo / common / weak_binding_set.h
blob7696c82c280487e266c520b6bd9f3fc245cd131b
1 // Copyright 2014 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.
5 #ifndef MOJO_COMMON_WEAK_BINDING_SET_H_
6 #define MOJO_COMMON_WEAK_BINDING_SET_H_
8 #include <algorithm>
9 #include <vector>
11 #include "base/memory/weak_ptr.h"
12 #include "third_party/mojo/src/mojo/public/cpp/bindings/binding.h"
14 namespace mojo {
16 template <typename Interface>
17 class WeakBinding;
19 // Use this class to manage a set of weak pointers to bindings each of which is
20 // owned by the pipe they are bound to.
21 template <typename Interface>
22 class WeakBindingSet {
23 public:
24 WeakBindingSet() {}
25 ~WeakBindingSet() { CloseAllBindings(); }
27 void set_connection_error_handler(const Closure& error_handler) {
28 error_handler_ = error_handler;
31 void AddBinding(Interface* impl, InterfaceRequest<Interface> request) {
32 auto binding = new WeakBinding<Interface>(impl, request.Pass());
33 binding->set_connection_error_handler([this]() { OnConnectionError(); });
34 bindings_.push_back(binding->GetWeakPtr());
37 void CloseAllBindings() {
38 for (const auto& it : bindings_) {
39 if (it) {
40 it->Close();
41 delete it.get();
44 bindings_.clear();
47 bool empty() const { return bindings_.empty(); }
49 private:
50 void OnConnectionError() {
51 // Clear any deleted bindings.
52 bindings_.erase(
53 std::remove_if(bindings_.begin(), bindings_.end(),
54 [](const base::WeakPtr<WeakBinding<Interface>>& p) {
55 return p.get() == nullptr;
56 }),
57 bindings_.end());
59 error_handler_.Run();
62 Closure error_handler_;
63 std::vector<base::WeakPtr<WeakBinding<Interface>>> bindings_;
65 DISALLOW_COPY_AND_ASSIGN(WeakBindingSet);
68 template <typename Interface>
69 class WeakBinding {
70 public:
71 WeakBinding(Interface* impl, InterfaceRequest<Interface> request)
72 : binding_(impl, request.Pass()),
73 weak_ptr_factory_(this) {
74 binding_.set_connection_error_handler([this]() { OnConnectionError(); });
77 ~WeakBinding() {}
79 void set_connection_error_handler(const Closure& error_handler) {
80 error_handler_ = error_handler;
83 base::WeakPtr<WeakBinding> GetWeakPtr() {
84 return weak_ptr_factory_.GetWeakPtr();
87 void Close() { binding_.Close(); }
89 void OnConnectionError() {
90 Closure error_handler = error_handler_;
91 delete this;
92 error_handler.Run();
95 private:
96 Binding<Interface> binding_;
97 Closure error_handler_;
98 base::WeakPtrFactory<WeakBinding> weak_ptr_factory_;
100 DISALLOW_COPY_AND_ASSIGN(WeakBinding);
103 } // namespace mojo
105 #endif // MOJO_COMMON_WEAK_BINDING_SET_H_