summaryrefslogtreecommitdiffstats
path: root/content/public/renderer/render_frame_observer_tracker.h
blob: 7c5b332ef32e0022e7900fcff8c5eedabc3b0d3e (plain)
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
// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// Helper class used to find the RenderFrameObservers for a given RenderFrame.
//
// Example usage:
//
//   class MyRFO : public RenderFrameObserver,
//                 public RenderFrameObserverTracker<MyRFO> {
//     ...
//   };
//
//   MyRFO::MyRFO(RenderFrame* render_frame)
//       : RenderFrameObserver(render_frame),
//         RenderFrameObserverTracker<MyRFO>(render_frame) {
//     ...
//   }
//
//  void SomeFunction(RenderFrame* rf) {
//    MyRFO* my_rfo = new MyRFO(rf);
//    MyRFO* my_rfo_tracked = MyRFO::Get(rf);
//    // my_rfo == my_rfo_tracked
//  }

#ifndef CONTENT_PUBLIC_RENDERER_RENDER_FRAME_OBSERVER_TRACKER_H_
#define CONTENT_PUBLIC_RENDERER_RENDER_FRAME_OBSERVER_TRACKER_H_

#include <map>

#include "base/lazy_instance.h"

namespace content {

class RenderFrame;

template <class T>
class RenderFrameObserverTracker {
 public:
  static T* Get(const RenderFrame* render_frame) {
    return render_frame_map_.Get()[render_frame];
  }

  explicit RenderFrameObserverTracker(const RenderFrame* render_frame)
      : render_frame_(render_frame) {
    render_frame_map_.Get()[render_frame] = static_cast<T*>(this);
  }
  ~RenderFrameObserverTracker() {
    render_frame_map_.Get().erase(render_frame_);
  }

 private:
  const RenderFrame* render_frame_;

  static base::LazyInstance<std::map<const RenderFrame*, T*> >
    render_frame_map_;

  DISALLOW_COPY_AND_ASSIGN(RenderFrameObserverTracker<T>);
};

template <class T>
base::LazyInstance<std::map<const RenderFrame*, T*> >
    RenderFrameObserverTracker<T>::render_frame_map_ =
        LAZY_INSTANCE_INITIALIZER;

}  // namespace content

#endif  // CONTENT_PUBLIC_RENDERER_RENDER_FRAME_OBSERVER_TRACKER_H_