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.
4
5 #include "apps/app_window_geometry_cache.h"
6
7 #include "base/bind.h"
8 #include "base/stl_util.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "chrome/browser/profiles/incognito_helpers.h"
11 #include "chrome/browser/profiles/profile.h"
12 #include "components/keyed_service/content/browser_context_dependency_manager.h"
13 #include "extensions/browser/extension_prefs.h"
14 #include "extensions/browser/extension_prefs_factory.h"
15 #include "extensions/browser/extension_registry.h"
16 #include "extensions/browser/extensions_browser_client.h"
17 #include "extensions/common/extension.h"
18
19 namespace {
20
21 // The timeout in milliseconds before we'll persist window geometry to the
22 // StateStore.
23 const int kSyncTimeoutMilliseconds = 1000;
24
25 } // namespace
26
27 namespace apps {
28
AppWindowGeometryCache(Profile * profile,extensions::ExtensionPrefs * prefs)29 AppWindowGeometryCache::AppWindowGeometryCache(
30 Profile* profile,
31 extensions::ExtensionPrefs* prefs)
32 : prefs_(prefs),
33 sync_delay_(base::TimeDelta::FromMilliseconds(kSyncTimeoutMilliseconds)),
34 extension_registry_observer_(this) {
35 extension_registry_observer_.Add(extensions::ExtensionRegistry::Get(profile));
36 }
37
~AppWindowGeometryCache()38 AppWindowGeometryCache::~AppWindowGeometryCache() {}
39
40 // static
Get(content::BrowserContext * context)41 AppWindowGeometryCache* AppWindowGeometryCache::Get(
42 content::BrowserContext* context) {
43 return Factory::GetForContext(context, true /* create */);
44 }
45
SaveGeometry(const std::string & extension_id,const std::string & window_id,const gfx::Rect & bounds,const gfx::Rect & screen_bounds,ui::WindowShowState window_state)46 void AppWindowGeometryCache::SaveGeometry(const std::string& extension_id,
47 const std::string& window_id,
48 const gfx::Rect& bounds,
49 const gfx::Rect& screen_bounds,
50 ui::WindowShowState window_state) {
51 ExtensionData& extension_data = cache_[extension_id];
52
53 // If we don't have any unsynced changes and this is a duplicate of what's
54 // already in the cache, just ignore it.
55 if (extension_data[window_id].bounds == bounds &&
56 extension_data[window_id].window_state == window_state &&
57 extension_data[window_id].screen_bounds == screen_bounds &&
58 !ContainsKey(unsynced_extensions_, extension_id))
59 return;
60
61 base::Time now = base::Time::Now();
62
63 extension_data[window_id].bounds = bounds;
64 extension_data[window_id].screen_bounds = screen_bounds;
65 extension_data[window_id].window_state = window_state;
66 extension_data[window_id].last_change = now;
67
68 if (extension_data.size() > kMaxCachedWindows) {
69 ExtensionData::iterator oldest = extension_data.end();
70 // Too many windows in the cache, find the oldest one to remove.
71 for (ExtensionData::iterator it = extension_data.begin();
72 it != extension_data.end();
73 ++it) {
74 // Don't expunge the window that was just added.
75 if (it->first == window_id)
76 continue;
77
78 // If time is in the future, reset it to now to minimize weirdness.
79 if (it->second.last_change > now)
80 it->second.last_change = now;
81
82 if (oldest == extension_data.end() ||
83 it->second.last_change < oldest->second.last_change)
84 oldest = it;
85 }
86 extension_data.erase(oldest);
87 }
88
89 unsynced_extensions_.insert(extension_id);
90
91 // We don't use Reset() because the timer may not yet be running.
92 // (In that case Stop() is a no-op.)
93 sync_timer_.Stop();
94 sync_timer_.Start(
95 FROM_HERE, sync_delay_, this, &AppWindowGeometryCache::SyncToStorage);
96 }
97
SyncToStorage()98 void AppWindowGeometryCache::SyncToStorage() {
99 std::set<std::string> tosync;
100 tosync.swap(unsynced_extensions_);
101 for (std::set<std::string>::const_iterator it = tosync.begin(),
102 eit = tosync.end();
103 it != eit;
104 ++it) {
105 const std::string& extension_id = *it;
106 const ExtensionData& extension_data = cache_[extension_id];
107
108 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
109 for (ExtensionData::const_iterator it = extension_data.begin(),
110 eit = extension_data.end();
111 it != eit;
112 ++it) {
113 base::DictionaryValue* value = new base::DictionaryValue;
114 const gfx::Rect& bounds = it->second.bounds;
115 const gfx::Rect& screen_bounds = it->second.screen_bounds;
116 DCHECK(!bounds.IsEmpty());
117 DCHECK(!screen_bounds.IsEmpty());
118 DCHECK(it->second.window_state != ui::SHOW_STATE_DEFAULT);
119 value->SetInteger("x", bounds.x());
120 value->SetInteger("y", bounds.y());
121 value->SetInteger("w", bounds.width());
122 value->SetInteger("h", bounds.height());
123 value->SetInteger("screen_bounds_x", screen_bounds.x());
124 value->SetInteger("screen_bounds_y", screen_bounds.y());
125 value->SetInteger("screen_bounds_w", screen_bounds.width());
126 value->SetInteger("screen_bounds_h", screen_bounds.height());
127 value->SetInteger("state", it->second.window_state);
128 value->SetString(
129 "ts", base::Int64ToString(it->second.last_change.ToInternalValue()));
130 dict->SetWithoutPathExpansion(it->first, value);
131
132 FOR_EACH_OBSERVER(
133 Observer,
134 observers_,
135 OnGeometryCacheChanged(extension_id, it->first, bounds));
136 }
137
138 prefs_->SetGeometryCache(extension_id, dict.Pass());
139 }
140 }
141
GetGeometry(const std::string & extension_id,const std::string & window_id,gfx::Rect * bounds,gfx::Rect * screen_bounds,ui::WindowShowState * window_state)142 bool AppWindowGeometryCache::GetGeometry(const std::string& extension_id,
143 const std::string& window_id,
144 gfx::Rect* bounds,
145 gfx::Rect* screen_bounds,
146 ui::WindowShowState* window_state) {
147 std::map<std::string, ExtensionData>::const_iterator extension_data_it =
148 cache_.find(extension_id);
149
150 // Not in the map means loading data for the extension didn't finish yet or
151 // the cache was not constructed until after the extension was loaded.
152 // Attempt to load from sync to address the latter case.
153 if (extension_data_it == cache_.end()) {
154 LoadGeometryFromStorage(extension_id);
155 extension_data_it = cache_.find(extension_id);
156 DCHECK(extension_data_it != cache_.end());
157 }
158
159 ExtensionData::const_iterator window_data_it =
160 extension_data_it->second.find(window_id);
161
162 if (window_data_it == extension_data_it->second.end())
163 return false;
164
165 const WindowData& window_data = window_data_it->second;
166
167 // Check for and do not return corrupt data.
168 if ((bounds && window_data.bounds.IsEmpty()) ||
169 (screen_bounds && window_data.screen_bounds.IsEmpty()) ||
170 (window_state && window_data.window_state == ui::SHOW_STATE_DEFAULT))
171 return false;
172
173 if (bounds)
174 *bounds = window_data.bounds;
175 if (screen_bounds)
176 *screen_bounds = window_data.screen_bounds;
177 if (window_state)
178 *window_state = window_data.window_state;
179 return true;
180 }
181
Shutdown()182 void AppWindowGeometryCache::Shutdown() { SyncToStorage(); }
183
WindowData()184 AppWindowGeometryCache::WindowData::WindowData()
185 : window_state(ui::SHOW_STATE_DEFAULT) {}
186
~WindowData()187 AppWindowGeometryCache::WindowData::~WindowData() {}
188
OnExtensionLoaded(content::BrowserContext * browser_context,const extensions::Extension * extension)189 void AppWindowGeometryCache::OnExtensionLoaded(
190 content::BrowserContext* browser_context,
191 const extensions::Extension* extension) {
192 LoadGeometryFromStorage(extension->id());
193 }
194
OnExtensionUnloaded(content::BrowserContext * browser_context,const extensions::Extension * extension,extensions::UnloadedExtensionInfo::Reason reason)195 void AppWindowGeometryCache::OnExtensionUnloaded(
196 content::BrowserContext* browser_context,
197 const extensions::Extension* extension,
198 extensions::UnloadedExtensionInfo::Reason reason) {
199 SyncToStorage();
200 cache_.erase(extension->id());
201 }
202
SetSyncDelayForTests(int timeout_ms)203 void AppWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
204 sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
205 }
206
LoadGeometryFromStorage(const std::string & extension_id)207 void AppWindowGeometryCache::LoadGeometryFromStorage(
208 const std::string& extension_id) {
209 ExtensionData& extension_data = cache_[extension_id];
210
211 const base::DictionaryValue* stored_windows =
212 prefs_->GetGeometryCache(extension_id);
213 if (!stored_windows)
214 return;
215
216 for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd();
217 it.Advance()) {
218 // If the cache already contains geometry for this window, don't
219 // overwrite that information since it is probably the result of an
220 // application starting up very quickly.
221 const std::string& window_id = it.key();
222 ExtensionData::iterator cached_window = extension_data.find(window_id);
223 if (cached_window == extension_data.end()) {
224 const base::DictionaryValue* stored_window;
225 if (it.value().GetAsDictionary(&stored_window)) {
226 WindowData& window_data = extension_data[it.key()];
227
228 int i;
229 if (stored_window->GetInteger("x", &i))
230 window_data.bounds.set_x(i);
231 if (stored_window->GetInteger("y", &i))
232 window_data.bounds.set_y(i);
233 if (stored_window->GetInteger("w", &i))
234 window_data.bounds.set_width(i);
235 if (stored_window->GetInteger("h", &i))
236 window_data.bounds.set_height(i);
237 if (stored_window->GetInteger("screen_bounds_x", &i))
238 window_data.screen_bounds.set_x(i);
239 if (stored_window->GetInteger("screen_bounds_y", &i))
240 window_data.screen_bounds.set_y(i);
241 if (stored_window->GetInteger("screen_bounds_w", &i))
242 window_data.screen_bounds.set_width(i);
243 if (stored_window->GetInteger("screen_bounds_h", &i))
244 window_data.screen_bounds.set_height(i);
245 if (stored_window->GetInteger("state", &i)) {
246 window_data.window_state = static_cast<ui::WindowShowState>(i);
247 }
248 std::string ts_as_string;
249 if (stored_window->GetString("ts", &ts_as_string)) {
250 int64 ts;
251 if (base::StringToInt64(ts_as_string, &ts)) {
252 window_data.last_change = base::Time::FromInternalValue(ts);
253 }
254 }
255 }
256 }
257 }
258 }
259
260 ///////////////////////////////////////////////////////////////////////////////
261 // Factory boilerplate
262
263 // static
GetForContext(content::BrowserContext * context,bool create)264 AppWindowGeometryCache* AppWindowGeometryCache::Factory::GetForContext(
265 content::BrowserContext* context,
266 bool create) {
267 return static_cast<AppWindowGeometryCache*>(
268 GetInstance()->GetServiceForBrowserContext(context, create));
269 }
270
271 AppWindowGeometryCache::Factory*
GetInstance()272 AppWindowGeometryCache::Factory::GetInstance() {
273 return Singleton<AppWindowGeometryCache::Factory>::get();
274 }
275
Factory()276 AppWindowGeometryCache::Factory::Factory()
277 : BrowserContextKeyedServiceFactory(
278 "AppWindowGeometryCache",
279 BrowserContextDependencyManager::GetInstance()) {
280 DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
281 }
282
~Factory()283 AppWindowGeometryCache::Factory::~Factory() {}
284
BuildServiceInstanceFor(content::BrowserContext * context) const285 KeyedService* AppWindowGeometryCache::Factory::BuildServiceInstanceFor(
286 content::BrowserContext* context) const {
287 Profile* profile = Profile::FromBrowserContext(context);
288 return new AppWindowGeometryCache(profile,
289 extensions::ExtensionPrefs::Get(profile));
290 }
291
ServiceIsNULLWhileTesting() const292 bool AppWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
293 return false;
294 }
295
296 content::BrowserContext*
GetBrowserContextToUse(content::BrowserContext * context) const297 AppWindowGeometryCache::Factory::GetBrowserContextToUse(
298 content::BrowserContext* context) const {
299 return extensions::ExtensionsBrowserClient::Get()->GetOriginalContext(
300 context);
301 }
302
AddObserver(Observer * observer)303 void AppWindowGeometryCache::AddObserver(Observer* observer) {
304 observers_.AddObserver(observer);
305 }
306
RemoveObserver(Observer * observer)307 void AppWindowGeometryCache::RemoveObserver(Observer* observer) {
308 observers_.RemoveObserver(observer);
309 }
310
311 } // namespace apps
312