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.
5 #ifndef ASH_WINDOW_USER_DATA_H_
6 #define ASH_WINDOW_USER_DATA_H_
12 #include "ui/aura/window.h"
13 #include "ui/aura/window_observer.h"
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()).
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 {
29 WindowUserData(const WindowUserData&) = delete;
30 WindowUserData& operator=(const WindowUserData&) = delete;
32 ~WindowUserData() override { 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);
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) {
48 if (window_to_data_.erase(window))
49 window->RemoveObserver(this);
52 if (window_to_data_.count(window) == 0u)
53 window->AddObserver(this);
54 window_to_data_[window] = std::move(data);
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();
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);
73 // aura::WindowObserver:
74 void OnWindowDestroying(aura::Window* window) override {
75 window->RemoveObserver(this);
76 window_to_data_.erase(window);
79 std::map<aura::Window*, std::unique_ptr<UserData>> window_to_data_;
84 #endif // ASH_WINDOW_USER_DATA_H_