Upstream version 5.34.92.0
[platform/framework/web/crosswalk.git] / src / apps / shell_window_geometry_cache.cc
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.
4
5 #include "apps/shell_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/chrome_notification_types.h"
11 #include "chrome/browser/profiles/incognito_helpers.h"
12 #include "chrome/browser/profiles/profile.h"
13 #include "components/browser_context_keyed_service/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/common/extension.h"
19
20 namespace {
21
22 // The timeout in milliseconds before we'll persist window geometry to the
23 // StateStore.
24 const int kSyncTimeoutMilliseconds = 1000;
25
26 } // namespace
27
28 namespace apps {
29
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));
38 }
39
40 ShellWindowGeometryCache::~ShellWindowGeometryCache() {
41 }
42
43 // static
44 ShellWindowGeometryCache* ShellWindowGeometryCache::Get(
45     content::BrowserContext* context) {
46   return Factory::GetForContext(context, true /* create */);
47 }
48
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];
56
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;
64
65   base::Time now = base::Time::Now();
66
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;
71
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;
79
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;
83
84       if (oldest == extension_data.end() ||
85           it->second.last_change < oldest->second.last_change)
86         oldest = it;
87     }
88     extension_data.erase(oldest);
89   }
90
91   unsynced_extensions_.insert(extension_id);
92
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);
98 }
99
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];
107
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);
129
130       FOR_EACH_OBSERVER(
131         Observer,
132         observers_,
133         OnGeometryCacheChanged(extension_id, it->first, bounds));
134     }
135
136     prefs_->SetGeometryCache(extension_id, dict.Pass());
137   }
138 }
139
140 bool ShellWindowGeometryCache::GetGeometry(
141     const std::string& extension_id,
142     const std::string& window_id,
143     gfx::Rect* bounds,
144     gfx::Rect* screen_bounds,
145     ui::WindowShowState* window_state) {
146
147   std::map<std::string, ExtensionData>::const_iterator
148       extension_data_it = 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 = extension_data_it->second.find(
160       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
182 void ShellWindowGeometryCache::Shutdown() {
183   SyncToStorage();
184 }
185
186
187 ShellWindowGeometryCache::WindowData::WindowData()
188   : window_state(ui::SHOW_STATE_DEFAULT) {
189 }
190
191 ShellWindowGeometryCache::WindowData::~WindowData() {
192 }
193
194 void ShellWindowGeometryCache::Observe(
195     int type, const content::NotificationSource& source,
196     const content::NotificationDetails& details) {
197   switch (type) {
198     case chrome::NOTIFICATION_EXTENSION_LOADED: {
199       std::string extension_id =
200           content::Details<const extensions::Extension>(details).ptr()->id();
201       LoadGeometryFromStorage(extension_id);
202       break;
203     }
204     case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
205       std::string extension_id =
206           content::Details<const extensions::UnloadedExtensionInfo>(details).
207               ptr()->extension->id();
208       OnExtensionUnloaded(extension_id);
209       break;
210     }
211     default:
212       NOTREACHED();
213       return;
214   }
215 }
216
217 void ShellWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
218   sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
219 }
220
221 void ShellWindowGeometryCache::LoadGeometryFromStorage(
222     const std::string& extension_id) {
223   ExtensionData& extension_data = cache_[extension_id];
224
225   const base::DictionaryValue* stored_windows =
226       prefs_->GetGeometryCache(extension_id);
227   if (!stored_windows)
228     return;
229
230   for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd();
231        it.Advance()) {
232     // If the cache already contains geometry for this window, don't
233     // overwrite that information since it is probably the result of an
234     // application starting up very quickly.
235     const std::string& window_id = it.key();
236     ExtensionData::iterator cached_window = extension_data.find(window_id);
237     if (cached_window == extension_data.end()) {
238       const base::DictionaryValue* stored_window;
239       if (it.value().GetAsDictionary(&stored_window)) {
240         WindowData& window_data = extension_data[it.key()];
241
242         int i;
243         if (stored_window->GetInteger("x", &i))
244           window_data.bounds.set_x(i);
245         if (stored_window->GetInteger("y", &i))
246           window_data.bounds.set_y(i);
247         if (stored_window->GetInteger("w", &i))
248           window_data.bounds.set_width(i);
249         if (stored_window->GetInteger("h", &i))
250           window_data.bounds.set_height(i);
251         if (stored_window->GetInteger("screen_bounds_x", &i))
252           window_data.screen_bounds.set_x(i);
253         if (stored_window->GetInteger("screen_bounds_y", &i))
254           window_data.screen_bounds.set_y(i);
255         if (stored_window->GetInteger("screen_bounds_w", &i))
256           window_data.screen_bounds.set_width(i);
257         if (stored_window->GetInteger("screen_bounds_h", &i))
258           window_data.screen_bounds.set_height(i);
259         if (stored_window->GetInteger("state", &i)) {
260           window_data.window_state =
261               static_cast<ui::WindowShowState>(i);
262         }
263         std::string ts_as_string;
264         if (stored_window->GetString("ts", &ts_as_string)) {
265           int64 ts;
266           if (base::StringToInt64(ts_as_string, &ts)) {
267             window_data.last_change = base::Time::FromInternalValue(ts);
268           }
269         }
270       }
271     }
272   }
273 }
274
275 void ShellWindowGeometryCache::OnExtensionUnloaded(
276     const std::string& extension_id) {
277   SyncToStorage();
278   cache_.erase(extension_id);
279 }
280
281 ///////////////////////////////////////////////////////////////////////////////
282 // Factory boilerplate
283
284 // static
285 ShellWindowGeometryCache* ShellWindowGeometryCache::Factory::GetForContext(
286     content::BrowserContext* context, bool create) {
287   return static_cast<ShellWindowGeometryCache*>(
288       GetInstance()->GetServiceForBrowserContext(context, create));
289 }
290
291 ShellWindowGeometryCache::Factory*
292 ShellWindowGeometryCache::Factory::GetInstance() {
293   return Singleton<ShellWindowGeometryCache::Factory>::get();
294 }
295
296 ShellWindowGeometryCache::Factory::Factory()
297     : BrowserContextKeyedServiceFactory(
298         "ShellWindowGeometryCache",
299         BrowserContextDependencyManager::GetInstance()) {
300   DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
301 }
302
303 ShellWindowGeometryCache::Factory::~Factory() {
304 }
305
306 BrowserContextKeyedService*
307 ShellWindowGeometryCache::Factory::BuildServiceInstanceFor(
308     content::BrowserContext* context) const {
309   Profile* profile = Profile::FromBrowserContext(context);
310   return new ShellWindowGeometryCache(
311       profile,
312       extensions::ExtensionPrefs::Get(profile));
313 }
314
315 bool ShellWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
316   return false;
317 }
318
319 content::BrowserContext*
320 ShellWindowGeometryCache::Factory::GetBrowserContextToUse(
321     content::BrowserContext* context) const {
322   return chrome::GetBrowserContextRedirectedInIncognito(context);
323 }
324
325 void ShellWindowGeometryCache::AddObserver(Observer* observer) {
326   observers_.AddObserver(observer);
327 }
328
329 void ShellWindowGeometryCache::RemoveObserver(Observer* observer) {
330   observers_.RemoveObserver(observer);
331 }
332
333 } // namespace apps