Upstream version 5.34.104.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/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/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,
38                  content::Source<Profile>(profile));
39   registrar_.Add(this,
40                  chrome::NOTIFICATION_EXTENSION_UNLOADED,
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
154   std::map<std::string, ExtensionData>::const_iterator extension_data_it =
155       cache_.find(extension_id);
156
157   // Not in the map means loading data for the extension didn't finish yet or
158   // the cache was not constructed until after the extension was loaded.
159   // Attempt to load from sync to address the latter case.
160   if (extension_data_it == cache_.end()) {
161     LoadGeometryFromStorage(extension_id);
162     extension_data_it = cache_.find(extension_id);
163     DCHECK(extension_data_it != cache_.end());
164   }
165
166   ExtensionData::const_iterator window_data_it =
167       extension_data_it->second.find(window_id);
168
169   if (window_data_it == extension_data_it->second.end())
170     return false;
171
172   const WindowData& window_data = window_data_it->second;
173
174   // Check for and do not return corrupt data.
175   if ((bounds && window_data.bounds.IsEmpty()) ||
176       (screen_bounds && window_data.screen_bounds.IsEmpty()) ||
177       (window_state && window_data.window_state == ui::SHOW_STATE_DEFAULT))
178     return false;
179
180   if (bounds)
181     *bounds = window_data.bounds;
182   if (screen_bounds)
183     *screen_bounds = window_data.screen_bounds;
184   if (window_state)
185     *window_state = window_data.window_state;
186   return true;
187 }
188
189 void AppWindowGeometryCache::Shutdown() { SyncToStorage(); }
190
191 AppWindowGeometryCache::WindowData::WindowData()
192     : window_state(ui::SHOW_STATE_DEFAULT) {}
193
194 AppWindowGeometryCache::WindowData::~WindowData() {}
195
196 void AppWindowGeometryCache::Observe(
197     int type,
198     const content::NotificationSource& source,
199     const content::NotificationDetails& details) {
200   switch (type) {
201     case chrome::NOTIFICATION_EXTENSION_LOADED: {
202       std::string extension_id =
203           content::Details<const extensions::Extension>(details).ptr()->id();
204       LoadGeometryFromStorage(extension_id);
205       break;
206     }
207     case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
208       std::string extension_id =
209           content::Details<const extensions::UnloadedExtensionInfo>(details)
210               .ptr()
211               ->extension->id();
212       OnExtensionUnloaded(extension_id);
213       break;
214     }
215     default:
216       NOTREACHED();
217       return;
218   }
219 }
220
221 void AppWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
222   sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
223 }
224
225 void AppWindowGeometryCache::LoadGeometryFromStorage(
226     const std::string& extension_id) {
227   ExtensionData& extension_data = cache_[extension_id];
228
229   const base::DictionaryValue* stored_windows =
230       prefs_->GetGeometryCache(extension_id);
231   if (!stored_windows)
232     return;
233
234   for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd();
235        it.Advance()) {
236     // If the cache already contains geometry for this window, don't
237     // overwrite that information since it is probably the result of an
238     // application starting up very quickly.
239     const std::string& window_id = it.key();
240     ExtensionData::iterator cached_window = extension_data.find(window_id);
241     if (cached_window == extension_data.end()) {
242       const base::DictionaryValue* stored_window;
243       if (it.value().GetAsDictionary(&stored_window)) {
244         WindowData& window_data = extension_data[it.key()];
245
246         int i;
247         if (stored_window->GetInteger("x", &i))
248           window_data.bounds.set_x(i);
249         if (stored_window->GetInteger("y", &i))
250           window_data.bounds.set_y(i);
251         if (stored_window->GetInteger("w", &i))
252           window_data.bounds.set_width(i);
253         if (stored_window->GetInteger("h", &i))
254           window_data.bounds.set_height(i);
255         if (stored_window->GetInteger("screen_bounds_x", &i))
256           window_data.screen_bounds.set_x(i);
257         if (stored_window->GetInteger("screen_bounds_y", &i))
258           window_data.screen_bounds.set_y(i);
259         if (stored_window->GetInteger("screen_bounds_w", &i))
260           window_data.screen_bounds.set_width(i);
261         if (stored_window->GetInteger("screen_bounds_h", &i))
262           window_data.screen_bounds.set_height(i);
263         if (stored_window->GetInteger("state", &i)) {
264           window_data.window_state = static_cast<ui::WindowShowState>(i);
265         }
266         std::string ts_as_string;
267         if (stored_window->GetString("ts", &ts_as_string)) {
268           int64 ts;
269           if (base::StringToInt64(ts_as_string, &ts)) {
270             window_data.last_change = base::Time::FromInternalValue(ts);
271           }
272         }
273       }
274     }
275   }
276 }
277
278 void AppWindowGeometryCache::OnExtensionUnloaded(
279     const std::string& extension_id) {
280   SyncToStorage();
281   cache_.erase(extension_id);
282 }
283
284 ///////////////////////////////////////////////////////////////////////////////
285 // Factory boilerplate
286
287 // static
288 AppWindowGeometryCache* AppWindowGeometryCache::Factory::GetForContext(
289     content::BrowserContext* context,
290     bool create) {
291   return static_cast<AppWindowGeometryCache*>(
292       GetInstance()->GetServiceForBrowserContext(context, create));
293 }
294
295 AppWindowGeometryCache::Factory*
296 AppWindowGeometryCache::Factory::GetInstance() {
297   return Singleton<AppWindowGeometryCache::Factory>::get();
298 }
299
300 AppWindowGeometryCache::Factory::Factory()
301     : BrowserContextKeyedServiceFactory(
302           "AppWindowGeometryCache",
303           BrowserContextDependencyManager::GetInstance()) {
304   DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
305 }
306
307 AppWindowGeometryCache::Factory::~Factory() {}
308
309 BrowserContextKeyedService*
310 AppWindowGeometryCache::Factory::BuildServiceInstanceFor(
311     content::BrowserContext* context) const {
312   Profile* profile = Profile::FromBrowserContext(context);
313   return new AppWindowGeometryCache(profile,
314                                     extensions::ExtensionPrefs::Get(profile));
315 }
316
317 bool AppWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
318   return false;
319 }
320
321 content::BrowserContext*
322 AppWindowGeometryCache::Factory::GetBrowserContextToUse(
323     content::BrowserContext* context) const {
324   return extensions::ExtensionsBrowserClient::Get()->GetOriginalContext(
325       context);
326 }
327
328 void AppWindowGeometryCache::AddObserver(Observer* observer) {
329   observers_.AddObserver(observer);
330 }
331
332 void AppWindowGeometryCache::RemoveObserver(Observer* observer) {
333   observers_.RemoveObserver(observer);
334 }
335
336 }  // namespace apps