Fix crash of content_shell aura due to ime.
[chromium-blink-merge.git] / apps / shell_window_geometry_cache.cc
bloba3b0bcf036afb16b3ee92ffef1546427ec13a38b
1 // Copyright (c) 2012 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/shell_window_geometry_cache.h"
7 #include "base/bind.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/extensions/extension_prefs.h"
12 #include "chrome/browser/extensions/extension_prefs_factory.h"
13 #include "chrome/browser/profiles/incognito_helpers.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/common/extensions/extension.h"
16 #include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
17 #include "content/public/browser/notification_service.h"
18 #include "content/public/browser/notification_types.h"
20 namespace {
22 // The timeout in milliseconds before we'll persist window geometry to the
23 // StateStore.
24 const int kSyncTimeoutMilliseconds = 1000;
26 } // namespace
28 namespace apps {
30 ShellWindowGeometryCache::ShellWindowGeometryCache(
31 Profile* profile, extensions::ExtensionPrefs* prefs)
32 : prefs_(prefs),
33 sync_delay_(base::TimeDelta::FromMilliseconds(kSyncTimeoutMilliseconds)) {
34 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_LOADED,
35 content::Source<Profile>(profile));
36 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
37 content::Source<Profile>(profile));
40 ShellWindowGeometryCache::~ShellWindowGeometryCache() {
43 // static
44 ShellWindowGeometryCache* ShellWindowGeometryCache::Get(
45 content::BrowserContext* context) {
46 return Factory::GetForContext(context, true /* create */);
49 void ShellWindowGeometryCache::SaveGeometry(
50 const std::string& extension_id,
51 const std::string& window_id,
52 const gfx::Rect& bounds,
53 const gfx::Rect& screen_bounds,
54 ui::WindowShowState window_state) {
55 ExtensionData& extension_data = cache_[extension_id];
57 // If we don't have any unsynced changes and this is a duplicate of what's
58 // already in the cache, just ignore it.
59 if (extension_data[window_id].bounds == bounds &&
60 extension_data[window_id].window_state == window_state &&
61 extension_data[window_id].screen_bounds == screen_bounds &&
62 !ContainsKey(unsynced_extensions_, extension_id))
63 return;
65 base::Time now = base::Time::Now();
67 extension_data[window_id].bounds = bounds;
68 extension_data[window_id].screen_bounds = screen_bounds;
69 extension_data[window_id].window_state = window_state;
70 extension_data[window_id].last_change = now;
72 if (extension_data.size() > kMaxCachedWindows) {
73 ExtensionData::iterator oldest = extension_data.end();
74 // Too many windows in the cache, find the oldest one to remove.
75 for (ExtensionData::iterator it = extension_data.begin();
76 it != extension_data.end(); ++it) {
77 // Don't expunge the window that was just added.
78 if (it->first == window_id) continue;
80 // If time is in the future, reset it to now to minimize weirdness.
81 if (it->second.last_change > now)
82 it->second.last_change = now;
84 if (oldest == extension_data.end() ||
85 it->second.last_change < oldest->second.last_change)
86 oldest = it;
88 extension_data.erase(oldest);
91 unsynced_extensions_.insert(extension_id);
93 // We don't use Reset() because the timer may not yet be running.
94 // (In that case Stop() is a no-op.)
95 sync_timer_.Stop();
96 sync_timer_.Start(FROM_HERE, sync_delay_, this,
97 &ShellWindowGeometryCache::SyncToStorage);
100 void ShellWindowGeometryCache::SyncToStorage() {
101 std::set<std::string> tosync;
102 tosync.swap(unsynced_extensions_);
103 for (std::set<std::string>::const_iterator it = tosync.begin(),
104 eit = tosync.end(); it != eit; ++it) {
105 const std::string& extension_id = *it;
106 const ExtensionData& extension_data = cache_[extension_id];
108 scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
109 for (ExtensionData::const_iterator it = extension_data.begin(),
110 eit = extension_data.end(); it != eit; ++it) {
111 base::DictionaryValue* value = new base::DictionaryValue;
112 const gfx::Rect& bounds = it->second.bounds;
113 const gfx::Rect& screen_bounds = it->second.screen_bounds;
114 DCHECK(!bounds.IsEmpty());
115 DCHECK(!screen_bounds.IsEmpty());
116 DCHECK(it->second.window_state != ui::SHOW_STATE_DEFAULT);
117 value->SetInteger("x", bounds.x());
118 value->SetInteger("y", bounds.y());
119 value->SetInteger("w", bounds.width());
120 value->SetInteger("h", bounds.height());
121 value->SetInteger("screen_bounds_x", screen_bounds.x());
122 value->SetInteger("screen_bounds_y", screen_bounds.y());
123 value->SetInteger("screen_bounds_w", screen_bounds.width());
124 value->SetInteger("screen_bounds_h", screen_bounds.height());
125 value->SetInteger("state", it->second.window_state);
126 value->SetString(
127 "ts", base::Int64ToString(it->second.last_change.ToInternalValue()));
128 dict->SetWithoutPathExpansion(it->first, value);
130 prefs_->SetGeometryCache(extension_id, dict.Pass());
134 bool ShellWindowGeometryCache::GetGeometry(
135 const std::string& extension_id,
136 const std::string& window_id,
137 gfx::Rect* bounds,
138 gfx::Rect* screen_bounds,
139 ui::WindowShowState* window_state) {
141 std::map<std::string, ExtensionData>::const_iterator
142 extension_data_it = cache_.find(extension_id);
144 // Not in the map means loading data for the extension didn't finish yet or
145 // the cache was not constructed until after the extension was loaded.
146 // Attempt to load from sync to address the latter case.
147 if (extension_data_it == cache_.end()) {
148 LoadGeometryFromStorage(extension_id);
149 extension_data_it = cache_.find(extension_id);
150 DCHECK(extension_data_it != cache_.end());
153 ExtensionData::const_iterator window_data_it = extension_data_it->second.find(
154 window_id);
156 if (window_data_it == extension_data_it->second.end())
157 return false;
159 const WindowData& window_data = window_data_it->second;
161 // Check for and do not return corrupt data.
162 if ((bounds && window_data.bounds.IsEmpty()) ||
163 (screen_bounds && window_data.screen_bounds.IsEmpty()) ||
164 (window_state && window_data.window_state == ui::SHOW_STATE_DEFAULT))
165 return false;
167 if (bounds)
168 *bounds = window_data.bounds;
169 if (screen_bounds)
170 *screen_bounds = window_data.screen_bounds;
171 if (window_state)
172 *window_state = window_data.window_state;
173 return true;
176 void ShellWindowGeometryCache::Shutdown() {
177 SyncToStorage();
181 ShellWindowGeometryCache::WindowData::WindowData()
182 : window_state(ui::SHOW_STATE_DEFAULT) {
185 ShellWindowGeometryCache::WindowData::~WindowData() {
188 void ShellWindowGeometryCache::Observe(
189 int type, const content::NotificationSource& source,
190 const content::NotificationDetails& details) {
191 switch (type) {
192 case chrome::NOTIFICATION_EXTENSION_LOADED: {
193 std::string extension_id =
194 content::Details<const extensions::Extension>(details).ptr()->id();
195 LoadGeometryFromStorage(extension_id);
196 break;
198 case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
199 std::string extension_id =
200 content::Details<const extensions::UnloadedExtensionInfo>(details).
201 ptr()->extension->id();
202 OnExtensionUnloaded(extension_id);
203 break;
205 default:
206 NOTREACHED();
207 return;
211 void ShellWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
212 sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
215 void ShellWindowGeometryCache::LoadGeometryFromStorage(
216 const std::string& extension_id) {
217 ExtensionData& extension_data = cache_[extension_id];
219 const base::DictionaryValue* stored_windows =
220 prefs_->GetGeometryCache(extension_id);
221 if (!stored_windows)
222 return;
224 for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd();
225 it.Advance()) {
226 // If the cache already contains geometry for this window, don't
227 // overwrite that information since it is probably the result of an
228 // application starting up very quickly.
229 const std::string& window_id = it.key();
230 ExtensionData::iterator cached_window = extension_data.find(window_id);
231 if (cached_window == extension_data.end()) {
232 const base::DictionaryValue* stored_window;
233 if (it.value().GetAsDictionary(&stored_window)) {
234 WindowData& window_data = extension_data[it.key()];
236 int i;
237 if (stored_window->GetInteger("x", &i))
238 window_data.bounds.set_x(i);
239 if (stored_window->GetInteger("y", &i))
240 window_data.bounds.set_y(i);
241 if (stored_window->GetInteger("w", &i))
242 window_data.bounds.set_width(i);
243 if (stored_window->GetInteger("h", &i))
244 window_data.bounds.set_height(i);
245 if (stored_window->GetInteger("screen_bounds_x", &i))
246 window_data.screen_bounds.set_x(i);
247 if (stored_window->GetInteger("screen_bounds_y", &i))
248 window_data.screen_bounds.set_y(i);
249 if (stored_window->GetInteger("screen_bounds_w", &i))
250 window_data.screen_bounds.set_width(i);
251 if (stored_window->GetInteger("screen_bounds_h", &i))
252 window_data.screen_bounds.set_height(i);
253 if (stored_window->GetInteger("state", &i)) {
254 window_data.window_state =
255 static_cast<ui::WindowShowState>(i);
257 std::string ts_as_string;
258 if (stored_window->GetString("ts", &ts_as_string)) {
259 int64 ts;
260 if (base::StringToInt64(ts_as_string, &ts)) {
261 window_data.last_change = base::Time::FromInternalValue(ts);
269 void ShellWindowGeometryCache::OnExtensionUnloaded(
270 const std::string& extension_id) {
271 SyncToStorage();
272 cache_.erase(extension_id);
275 ///////////////////////////////////////////////////////////////////////////////
276 // Factory boilerplate
278 // static
279 ShellWindowGeometryCache* ShellWindowGeometryCache::Factory::GetForContext(
280 content::BrowserContext* context, bool create) {
281 return static_cast<ShellWindowGeometryCache*>(
282 GetInstance()->GetServiceForBrowserContext(context, create));
285 ShellWindowGeometryCache::Factory*
286 ShellWindowGeometryCache::Factory::GetInstance() {
287 return Singleton<ShellWindowGeometryCache::Factory>::get();
290 ShellWindowGeometryCache::Factory::Factory()
291 : BrowserContextKeyedServiceFactory(
292 "ShellWindowGeometryCache",
293 BrowserContextDependencyManager::GetInstance()) {
294 DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
297 ShellWindowGeometryCache::Factory::~Factory() {
300 BrowserContextKeyedService*
301 ShellWindowGeometryCache::Factory::BuildServiceInstanceFor(
302 content::BrowserContext* context) const {
303 Profile* profile = Profile::FromBrowserContext(context);
304 return new ShellWindowGeometryCache(
305 profile,
306 extensions::ExtensionPrefs::Get(profile));
309 bool ShellWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
310 return false;
313 content::BrowserContext*
314 ShellWindowGeometryCache::Factory::GetBrowserContextToUse(
315 content::BrowserContext* context) const {
316 return chrome::GetBrowserContextRedirectedInIncognito(context);
319 } // namespace apps