1 // Copyright 2014 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.
5 #include "apps/app_window_geometry_cache.h"
8 #include "base/stl_util.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "chrome/browser/chrome_notification_types.h"
11 #include "chrome/browser/profiles/incognito_helpers.h"
12 #include "chrome/browser/profiles/profile.h"
13 #include "components/keyed_service/content/browser_context_dependency_manager.h"
14 #include "content/public/browser/notification_service.h"
15 #include "content/public/browser/notification_types.h"
16 #include "extensions/browser/extension_prefs.h"
17 #include "extensions/browser/extension_prefs_factory.h"
18 #include "extensions/browser/extensions_browser_client.h"
19 #include "extensions/common/extension.h"
23 // The timeout in milliseconds before we'll persist window geometry to the
25 const int kSyncTimeoutMilliseconds = 1000;
31 AppWindowGeometryCache::AppWindowGeometryCache(
33 extensions::ExtensionPrefs* prefs)
35 sync_delay_(base::TimeDelta::FromMilliseconds(kSyncTimeoutMilliseconds)) {
37 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
38 content::Source<Profile>(profile));
40 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
41 content::Source<Profile>(profile));
44 AppWindowGeometryCache::~AppWindowGeometryCache() {}
47 AppWindowGeometryCache* AppWindowGeometryCache::Get(
48 content::BrowserContext* context) {
49 return Factory::GetForContext(context, true /* create */);
52 void AppWindowGeometryCache::SaveGeometry(const std::string& extension_id,
53 const std::string& window_id,
54 const gfx::Rect& bounds,
55 const gfx::Rect& screen_bounds,
56 ui::WindowShowState window_state) {
57 ExtensionData& extension_data = cache_[extension_id];
59 // If we don't have any unsynced changes and this is a duplicate of what's
60 // already in the cache, just ignore it.
61 if (extension_data[window_id].bounds == bounds &&
62 extension_data[window_id].window_state == window_state &&
63 extension_data[window_id].screen_bounds == screen_bounds &&
64 !ContainsKey(unsynced_extensions_, extension_id))
67 base::Time now = base::Time::Now();
69 extension_data[window_id].bounds = bounds;
70 extension_data[window_id].screen_bounds = screen_bounds;
71 extension_data[window_id].window_state = window_state;
72 extension_data[window_id].last_change = now;
74 if (extension_data.size() > kMaxCachedWindows) {
75 ExtensionData::iterator oldest = extension_data.end();
76 // Too many windows in the cache, find the oldest one to remove.
77 for (ExtensionData::iterator it = extension_data.begin();
78 it != extension_data.end();
80 // Don't expunge the window that was just added.
81 if (it->first == window_id)
84 // If time is in the future, reset it to now to minimize weirdness.
85 if (it->second.last_change > now)
86 it->second.last_change = now;
88 if (oldest == extension_data.end() ||
89 it->second.last_change < oldest->second.last_change)
92 extension_data.erase(oldest);
95 unsynced_extensions_.insert(extension_id);
97 // We don't use Reset() because the timer may not yet be running.
98 // (In that case Stop() is a no-op.)
101 FROM_HERE, sync_delay_, this, &AppWindowGeometryCache::SyncToStorage);
104 void AppWindowGeometryCache::SyncToStorage() {
105 std::set<std::string> tosync;
106 tosync.swap(unsynced_extensions_);
107 for (std::set<std::string>::const_iterator it = tosync.begin(),
111 const std::string& extension_id = *it;
112 const ExtensionData& extension_data = cache_[extension_id];
114 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
115 for (ExtensionData::const_iterator it = extension_data.begin(),
116 eit = extension_data.end();
119 base::DictionaryValue* value = new base::DictionaryValue;
120 const gfx::Rect& bounds = it->second.bounds;
121 const gfx::Rect& screen_bounds = it->second.screen_bounds;
122 DCHECK(!bounds.IsEmpty());
123 DCHECK(!screen_bounds.IsEmpty());
124 DCHECK(it->second.window_state != ui::SHOW_STATE_DEFAULT);
125 value->SetInteger("x", bounds.x());
126 value->SetInteger("y", bounds.y());
127 value->SetInteger("w", bounds.width());
128 value->SetInteger("h", bounds.height());
129 value->SetInteger("screen_bounds_x", screen_bounds.x());
130 value->SetInteger("screen_bounds_y", screen_bounds.y());
131 value->SetInteger("screen_bounds_w", screen_bounds.width());
132 value->SetInteger("screen_bounds_h", screen_bounds.height());
133 value->SetInteger("state", it->second.window_state);
135 "ts", base::Int64ToString(it->second.last_change.ToInternalValue()));
136 dict->SetWithoutPathExpansion(it->first, value);
141 OnGeometryCacheChanged(extension_id, it->first, bounds));
144 prefs_->SetGeometryCache(extension_id, dict.Pass());
148 bool AppWindowGeometryCache::GetGeometry(const std::string& extension_id,
149 const std::string& window_id,
151 gfx::Rect* screen_bounds,
152 ui::WindowShowState* window_state) {
153 std::map<std::string, ExtensionData>::const_iterator extension_data_it =
154 cache_.find(extension_id);
156 // Not in the map means loading data for the extension didn't finish yet or
157 // the cache was not constructed until after the extension was loaded.
158 // Attempt to load from sync to address the latter case.
159 if (extension_data_it == cache_.end()) {
160 LoadGeometryFromStorage(extension_id);
161 extension_data_it = cache_.find(extension_id);
162 DCHECK(extension_data_it != cache_.end());
165 ExtensionData::const_iterator window_data_it =
166 extension_data_it->second.find(window_id);
168 if (window_data_it == extension_data_it->second.end())
171 const WindowData& window_data = window_data_it->second;
173 // Check for and do not return corrupt data.
174 if ((bounds && window_data.bounds.IsEmpty()) ||
175 (screen_bounds && window_data.screen_bounds.IsEmpty()) ||
176 (window_state && window_data.window_state == ui::SHOW_STATE_DEFAULT))
180 *bounds = window_data.bounds;
182 *screen_bounds = window_data.screen_bounds;
184 *window_state = window_data.window_state;
188 void AppWindowGeometryCache::Shutdown() { SyncToStorage(); }
190 AppWindowGeometryCache::WindowData::WindowData()
191 : window_state(ui::SHOW_STATE_DEFAULT) {}
193 AppWindowGeometryCache::WindowData::~WindowData() {}
195 void AppWindowGeometryCache::Observe(
197 const content::NotificationSource& source,
198 const content::NotificationDetails& details) {
200 case chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED: {
201 std::string extension_id =
202 content::Details<const extensions::Extension>(details).ptr()->id();
203 LoadGeometryFromStorage(extension_id);
206 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
207 std::string extension_id =
208 content::Details<const extensions::UnloadedExtensionInfo>(details)
211 OnExtensionUnloaded(extension_id);
220 void AppWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
221 sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
224 void AppWindowGeometryCache::LoadGeometryFromStorage(
225 const std::string& extension_id) {
226 ExtensionData& extension_data = cache_[extension_id];
228 const base::DictionaryValue* stored_windows =
229 prefs_->GetGeometryCache(extension_id);
233 for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd();
235 // If the cache already contains geometry for this window, don't
236 // overwrite that information since it is probably the result of an
237 // application starting up very quickly.
238 const std::string& window_id = it.key();
239 ExtensionData::iterator cached_window = extension_data.find(window_id);
240 if (cached_window == extension_data.end()) {
241 const base::DictionaryValue* stored_window;
242 if (it.value().GetAsDictionary(&stored_window)) {
243 WindowData& window_data = extension_data[it.key()];
246 if (stored_window->GetInteger("x", &i))
247 window_data.bounds.set_x(i);
248 if (stored_window->GetInteger("y", &i))
249 window_data.bounds.set_y(i);
250 if (stored_window->GetInteger("w", &i))
251 window_data.bounds.set_width(i);
252 if (stored_window->GetInteger("h", &i))
253 window_data.bounds.set_height(i);
254 if (stored_window->GetInteger("screen_bounds_x", &i))
255 window_data.screen_bounds.set_x(i);
256 if (stored_window->GetInteger("screen_bounds_y", &i))
257 window_data.screen_bounds.set_y(i);
258 if (stored_window->GetInteger("screen_bounds_w", &i))
259 window_data.screen_bounds.set_width(i);
260 if (stored_window->GetInteger("screen_bounds_h", &i))
261 window_data.screen_bounds.set_height(i);
262 if (stored_window->GetInteger("state", &i)) {
263 window_data.window_state = static_cast<ui::WindowShowState>(i);
265 std::string ts_as_string;
266 if (stored_window->GetString("ts", &ts_as_string)) {
268 if (base::StringToInt64(ts_as_string, &ts)) {
269 window_data.last_change = base::Time::FromInternalValue(ts);
277 void AppWindowGeometryCache::OnExtensionUnloaded(
278 const std::string& extension_id) {
280 cache_.erase(extension_id);
283 ///////////////////////////////////////////////////////////////////////////////
284 // Factory boilerplate
287 AppWindowGeometryCache* AppWindowGeometryCache::Factory::GetForContext(
288 content::BrowserContext* context,
290 return static_cast<AppWindowGeometryCache*>(
291 GetInstance()->GetServiceForBrowserContext(context, create));
294 AppWindowGeometryCache::Factory*
295 AppWindowGeometryCache::Factory::GetInstance() {
296 return Singleton<AppWindowGeometryCache::Factory>::get();
299 AppWindowGeometryCache::Factory::Factory()
300 : BrowserContextKeyedServiceFactory(
301 "AppWindowGeometryCache",
302 BrowserContextDependencyManager::GetInstance()) {
303 DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
306 AppWindowGeometryCache::Factory::~Factory() {}
308 KeyedService* AppWindowGeometryCache::Factory::BuildServiceInstanceFor(
309 content::BrowserContext* context) const {
310 Profile* profile = Profile::FromBrowserContext(context);
311 return new AppWindowGeometryCache(profile,
312 extensions::ExtensionPrefs::Get(profile));
315 bool AppWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
319 content::BrowserContext*
320 AppWindowGeometryCache::Factory::GetBrowserContextToUse(
321 content::BrowserContext* context) const {
322 return extensions::ExtensionsBrowserClient::Get()->GetOriginalContext(
326 void AppWindowGeometryCache::AddObserver(Observer* observer) {
327 observers_.AddObserver(observer);
330 void AppWindowGeometryCache::RemoveObserver(Observer* observer) {
331 observers_.RemoveObserver(observer);