shell_window_geometry_cache.cc revision 7d4cd473f85ac64c3747c96c277f9e506a0d2246
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/extensions/extension_prefs.h"
11#include "chrome/browser/extensions/extension_prefs_factory.h"
12#include "chrome/browser/profiles/incognito_helpers.h"
13#include "chrome/browser/profiles/profile.h"
14#include "chrome/common/chrome_notification_types.h"
15#include "chrome/common/extensions/extension.h"
16#include "components/browser_context_keyed_service/browser_context_dependency_manager.h"
17#include "content/public/browser/notification_service.h"
18#include "content/public/browser/notification_types.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    ui::WindowShowState window_state) {
54  ExtensionData& extension_data = cache_[extension_id];
55
56  // If we don't have any unsynced changes and this is a duplicate of what's
57  // already in the cache, just ignore it.
58  if (extension_data[window_id].bounds == bounds &&
59      extension_data[window_id].window_state == window_state &&
60      !ContainsKey(unsynced_extensions_, extension_id))
61    return;
62
63  base::Time now = base::Time::Now();
64
65  extension_data[window_id].bounds = bounds;
66  extension_data[window_id].window_state = window_state;
67  extension_data[window_id].last_change = now;
68
69  if (extension_data.size() > kMaxCachedWindows) {
70    ExtensionData::iterator oldest = extension_data.end();
71    // Too many windows in the cache, find the oldest one to remove.
72    for (ExtensionData::iterator it = extension_data.begin();
73         it != extension_data.end(); ++it) {
74      // Don't expunge the window that was just added.
75      if (it->first == window_id) continue;
76
77      // If time is in the future, reset it to now to minimize weirdness.
78      if (it->second.last_change > now)
79        it->second.last_change = now;
80
81      if (oldest == extension_data.end() ||
82          it->second.last_change < oldest->second.last_change)
83        oldest = it;
84    }
85    extension_data.erase(oldest);
86  }
87
88  unsynced_extensions_.insert(extension_id);
89
90  // We don't use Reset() because the timer may not yet be running.
91  // (In that case Stop() is a no-op.)
92  sync_timer_.Stop();
93  sync_timer_.Start(FROM_HERE, sync_delay_, this,
94                    &ShellWindowGeometryCache::SyncToStorage);
95}
96
97void ShellWindowGeometryCache::SyncToStorage() {
98  std::set<std::string> tosync;
99  tosync.swap(unsynced_extensions_);
100  for (std::set<std::string>::const_iterator it = tosync.begin(),
101      eit = tosync.end(); it != eit; ++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(); it != eit; ++it) {
108      base::DictionaryValue* value = new base::DictionaryValue;
109      const gfx::Rect& bounds = it->second.bounds;
110      value->SetInteger("x", bounds.x());
111      value->SetInteger("y", bounds.y());
112      value->SetInteger("w", bounds.width());
113      value->SetInteger("h", bounds.height());
114      value->SetInteger("state", it->second.window_state);
115      value->SetString(
116          "ts", base::Int64ToString(it->second.last_change.ToInternalValue()));
117      dict->SetWithoutPathExpansion(it->first, value);
118    }
119    prefs_->SetGeometryCache(extension_id, dict.Pass());
120  }
121}
122
123bool ShellWindowGeometryCache::GetGeometry(
124    const std::string& extension_id,
125    const std::string& window_id,
126    gfx::Rect* bounds,
127    ui::WindowShowState* window_state) {
128
129  std::map<std::string, ExtensionData>::const_iterator
130      extension_data_it = cache_.find(extension_id);
131
132  // Not in the map means loading data for the extension didn't finish yet or
133  // the cache was not constructed until after the extension was loaded.
134  // Attempt to load from sync to address the latter case.
135  if (extension_data_it == cache_.end()) {
136    LoadGeometryFromStorage(extension_id);
137    extension_data_it = cache_.find(extension_id);
138    DCHECK(extension_data_it != cache_.end());
139  }
140
141  ExtensionData::const_iterator window_data = extension_data_it->second.find(
142      window_id);
143
144  if (window_data == extension_data_it->second.end())
145    return false;
146
147  if (bounds)
148    *bounds = window_data->second.bounds;
149  if (window_state)
150    *window_state = window_data->second.window_state;
151  return true;
152}
153
154void ShellWindowGeometryCache::Shutdown() {
155  SyncToStorage();
156}
157
158void ShellWindowGeometryCache::Observe(
159    int type, const content::NotificationSource& source,
160    const content::NotificationDetails& details) {
161  switch (type) {
162    case chrome::NOTIFICATION_EXTENSION_LOADED: {
163      std::string extension_id =
164          content::Details<const extensions::Extension>(details).ptr()->id();
165      LoadGeometryFromStorage(extension_id);
166      break;
167    }
168    case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
169      std::string extension_id =
170          content::Details<const extensions::UnloadedExtensionInfo>(details).
171              ptr()->extension->id();
172      OnExtensionUnloaded(extension_id);
173      break;
174    }
175    default:
176      NOTREACHED();
177      return;
178  }
179}
180
181void ShellWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) {
182  sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms);
183}
184
185void ShellWindowGeometryCache::LoadGeometryFromStorage(
186    const std::string& extension_id) {
187  ExtensionData& extension_data = cache_[extension_id];
188
189  const base::DictionaryValue* stored_windows =
190      prefs_->GetGeometryCache(extension_id);
191  if (!stored_windows)
192    return;
193
194  for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd();
195       it.Advance()) {
196    // If the cache already contains geometry for this window, don't
197    // overwrite that information since it is probably the result of an
198    // application starting up very quickly.
199    const std::string& window_id = it.key();
200    ExtensionData::iterator cached_window = extension_data.find(window_id);
201    if (cached_window == extension_data.end()) {
202      const base::DictionaryValue* stored_window;
203      if (it.value().GetAsDictionary(&stored_window)) {
204        WindowData& window_data = extension_data[it.key()];
205
206        int i;
207        if (stored_window->GetInteger("x", &i))
208          window_data.bounds.set_x(i);
209        if (stored_window->GetInteger("y", &i))
210          window_data.bounds.set_y(i);
211        if (stored_window->GetInteger("w", &i))
212          window_data.bounds.set_width(i);
213        if (stored_window->GetInteger("h", &i))
214          window_data.bounds.set_height(i);
215        if (stored_window->GetInteger("state", &i)) {
216          window_data.window_state =
217              static_cast<ui::WindowShowState>(i);
218        }
219        std::string ts_as_string;
220        if (stored_window->GetString("ts", &ts_as_string)) {
221          int64 ts;
222          if (base::StringToInt64(ts_as_string, &ts)) {
223            window_data.last_change = base::Time::FromInternalValue(ts);
224          }
225        }
226      }
227    }
228  }
229}
230
231void ShellWindowGeometryCache::OnExtensionUnloaded(
232    const std::string& extension_id) {
233  SyncToStorage();
234  cache_.erase(extension_id);
235}
236
237///////////////////////////////////////////////////////////////////////////////
238// Factory boilerplate
239
240// static
241ShellWindowGeometryCache* ShellWindowGeometryCache::Factory::GetForContext(
242    content::BrowserContext* context, bool create) {
243  return static_cast<ShellWindowGeometryCache*>(
244      GetInstance()->GetServiceForBrowserContext(context, create));
245}
246
247ShellWindowGeometryCache::Factory*
248ShellWindowGeometryCache::Factory::GetInstance() {
249  return Singleton<ShellWindowGeometryCache::Factory>::get();
250}
251
252ShellWindowGeometryCache::Factory::Factory()
253    : BrowserContextKeyedServiceFactory(
254        "ShellWindowGeometryCache",
255        BrowserContextDependencyManager::GetInstance()) {
256  DependsOn(extensions::ExtensionPrefsFactory::GetInstance());
257}
258
259ShellWindowGeometryCache::Factory::~Factory() {
260}
261
262BrowserContextKeyedService*
263ShellWindowGeometryCache::Factory::BuildServiceInstanceFor(
264    content::BrowserContext* context) const {
265  Profile* profile = Profile::FromBrowserContext(context);
266  return new ShellWindowGeometryCache(
267      profile,
268      extensions::ExtensionPrefs::Get(profile));
269}
270
271bool ShellWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const {
272  return false;
273}
274
275content::BrowserContext*
276ShellWindowGeometryCache::Factory::GetBrowserContextToUse(
277    content::BrowserContext* context) const {
278  return chrome::GetBrowserContextRedirectedInIncognito(context);
279}
280
281} // namespace apps
282