shell_window_geometry_cache.cc revision f2477e01787aa58f445919b809d89e252beef54f
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/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 "components/browser_context_keyed_service/browser_context_dependency_manager.h"
16#include "content/public/browser/notification_service.h"
17#include "content/public/browser/notification_types.h"
18#include "extensions/common/extension.h"
19
20namespace {
21
22// The timeout in milliseconds before we'll persist window geometry to the
23// StateStore.
24const int kSyncTimeoutMilliseconds = 1000;
25
26} // namespace
27
28namespace apps {
29
30ShellWindowGeometryCache::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
40ShellWindowGeometryCache::~ShellWindowGeometryCache() {
41}
42
43// static
44ShellWindowGeometryCache* ShellWindowGeometryCache::Get(
45    content::BrowserContext* context) {
46  return Factory::GetForContext(context, true /* create */);
47}
48
49void 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
100void 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    prefs_->SetGeometryCache(extension_id, dict.Pass());
131  }
132}
133
134bool 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) {
140
141  std::map<std::string, ExtensionData>::const_iterator
142      extension_data_it = cache_.find(extension_id);
143
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());
151  }
152
153  ExtensionData::const_iterator window_data_it = extension_data_it->second.find(
154      window_id);
155
156  if (window_data_it == extension_data_it->second.end())
157    return false;
158
159  const WindowData& window_data = window_data_it->second;
160
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;
166
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;
174}
175
176void ShellWindowGeometryCache::Shutdown() {
177  SyncToStorage();
178}
179
180
181ShellWindowGeometryCache::WindowData::WindowData()
182  : window_state(ui::SHOW_STATE_DEFAULT) {
183}
184
185ShellWindowGeometryCache::WindowData::~WindowData() {
186}
187
188void 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;
197    }
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;
204    }
205    default:
206      NOTREACHED();
207      return;
208  }
209}
210
211void ShellWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
212  sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
213}
214
215void ShellWindowGeometryCache::LoadGeometryFromStorage(
216    const std::string& extension_id) {
217  ExtensionData& extension_data = cache_[extension_id];
218
219  const base::DictionaryValue* stored_windows =
220      prefs_->GetGeometryCache(extension_id);
221  if (!stored_windows)
222    return;
223
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()];
235
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);
256        }
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);
262          }
263        }
264      }
265    }
266  }
267}
268
269void ShellWindowGeometryCache::OnExtensionUnloaded(
270    const std::string& extension_id) {
271  SyncToStorage();
272  cache_.erase(extension_id);
273}
274
275///////////////////////////////////////////////////////////////////////////////
276// Factory boilerplate
277
278// static
279ShellWindowGeometryCache* ShellWindowGeometryCache::Factory::GetForContext(
280    content::BrowserContext* context, bool create) {
281  return static_cast<ShellWindowGeometryCache*>(
282      GetInstance()->GetServiceForBrowserContext(context, create));
283}
284
285ShellWindowGeometryCache::Factory*
286ShellWindowGeometryCache::Factory::GetInstance() {
287  return Singleton<ShellWindowGeometryCache::Factory>::get();
288}
289
290ShellWindowGeometryCache::Factory::Factory()
291    : BrowserContextKeyedServiceFactory(
292        "ShellWindowGeometryCache",
293        BrowserContextDependencyManager::GetInstance()) {
294  DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
295}
296
297ShellWindowGeometryCache::Factory::~Factory() {
298}
299
300BrowserContextKeyedService*
301ShellWindowGeometryCache::Factory::BuildServiceInstanceFor(
302    content::BrowserContext* context) const {
303  Profile* profile = Profile::FromBrowserContext(context);
304  return new ShellWindowGeometryCache(
305      profile,
306      extensions::ExtensionPrefs::Get(profile));
307}
308
309bool ShellWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
310  return false;
311}
312
313content::BrowserContext*
314ShellWindowGeometryCache::Factory::GetBrowserContextToUse(
315    content::BrowserContext* context) const {
316  return chrome::GetBrowserContextRedirectedInIncognito(context);
317}
318
319} // namespace apps
320