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