| OLD | NEW |
| (Empty) |
| 1 // Copyright 2016 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 ASH_WM_WINDOW_USER_DATA_H_ | |
| 6 #define ASH_WM_WINDOW_USER_DATA_H_ | |
| 7 | |
| 8 #include <map> | |
| 9 #include <memory> | |
| 10 #include <utility> | |
| 11 | |
| 12 #include "ash/wm_window.h" | |
| 13 #include "base/macros.h" | |
| 14 #include "ui/aura/window.h" | |
| 15 #include "ui/aura/window_observer.h" | |
| 16 | |
| 17 namespace ash { | |
| 18 | |
| 19 // WmWindowUserData provides a way to associate arbitrary objects with a | |
| 20 // WmWindow. WmWindowUserData owns the data, deleting it either when | |
| 21 // WmWindowUserData is deleted, or when the window the data is associated with | |
| 22 // is destroyed (from aura::WindowObserver::OnWindowDestroying()). | |
| 23 template <typename UserData> | |
| 24 class WmWindowUserData : public aura::WindowObserver { | |
| 25 public: | |
| 26 WmWindowUserData() {} | |
| 27 | |
| 28 ~WmWindowUserData() override { clear(); } | |
| 29 | |
| 30 void clear() { | |
| 31 for (auto& pair : window_to_data_) | |
| 32 pair.first->aura_window()->RemoveObserver(this); | |
| 33 window_to_data_.clear(); | |
| 34 } | |
| 35 | |
| 36 // Sets the data associated with window. This destroys any existing data. | |
| 37 // |data| may be null. | |
| 38 void Set(WmWindow* window, std::unique_ptr<UserData> data) { | |
| 39 if (!data) { | |
| 40 if (window_to_data_.erase(window)) | |
| 41 window->aura_window()->RemoveObserver(this); | |
| 42 return; | |
| 43 } | |
| 44 if (window_to_data_.count(window) == 0u) | |
| 45 window->aura_window()->AddObserver(this); | |
| 46 window_to_data_[window] = std::move(data); | |
| 47 } | |
| 48 | |
| 49 // Returns the data associated with the window, or null if none set. The | |
| 50 // returned object is owned by WmWindowUserData. | |
| 51 UserData* Get(WmWindow* window) { | |
| 52 auto it = window_to_data_.find(window); | |
| 53 return it == window_to_data_.end() ? nullptr : it->second.get(); | |
| 54 } | |
| 55 | |
| 56 // Returns the set of windows with data associated with them. | |
| 57 std::set<WmWindow*> GetWindows() { | |
| 58 std::set<WmWindow*> windows; | |
| 59 for (auto& pair : window_to_data_) | |
| 60 windows.insert(pair.first); | |
| 61 return windows; | |
| 62 } | |
| 63 | |
| 64 private: | |
| 65 // aura::WindowObserver: | |
| 66 void OnWindowDestroying(aura::Window* window) override { | |
| 67 window->RemoveObserver(this); | |
| 68 window_to_data_.erase(WmWindow::Get(window)); | |
| 69 } | |
| 70 | |
| 71 std::map<WmWindow*, std::unique_ptr<UserData>> window_to_data_; | |
| 72 | |
| 73 DISALLOW_COPY_AND_ASSIGN(WmWindowUserData); | |
| 74 }; | |
| 75 | |
| 76 } // namespace ash | |
| 77 | |
| 78 #endif // ASH_WM_WINDOW_USER_DATA_H_ | |
| OLD | NEW |