Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / apps / app_window_geometry_cache.cc
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/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"
20
21 namespace {
22
23 // The timeout in milliseconds before we'll persist window geometry to the
24 // StateStore.
25 const int kSyncTimeoutMilliseconds = 1000;
26
27 }  // namespace
28
29 namespace apps {
30
31 AppWindowGeometryCache::AppWindowGeometryCache(
32     Profile* profile,
33     extensions::ExtensionPrefs* prefs)
34     : prefs_(prefs),
35       sync_delay_(base::TimeDelta::FromMilliseconds(kSyncTimeoutMilliseconds)) {
36   registrar_.Add(this,
37                  chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
38                  content::Source<Profile>(profile));
39   registrar_.Add(this,
40                  chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
41                  content::Source<Profile>(profile));
42 }
43
44 AppWindowGeometryCache::~AppWindowGeometryCache() {}
45
46 // static
47 AppWindowGeometryCache* AppWindowGeometryCache::Get(
48     content::BrowserContext* context) {
49   return Factory::GetForContext(context, true /* create */);
50 }
51
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];
58
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))
65     return;
66
67   base::Time now = base::Time::Now();
68
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;
73
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();
79          ++it) {
80       // Don't expunge the window that was just added.
81       if (it->first == window_id)
82         continue;
83
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;
87
88       if (oldest == extension_data.end() ||
89           it->second.last_change < oldest->second.last_change)
90         oldest = it;
91     }
92     extension_data.erase(oldest);
93   }
94
95   unsynced_extensions_.insert(extension_id);
96
97   // We don't use Reset() because the timer may not yet be running.
98   // (In that case Stop() is a no-op.)
99   sync_timer_.Stop();
100   sync_timer_.Start(
101       FROM_HERE, sync_delay_, this, &AppWindowGeometryCache::SyncToStorage);
102 }
103
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(),
108                                              eit = tosync.end();
109        it != eit;
110        ++it) {
111     const std::string& extension_id = *it;
112     const ExtensionData& extension_data = cache_[extension_id];
113
114     scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue);
115     for (ExtensionData::const_iterator it = extension_data.begin(),
116                                        eit = extension_data.end();
117          it != eit;
118          ++it) {
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);
134       value->SetString(
135           "ts", base::Int64ToString(it->second.last_change.ToInternalValue()));
136       dict->SetWithoutPathExpansion(it->first, value);
137
138       FOR_EACH_OBSERVER(
139           Observer,
140           observers_,
141           OnGeometryCacheChanged(extension_id, it->first, bounds));
142     }
143
144     prefs_->SetGeometryCache(extension_id, dict.Pass());
145   }
146 }
147
148 bool AppWindowGeometryCache::GetGeometry(const std::string& extension_id,
149                                          const std::string& window_id,
150                                          gfx::Rect* bounds,
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);
155
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());
163   }
164
165   ExtensionData::const_iterator window_data_it =
166       extension_data_it->second.find(window_id);
167
168   if (window_data_it == extension_data_it->second.end())
169     return false;
170
171   const WindowData& window_data = window_data_it->second;
172
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))
177     return false;
178
179   if (bounds)
180     *bounds = window_data.bounds;
181   if (screen_bounds)
182     *screen_bounds = window_data.screen_bounds;
183   if (window_state)
184     *window_state = window_data.window_state;
185   return true;
186 }
187
188 void AppWindowGeometryCache::Shutdown() { SyncToStorage(); }
189
190 AppWindowGeometryCache::WindowData::WindowData()
191     : window_state(ui::SHOW_STATE_DEFAULT) {}
192
193 AppWindowGeometryCache::WindowData::~WindowData() {}
194
195 void AppWindowGeometryCache::Observe(
196     int type,
197     const content::NotificationSource& source,
198     const content::NotificationDetails& details) {
199   switch (type) {
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);
204       break;
205     }
206     case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
207       std::string extension_id =
208           content::Details<const extensions::UnloadedExtensionInfo>(details)
209               .ptr()
210               ->extension->id();
211       OnExtensionUnloaded(extension_id);
212       break;
213     }
214     default:
215       NOTREACHED();
216       return;
217   }
218 }
219
220 void AppWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
221   sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
222 }
223
224 void AppWindowGeometryCache::LoadGeometryFromStorage(
225     const std::string& extension_id) {
226   ExtensionData& extension_data = cache_[extension_id];
227
228   const base::DictionaryValue* stored_windows =
229       prefs_->GetGeometryCache(extension_id);
230   if (!stored_windows)
231     return;
232
233   for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd();
234        it.Advance()) {
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()];
244
245         int i;
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);
264         }
265         std::string ts_as_string;
266         if (stored_window->GetString("ts", &ts_as_string)) {
267           int64 ts;
268           if (base::StringToInt64(ts_as_string, &ts)) {
269             window_data.last_change = base::Time::FromInternalValue(ts);
270           }
271         }
272       }
273     }
274   }
275 }
276
277 void AppWindowGeometryCache::OnExtensionUnloaded(
278     const std::string& extension_id) {
279   SyncToStorage();
280   cache_.erase(extension_id);
281 }
282
283 ///////////////////////////////////////////////////////////////////////////////
284 // Factory boilerplate
285
286 // static
287 AppWindowGeometryCache* AppWindowGeometryCache::Factory::GetForContext(
288     content::BrowserContext* context,
289     bool create) {
290   return static_cast<AppWindowGeometryCache*>(
291       GetInstance()->GetServiceForBrowserContext(context, create));
292 }
293
294 AppWindowGeometryCache::Factory*
295 AppWindowGeometryCache::Factory::GetInstance() {
296   return Singleton<AppWindowGeometryCache::Factory>::get();
297 }
298
299 AppWindowGeometryCache::Factory::Factory()
300     : BrowserContextKeyedServiceFactory(
301           "AppWindowGeometryCache",
302           BrowserContextDependencyManager::GetInstance()) {
303   DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
304 }
305
306 AppWindowGeometryCache::Factory::~Factory() {}
307
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));
313 }
314
315 bool AppWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
316   return false;
317 }
318
319 content::BrowserContext*
320 AppWindowGeometryCache::Factory::GetBrowserContextToUse(
321     content::BrowserContext* context) const {
322   return extensions::ExtensionsBrowserClient::Get()->GetOriginalContext(
323       context);
324 }
325
326 void AppWindowGeometryCache::AddObserver(Observer* observer) {
327   observers_.AddObserver(observer);
328 }
329
330 void AppWindowGeometryCache::RemoveObserver(Observer* observer) {
331   observers_.RemoveObserver(observer);
332 }
333
334 }  // namespace apps