• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 OSP_IMPL_SERVICE_LISTENER_IMPL_H_
6 #define OSP_IMPL_SERVICE_LISTENER_IMPL_H_
7 
8 #include <vector>
9 
10 #include "osp/impl/receiver_list.h"
11 #include "osp/impl/with_destruction_callback.h"
12 #include "osp/public/service_info.h"
13 #include "osp/public/service_listener.h"
14 #include "platform/base/macros.h"
15 
16 namespace openscreen {
17 namespace osp {
18 
19 class ServiceListenerImpl final : public ServiceListener,
20                                   public WithDestructionCallback {
21  public:
22   class Delegate {
23    public:
24     Delegate();
25 
26     void SetListenerImpl(ServiceListenerImpl* listener);
27 
28     virtual void StartListener() = 0;
29     virtual void StartAndSuspendListener() = 0;
30     virtual void StopListener() = 0;
31     virtual void SuspendListener() = 0;
32     virtual void ResumeListener() = 0;
33     virtual void SearchNow(State from) = 0;
34 
35    protected:
36     virtual ~Delegate();
SetState(State state)37     void SetState(State state) { listener_->SetState(state); }
38 
39     ServiceListenerImpl* listener_ = nullptr;
40   };
41 
42   // |delegate| is used to implement state transitions.
43   explicit ServiceListenerImpl(Delegate* delegate);
44   ~ServiceListenerImpl() override;
45 
46   // Called by |delegate_| when there are updates to the available receivers.
47   void OnReceiverAdded(const ServiceInfo& info);
48   void OnReceiverChanged(const ServiceInfo& info);
49   void OnReceiverRemoved(const ServiceInfo& info);
50   void OnAllReceiversRemoved();
51 
52   // Called by |delegate_| when an internal error occurs.
53   void OnError(ServiceListenerError error);
54 
55   // ServiceListener overrides.
56   bool Start() override;
57   bool StartAndSuspend() override;
58   bool Stop() override;
59   bool Suspend() override;
60   bool Resume() override;
61   bool SearchNow() override;
62 
63   void AddObserver(Observer* observer) override;
64   void RemoveObserver(Observer* observer) override;
65 
66   const std::vector<ServiceInfo>& GetReceivers() const override;
67 
68  private:
69   // Called by |delegate_| to transition the state machine (except kStarting and
70   // kStopping which are done automatically).
71   void SetState(State state);
72 
73   // Notifies each observer in |observers_| if the transition to |state_| is one
74   // that is watched by the observer interface.
75   void MaybeNotifyObservers();
76 
77   Delegate* const delegate_;
78   ReceiverList receiver_list_;
79 
80   OSP_DISALLOW_COPY_AND_ASSIGN(ServiceListenerImpl);
81 };
82 
83 }  // namespace osp
84 }  // namespace openscreen
85 
86 #endif  // OSP_IMPL_SERVICE_LISTENER_IMPL_H_
87