Revert "[M120 Migration]Fix for crash during chrome exit"
[platform/framework/web/chromium-efl.git] / ash / window_user_data.h
1 // Copyright 2016 The Chromium Authors
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 ASH_WINDOW_USER_DATA_H_
6 #define ASH_WINDOW_USER_DATA_H_
7
8 #include <map>
9 #include <memory>
10 #include <utility>
11
12 #include "ui/aura/window.h"
13 #include "ui/aura/window_observer.h"
14
15 namespace ash {
16
17 // WindowUserData provides a way to associate an object with a Window and have
18 // that object destroyed when the window is destroyed, or when WindowUserData
19 // is destroyed (from aura::WindowObserver::OnWindowDestroying()).
20 //
21 // NOTE: WindowUserData does not make use of the Set/GetProperty API offered
22 // on aura::Window. This is done to avoid collisions in the case of multiple
23 // WindowUserDatas operating on the same Window.
24 template <typename UserData>
25 class WindowUserData : public aura::WindowObserver {
26  public:
27   WindowUserData() {}
28
29   WindowUserData(const WindowUserData&) = delete;
30   WindowUserData& operator=(const WindowUserData&) = delete;
31
32   ~WindowUserData() override { clear(); }
33
34   void clear() {
35     // Take care to destroy the data after removing from the map.
36     while (!window_to_data_.empty()) {
37       auto iter = window_to_data_.begin();
38       iter->first->RemoveObserver(this);
39       std::unique_ptr<UserData> user_data = std::move(iter->second);
40       window_to_data_.erase(iter);
41     }
42   }
43
44   // Sets the data associated with window. This destroys any existing data.
45   // |data| may be null.
46   void Set(aura::Window* window, std::unique_ptr<UserData> data) {
47     if (!data) {
48       if (window_to_data_.erase(window))
49         window->RemoveObserver(this);
50       return;
51     }
52     if (window_to_data_.count(window) == 0u)
53       window->AddObserver(this);
54     window_to_data_[window] = std::move(data);
55   }
56
57   // Returns the data associated with the window, or null if none set. The
58   // returned object is owned by WindowUserData.
59   UserData* Get(aura::Window* window) {
60     auto it = window_to_data_.find(window);
61     return it == window_to_data_.end() ? nullptr : it->second.get();
62   }
63
64   // Returns the set of windows with data associated with them.
65   std::set<aura::Window*> GetWindows() {
66     std::set<aura::Window*> windows;
67     for (auto& pair : window_to_data_)
68       windows.insert(pair.first);
69     return windows;
70   }
71
72  private:
73   // aura::WindowObserver:
74   void OnWindowDestroying(aura::Window* window) override {
75     window->RemoveObserver(this);
76     window_to_data_.erase(window);
77   }
78
79   std::map<aura::Window*, std::unique_ptr<UserData>> window_to_data_;
80 };
81
82 }  // namespace ash
83
84 #endif  // ASH_WINDOW_USER_DATA_H_