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