diff options
author | hashimoto@chromium.org <hashimoto@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-08-20 09:39:55 +0000 |
---|---|---|
committer | hashimoto@chromium.org <hashimoto@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2014-08-20 09:41:15 +0000 |
commit | 21d3f3af7ad25ea37d10901e915e8af0f2f3d72d (patch) | |
tree | cdb9c4999546d0df1585e4509c3d79e42f0c41ed /extensions | |
parent | b6f801cc56e0baa1436816b549617e9b3a9eeb71 (diff) | |
download | chromium_src-21d3f3af7ad25ea37d10901e915e8af0f2f3d72d.zip chromium_src-21d3f3af7ad25ea37d10901e915e8af0f2f3d72d.tar.gz chromium_src-21d3f3af7ad25ea37d10901e915e8af0f2f3d72d.tar.bz2 |
Move AppWindow related classes to extensions
Move AppDelegate, AppWebContentsHelper and AppWindowGeometryCache to extensions/browser/app_window
Change the namespace from apps to extensions.
BUG=403726
R=benwells@chromium.org
Review URL: https://codereview.chromium.org/486153002
Cr-Commit-Position: refs/heads/master@{#290796}
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@290796 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'extensions')
-rw-r--r-- | extensions/DEPS | 1 | ||||
-rw-r--r-- | extensions/browser/BUILD.gn | 5 | ||||
-rw-r--r-- | extensions/browser/app_window/app_delegate.h | 72 | ||||
-rw-r--r-- | extensions/browser/app_window/app_web_contents_helper.cc | 114 | ||||
-rw-r--r-- | extensions/browser/app_window/app_web_contents_helper.h | 73 | ||||
-rw-r--r-- | extensions/browser/app_window/app_window_geometry_cache.cc | 305 | ||||
-rw-r--r-- | extensions/browser/app_window/app_window_geometry_cache.h | 158 | ||||
-rw-r--r-- | extensions/browser/app_window/app_window_geometry_cache_unittest.cc | 364 | ||||
-rw-r--r-- | extensions/extensions.gyp | 5 |
9 files changed, 1097 insertions, 0 deletions
diff --git a/extensions/DEPS b/extensions/DEPS index 7e2496a..98f9058 100644 --- a/extensions/DEPS +++ b/extensions/DEPS @@ -32,6 +32,7 @@ specific_include_rules = { "+chrome/browser/extensions/extension_service.h", "+chrome/browser/extensions/extension_service_test_base.h", "+chrome/browser/extensions/test_extension_dir.h", + "+chrome/browser/extensions/test_extension_prefs.h", "+chrome/browser/extensions/test_extension_system.h", "+chrome/browser/ui/browser.h", "+chrome/common/chrome_paths.h", diff --git a/extensions/browser/BUILD.gn b/extensions/browser/BUILD.gn index 6bf06fb..954ba9b 100644 --- a/extensions/browser/BUILD.gn +++ b/extensions/browser/BUILD.gn @@ -126,6 +126,11 @@ source_set("browser") { "api/usb/usb_device_resource.h", "api_activity_monitor.h", "app_sorting.h", + "app_window/app_delegate.h", + "app_window/app_web_contents_helper.cc", + "app_window/app_web_contents_helper.h", + "app_window/app_window_geometry_cache.cc", + "app_window/app_window_geometry_cache.h", "app_window/native_app_window.h", "app_window/size_constraints.cc", "app_window/size_constraints.h", diff --git a/extensions/browser/app_window/app_delegate.h b/extensions/browser/app_window/app_delegate.h new file mode 100644 index 0000000..de78627 --- /dev/null +++ b/extensions/browser/app_window/app_delegate.h @@ -0,0 +1,72 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_BROWSER_APP_WINDOW_APP_DELEGATE_H_ +#define EXTENSIONS_BROWSER_APP_WINDOW_APP_DELEGATE_H_ + +#include "content/public/common/media_stream_request.h" +#include "third_party/skia/include/core/SkColor.h" +#include "ui/base/window_open_disposition.h" +#include "ui/gfx/image/image_skia.h" + +namespace content { +class BrowserContext; +class ColorChooser; +struct FileChooserParams; +struct OpenURLParams; +class WebContents; +} + +namespace gfx { +class Rect; +} + +namespace extensions { + +class Extension; + +// Interface to give packaged apps access to services in the browser, for things +// like handling links and showing UI prompts to the user. +class AppDelegate { + public: + virtual ~AppDelegate() {} + + // General initialization. + virtual void InitWebContents(content::WebContents* web_contents) = 0; + + // Link handling. + virtual content::WebContents* OpenURLFromTab( + content::BrowserContext* context, + content::WebContents* source, + const content::OpenURLParams& params) = 0; + virtual void AddNewContents(content::BrowserContext* context, + content::WebContents* new_contents, + WindowOpenDisposition disposition, + const gfx::Rect& initial_pos, + bool user_gesture, + bool* was_blocked) = 0; + + // Feature support. + virtual content::ColorChooser* ShowColorChooser( + content::WebContents* web_contents, + SkColor initial_color) = 0; + virtual void RunFileChooser(content::WebContents* tab, + const content::FileChooserParams& params) = 0; + virtual void RequestMediaAccessPermission( + content::WebContents* web_contents, + const content::MediaStreamRequest& request, + const content::MediaResponseCallback& callback, + const Extension* extension) = 0; + virtual int PreferredIconSize() = 0; + virtual gfx::ImageSkia GetAppDefaultIcon() = 0; + + // Web contents modal dialog support. + virtual void SetWebContentsBlocked(content::WebContents* web_contents, + bool blocked) = 0; + virtual bool IsWebContentsVisible(content::WebContents* web_contents) = 0; +}; + +} // namespace extensions + +#endif // EXTENSIONS_BROWSER_APP_WINDOW_APP_DELEGATE_H_ diff --git a/extensions/browser/app_window/app_web_contents_helper.cc b/extensions/browser/app_window/app_web_contents_helper.cc new file mode 100644 index 0000000..54153ac --- /dev/null +++ b/extensions/browser/app_window/app_web_contents_helper.cc @@ -0,0 +1,114 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/browser/app_window/app_web_contents_helper.h" + +#include "base/strings/stringprintf.h" +#include "content/public/browser/native_web_keyboard_event.h" +#include "content/public/browser/page_navigator.h" +#include "content/public/browser/render_view_host.h" +#include "content/public/browser/web_contents.h" +#include "extensions/browser/app_window/app_delegate.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/suggest_permission_util.h" +#include "extensions/common/extension_messages.h" +#include "extensions/common/permissions/api_permission.h" + +namespace extensions { + +AppWebContentsHelper::AppWebContentsHelper( + content::BrowserContext* browser_context, + const std::string& extension_id, + content::WebContents* web_contents, + AppDelegate* app_delegate) + : browser_context_(browser_context), + extension_id_(extension_id), + web_contents_(web_contents), + app_delegate_(app_delegate) { +} + +// static +bool AppWebContentsHelper::ShouldSuppressGestureEvent( + const blink::WebGestureEvent& event) { + // Disable pinch zooming in app windows. + return event.type == blink::WebGestureEvent::GesturePinchBegin || + event.type == blink::WebGestureEvent::GesturePinchUpdate || + event.type == blink::WebGestureEvent::GesturePinchEnd; +} + +content::WebContents* AppWebContentsHelper::OpenURLFromTab( + const content::OpenURLParams& params) const { + // Don't allow the current tab to be navigated. It would be nice to map all + // anchor tags (even those without target="_blank") to new tabs, but right + // now we can't distinguish between those and <meta> refreshes or window.href + // navigations, which we don't want to allow. + // TOOD(mihaip): Can we check for user gestures instead? + WindowOpenDisposition disposition = params.disposition; + if (disposition == CURRENT_TAB) { + AddMessageToDevToolsConsole( + content::CONSOLE_MESSAGE_LEVEL_ERROR, + base::StringPrintf( + "Can't open same-window link to \"%s\"; try target=\"_blank\".", + params.url.spec().c_str())); + return NULL; + } + + // These dispositions aren't really navigations. + if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK || + disposition == IGNORE_ACTION) { + return NULL; + } + + content::WebContents* contents = + app_delegate_->OpenURLFromTab(browser_context_, web_contents_, params); + if (!contents) { + AddMessageToDevToolsConsole( + content::CONSOLE_MESSAGE_LEVEL_ERROR, + base::StringPrintf( + "Can't navigate to \"%s\"; apps do not support navigation.", + params.url.spec().c_str())); + } + + return contents; +} + +void AppWebContentsHelper::RequestToLockMouse() const { + const Extension* extension = GetExtension(); + if (!extension) + return; + + bool has_permission = IsExtensionWithPermissionOrSuggestInConsole( + APIPermission::kPointerLock, + extension, + web_contents_->GetRenderViewHost()); + + web_contents_->GotResponseToLockMouseRequest(has_permission); +} + +void AppWebContentsHelper::RequestMediaAccessPermission( + const content::MediaStreamRequest& request, + const content::MediaResponseCallback& callback) const { + const Extension* extension = GetExtension(); + if (!extension) + return; + + app_delegate_->RequestMediaAccessPermission( + web_contents_, request, callback, extension); +} + +const Extension* AppWebContentsHelper::GetExtension() const { + return ExtensionRegistry::Get(browser_context_) + ->enabled_extensions() + .GetByID(extension_id_); +} + +void AppWebContentsHelper::AddMessageToDevToolsConsole( + content::ConsoleMessageLevel level, + const std::string& message) const { + content::RenderViewHost* rvh = web_contents_->GetRenderViewHost(); + rvh->Send(new ExtensionMsg_AddMessageToConsole( + rvh->GetRoutingID(), level, message)); +} + +} // namespace extensions diff --git a/extensions/browser/app_window/app_web_contents_helper.h b/extensions/browser/app_window/app_web_contents_helper.h new file mode 100644 index 0000000..3d17851 --- /dev/null +++ b/extensions/browser/app_window/app_web_contents_helper.h @@ -0,0 +1,73 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_BROWSER_APP_WINDOW_APP_WEB_CONTENTS_HELPER_H_ +#define EXTENSIONS_BROWSER_APP_WINDOW_APP_WEB_CONTENTS_HELPER_H_ + +#include "content/public/common/console_message_level.h" +#include "content/public/common/media_stream_request.h" + +namespace blink { +class WebGestureEvent; +} + +namespace content { +class BrowserContext; +struct OpenURLParams; +class WebContents; +} + +namespace extensions { + +class AppDelegate; +class Extension; + +// Provides common functionality for apps and launcher pages to respond to +// messages from a WebContents. +class AppWebContentsHelper { + public: + AppWebContentsHelper(content::BrowserContext* browser_context, + const std::string& extension_id, + content::WebContents* web_contents, + AppDelegate* app_delegate); + + // Returns true if the given |event| should not be handled by the renderer. + static bool ShouldSuppressGestureEvent(const blink::WebGestureEvent& event); + + // Opens a new URL inside the passed in WebContents. See WebContentsDelegate. + content::WebContents* OpenURLFromTab( + const content::OpenURLParams& params) const; + + // Requests to lock the mouse. See WebContentsDelegate. + void RequestToLockMouse() const; + + // Asks permission to use the camera and/or microphone. See + // WebContentsDelegate. + void RequestMediaAccessPermission( + const content::MediaStreamRequest& request, + const content::MediaResponseCallback& callback) const; + + private: + const Extension* GetExtension() const; + + // Helper method to add a message to the renderer's DevTools console. + void AddMessageToDevToolsConsole(content::ConsoleMessageLevel level, + const std::string& message) const; + + // The browser context with which this window is associated. + // AppWindowWebContentsDelegate does not own this object. + content::BrowserContext* browser_context_; + + const std::string extension_id_; + + content::WebContents* web_contents_; + + AppDelegate* app_delegate_; + + DISALLOW_COPY_AND_ASSIGN(AppWebContentsHelper); +}; + +} // namespace extensions + +#endif // EXTENSIONS_BROWSER_APP_WINDOW_APP_WEB_CONTENTS_HELPER_H_ diff --git a/extensions/browser/app_window/app_window_geometry_cache.cc b/extensions/browser/app_window/app_window_geometry_cache.cc new file mode 100644 index 0000000..3c3ec53 --- /dev/null +++ b/extensions/browser/app_window/app_window_geometry_cache.cc @@ -0,0 +1,305 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "extensions/browser/app_window/app_window_geometry_cache.h" + +#include "base/bind.h" +#include "base/stl_util.h" +#include "base/strings/string_number_conversions.h" +#include "components/keyed_service/content/browser_context_dependency_manager.h" +#include "extensions/browser/extension_prefs.h" +#include "extensions/browser/extension_prefs_factory.h" +#include "extensions/browser/extension_registry.h" +#include "extensions/browser/extensions_browser_client.h" +#include "extensions/common/extension.h" + +namespace { + +// The timeout in milliseconds before we'll persist window geometry to the +// StateStore. +const int kSyncTimeoutMilliseconds = 1000; + +} // namespace + +namespace extensions { + +AppWindowGeometryCache::AppWindowGeometryCache(content::BrowserContext* context, + ExtensionPrefs* prefs) + : prefs_(prefs), + sync_delay_(base::TimeDelta::FromMilliseconds(kSyncTimeoutMilliseconds)), + extension_registry_observer_(this) { + extension_registry_observer_.Add(ExtensionRegistry::Get(context)); +} + +AppWindowGeometryCache::~AppWindowGeometryCache() {} + +// static +AppWindowGeometryCache* AppWindowGeometryCache::Get( + content::BrowserContext* context) { + return Factory::GetForContext(context, true /* create */); +} + +void AppWindowGeometryCache::SaveGeometry(const std::string& extension_id, + const std::string& window_id, + const gfx::Rect& bounds, + const gfx::Rect& screen_bounds, + ui::WindowShowState window_state) { + ExtensionData& extension_data = cache_[extension_id]; + + // If we don't have any unsynced changes and this is a duplicate of what's + // already in the cache, just ignore it. + if (extension_data[window_id].bounds == bounds && + extension_data[window_id].window_state == window_state && + extension_data[window_id].screen_bounds == screen_bounds && + !ContainsKey(unsynced_extensions_, extension_id)) + return; + + base::Time now = base::Time::Now(); + + extension_data[window_id].bounds = bounds; + extension_data[window_id].screen_bounds = screen_bounds; + extension_data[window_id].window_state = window_state; + extension_data[window_id].last_change = now; + + if (extension_data.size() > kMaxCachedWindows) { + ExtensionData::iterator oldest = extension_data.end(); + // Too many windows in the cache, find the oldest one to remove. + for (ExtensionData::iterator it = extension_data.begin(); + it != extension_data.end(); + ++it) { + // Don't expunge the window that was just added. + if (it->first == window_id) + continue; + + // If time is in the future, reset it to now to minimize weirdness. + if (it->second.last_change > now) + it->second.last_change = now; + + if (oldest == extension_data.end() || + it->second.last_change < oldest->second.last_change) + oldest = it; + } + extension_data.erase(oldest); + } + + unsynced_extensions_.insert(extension_id); + + // We don't use Reset() because the timer may not yet be running. + // (In that case Stop() is a no-op.) + sync_timer_.Stop(); + sync_timer_.Start( + FROM_HERE, sync_delay_, this, &AppWindowGeometryCache::SyncToStorage); +} + +void AppWindowGeometryCache::SyncToStorage() { + std::set<std::string> tosync; + tosync.swap(unsynced_extensions_); + for (std::set<std::string>::const_iterator it = tosync.begin(), + eit = tosync.end(); + it != eit; + ++it) { + const std::string& extension_id = *it; + const ExtensionData& extension_data = cache_[extension_id]; + + scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue); + for (ExtensionData::const_iterator it = extension_data.begin(), + eit = extension_data.end(); + it != eit; + ++it) { + base::DictionaryValue* value = new base::DictionaryValue; + const gfx::Rect& bounds = it->second.bounds; + const gfx::Rect& screen_bounds = it->second.screen_bounds; + DCHECK(!bounds.IsEmpty()); + DCHECK(!screen_bounds.IsEmpty()); + DCHECK(it->second.window_state != ui::SHOW_STATE_DEFAULT); + value->SetInteger("x", bounds.x()); + value->SetInteger("y", bounds.y()); + value->SetInteger("w", bounds.width()); + value->SetInteger("h", bounds.height()); + value->SetInteger("screen_bounds_x", screen_bounds.x()); + value->SetInteger("screen_bounds_y", screen_bounds.y()); + value->SetInteger("screen_bounds_w", screen_bounds.width()); + value->SetInteger("screen_bounds_h", screen_bounds.height()); + value->SetInteger("state", it->second.window_state); + value->SetString( + "ts", base::Int64ToString(it->second.last_change.ToInternalValue())); + dict->SetWithoutPathExpansion(it->first, value); + + FOR_EACH_OBSERVER( + Observer, + observers_, + OnGeometryCacheChanged(extension_id, it->first, bounds)); + } + + prefs_->SetGeometryCache(extension_id, dict.Pass()); + } +} + +bool AppWindowGeometryCache::GetGeometry(const std::string& extension_id, + const std::string& window_id, + gfx::Rect* bounds, + gfx::Rect* screen_bounds, + ui::WindowShowState* window_state) { + std::map<std::string, ExtensionData>::const_iterator extension_data_it = + cache_.find(extension_id); + + // Not in the map means loading data for the extension didn't finish yet or + // the cache was not constructed until after the extension was loaded. + // Attempt to load from sync to address the latter case. + if (extension_data_it == cache_.end()) { + LoadGeometryFromStorage(extension_id); + extension_data_it = cache_.find(extension_id); + DCHECK(extension_data_it != cache_.end()); + } + + ExtensionData::const_iterator window_data_it = + extension_data_it->second.find(window_id); + + if (window_data_it == extension_data_it->second.end()) + return false; + + const WindowData& window_data = window_data_it->second; + + // Check for and do not return corrupt data. + if ((bounds && window_data.bounds.IsEmpty()) || + (screen_bounds && window_data.screen_bounds.IsEmpty()) || + (window_state && window_data.window_state == ui::SHOW_STATE_DEFAULT)) + return false; + + if (bounds) + *bounds = window_data.bounds; + if (screen_bounds) + *screen_bounds = window_data.screen_bounds; + if (window_state) + *window_state = window_data.window_state; + return true; +} + +void AppWindowGeometryCache::Shutdown() { SyncToStorage(); } + +AppWindowGeometryCache::WindowData::WindowData() + : window_state(ui::SHOW_STATE_DEFAULT) {} + +AppWindowGeometryCache::WindowData::~WindowData() {} + +void AppWindowGeometryCache::OnExtensionLoaded( + content::BrowserContext* browser_context, + const Extension* extension) { + LoadGeometryFromStorage(extension->id()); +} + +void AppWindowGeometryCache::OnExtensionUnloaded( + content::BrowserContext* browser_context, + const Extension* extension, + UnloadedExtensionInfo::Reason reason) { + SyncToStorage(); + cache_.erase(extension->id()); +} + +void AppWindowGeometryCache::SetSyncDelayForTests(int timeout_ms) { + sync_delay_ = base::TimeDelta::FromMilliseconds(timeout_ms); +} + +void AppWindowGeometryCache::LoadGeometryFromStorage( + const std::string& extension_id) { + ExtensionData& extension_data = cache_[extension_id]; + + const base::DictionaryValue* stored_windows = + prefs_->GetGeometryCache(extension_id); + if (!stored_windows) + return; + + for (base::DictionaryValue::Iterator it(*stored_windows); !it.IsAtEnd(); + it.Advance()) { + // If the cache already contains geometry for this window, don't + // overwrite that information since it is probably the result of an + // application starting up very quickly. + const std::string& window_id = it.key(); + ExtensionData::iterator cached_window = extension_data.find(window_id); + if (cached_window == extension_data.end()) { + const base::DictionaryValue* stored_window; + if (it.value().GetAsDictionary(&stored_window)) { + WindowData& window_data = extension_data[it.key()]; + + int i; + if (stored_window->GetInteger("x", &i)) + window_data.bounds.set_x(i); + if (stored_window->GetInteger("y", &i)) + window_data.bounds.set_y(i); + if (stored_window->GetInteger("w", &i)) + window_data.bounds.set_width(i); + if (stored_window->GetInteger("h", &i)) + window_data.bounds.set_height(i); + if (stored_window->GetInteger("screen_bounds_x", &i)) + window_data.screen_bounds.set_x(i); + if (stored_window->GetInteger("screen_bounds_y", &i)) + window_data.screen_bounds.set_y(i); + if (stored_window->GetInteger("screen_bounds_w", &i)) + window_data.screen_bounds.set_width(i); + if (stored_window->GetInteger("screen_bounds_h", &i)) + window_data.screen_bounds.set_height(i); + if (stored_window->GetInteger("state", &i)) { + window_data.window_state = static_cast<ui::WindowShowState>(i); + } + std::string ts_as_string; + if (stored_window->GetString("ts", &ts_as_string)) { + int64 ts; + if (base::StringToInt64(ts_as_string, &ts)) { + window_data.last_change = base::Time::FromInternalValue(ts); + } + } + } + } + } +} + +/////////////////////////////////////////////////////////////////////////////// +// Factory boilerplate + +// static +AppWindowGeometryCache* AppWindowGeometryCache::Factory::GetForContext( + content::BrowserContext* context, + bool create) { + return static_cast<AppWindowGeometryCache*>( + GetInstance()->GetServiceForBrowserContext(context, create)); +} + +AppWindowGeometryCache::Factory* +AppWindowGeometryCache::Factory::GetInstance() { + return Singleton<AppWindowGeometryCache::Factory>::get(); +} + +AppWindowGeometryCache::Factory::Factory() + : BrowserContextKeyedServiceFactory( + "AppWindowGeometryCache", + BrowserContextDependencyManager::GetInstance()) { + DependsOn(ExtensionPrefsFactory::GetInstance()); +} + +AppWindowGeometryCache::Factory::~Factory() {} + +KeyedService* AppWindowGeometryCache::Factory::BuildServiceInstanceFor( + content::BrowserContext* context) const { + return new AppWindowGeometryCache(context, ExtensionPrefs::Get(context)); +} + +bool AppWindowGeometryCache::Factory::ServiceIsNULLWhileTesting() const { + return false; +} + +content::BrowserContext* +AppWindowGeometryCache::Factory::GetBrowserContextToUse( + content::BrowserContext* context) const { + return ExtensionsBrowserClient::Get()->GetOriginalContext(context); +} + +void AppWindowGeometryCache::AddObserver(Observer* observer) { + observers_.AddObserver(observer); +} + +void AppWindowGeometryCache::RemoveObserver(Observer* observer) { + observers_.RemoveObserver(observer); +} + +} // namespace extensions diff --git a/extensions/browser/app_window/app_window_geometry_cache.h b/extensions/browser/app_window/app_window_geometry_cache.h new file mode 100644 index 0000000..f73ae48 --- /dev/null +++ b/extensions/browser/app_window/app_window_geometry_cache.h @@ -0,0 +1,158 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_GEOMETRY_CACHE_H_ +#define EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_GEOMETRY_CACHE_H_ + +#include <map> +#include <set> +#include <string> + +#include "base/memory/scoped_ptr.h" +#include "base/memory/singleton.h" +#include "base/observer_list.h" +#include "base/scoped_observer.h" +#include "base/time/time.h" +#include "base/timer/timer.h" +#include "base/values.h" +#include "components/keyed_service/content/browser_context_keyed_service_factory.h" +#include "components/keyed_service/core/keyed_service.h" +#include "extensions/browser/extension_registry_observer.h" +#include "ui/base/ui_base_types.h" +#include "ui/gfx/rect.h" + +namespace extensions { + +class ExtensionPrefs; +class ExtensionRegistry; + +// A cache for persisted geometry of app windows, both to not have to wait +// for IO when creating a new window, and to not cause IO on every window +// geometry change. +class AppWindowGeometryCache : public KeyedService, + public ExtensionRegistryObserver { + public: + class Factory : public BrowserContextKeyedServiceFactory { + public: + static AppWindowGeometryCache* GetForContext( + content::BrowserContext* context, + bool create); + + static Factory* GetInstance(); + + private: + friend struct DefaultSingletonTraits<Factory>; + + Factory(); + virtual ~Factory(); + + // BrowserContextKeyedServiceFactory + virtual KeyedService* BuildServiceInstanceFor( + content::BrowserContext* context) const OVERRIDE; + virtual bool ServiceIsNULLWhileTesting() const OVERRIDE; + virtual content::BrowserContext* GetBrowserContextToUse( + content::BrowserContext* context) const OVERRIDE; + }; + + class Observer { + public: + virtual void OnGeometryCacheChanged(const std::string& extension_id, + const std::string& window_id, + const gfx::Rect& bounds) = 0; + + protected: + virtual ~Observer() {} + }; + + AppWindowGeometryCache(content::BrowserContext* context, + ExtensionPrefs* prefs); + + virtual ~AppWindowGeometryCache(); + + // Returns the instance for the given browsing context. + static AppWindowGeometryCache* Get(content::BrowserContext* context); + + // Save the geometry and state associated with |extension_id| and |window_id|. + void SaveGeometry(const std::string& extension_id, + const std::string& window_id, + const gfx::Rect& bounds, + const gfx::Rect& screen_bounds, + ui::WindowShowState state); + + // Get any saved geometry and state associated with |extension_id| and + // |window_id|. If saved data exists, sets |bounds|, |screen_bounds| and + // |state| if not NULL and returns true. + bool GetGeometry(const std::string& extension_id, + const std::string& window_id, + gfx::Rect* bounds, + gfx::Rect* screen_bounds, + ui::WindowShowState* state); + + // KeyedService + virtual void Shutdown() OVERRIDE; + + void AddObserver(Observer* observer); + void RemoveObserver(Observer* observer); + + // Maximum number of windows we'll cache the geometry for per app. + static const size_t kMaxCachedWindows = 100; + + protected: + friend class AppWindowGeometryCacheTest; + + // For tests, this modifies the timeout delay for saving changes from calls + // to SaveGeometry. (Note that even if this is set to 0, you still need to + // run the message loop to see the results of any SyncToStorage call). + void SetSyncDelayForTests(int timeout_ms); + + private: + // Data stored for each window. + struct WindowData { + WindowData(); + ~WindowData(); + gfx::Rect bounds; + gfx::Rect screen_bounds; + ui::WindowShowState window_state; + base::Time last_change; + }; + + // Data stored for each extension. + typedef std::map<std::string, WindowData> ExtensionData; + + // ExtensionRegistryObserver implementation. + virtual void OnExtensionLoaded(content::BrowserContext* browser_context, + const Extension* extension) OVERRIDE; + virtual void OnExtensionUnloaded( + content::BrowserContext* browser_context, + const Extension* extension, + UnloadedExtensionInfo::Reason reason) OVERRIDE; + + void LoadGeometryFromStorage(const std::string& extension_id); + void SyncToStorage(); + + // Preferences storage. + ExtensionPrefs* prefs_; + + // Cached data. + std::map<std::string, ExtensionData> cache_; + + // Data that still needs saving. + std::set<std::string> unsynced_extensions_; + + // The timer used to save the data. + base::OneShotTimer<AppWindowGeometryCache> sync_timer_; + + // The timeout value we'll use for |sync_timer_|. + base::TimeDelta sync_delay_; + + // Listen to extension load, unloaded notifications. + ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver> + extension_registry_observer_; + + ObserverList<Observer> observers_; +}; + +} // namespace extensions + +#endif // EXTENSIONS_BROWSER_APP_WINDOW_APP_WINDOW_GEOMETRY_CACHE_H_ diff --git a/extensions/browser/app_window/app_window_geometry_cache_unittest.cc b/extensions/browser/app_window/app_window_geometry_cache_unittest.cc new file mode 100644 index 0000000..a526e7d --- /dev/null +++ b/extensions/browser/app_window/app_window_geometry_cache_unittest.cc @@ -0,0 +1,364 @@ +// Copyright 2014 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "base/memory/scoped_ptr.h" +#include "base/prefs/mock_pref_change_callback.h" +#include "base/strings/string_number_conversions.h" +#include "chrome/browser/extensions/test_extension_prefs.h" +#include "chrome/test/base/testing_profile.h" +#include "content/public/test/test_browser_thread.h" +#include "content/public/test/test_utils.h" +#include "extensions/browser/app_window/app_window_geometry_cache.h" +#include "extensions/browser/extension_prefs.h" +#include "extensions/common/extension_builder.h" +#include "extensions/common/value_builder.h" +#include "testing/gtest/include/gtest/gtest.h" + +using content::BrowserThread; + +namespace extensions { + +namespace { +const char kWindowId[] = "windowid"; +const char kWindowId2[] = "windowid2"; + +// Create a very simple extension with id. +scoped_refptr<Extension> CreateExtension(const std::string& id) { + return ExtensionBuilder() + .SetManifest(DictionaryBuilder().Set("name", "test").Set( + "version", "0.1")) + .SetID(id) + .Build(); +} + +} // namespace + +// Base class for tests. +class AppWindowGeometryCacheTest : public testing::Test { + public: + AppWindowGeometryCacheTest() + : profile_(new TestingProfile), + ui_thread_(BrowserThread::UI, &ui_message_loop_) { + prefs_.reset(new TestExtensionPrefs( + ui_message_loop_.message_loop_proxy().get())); + cache_.reset(new AppWindowGeometryCache(profile_.get(), prefs_->prefs())); + cache_->SetSyncDelayForTests(0); + } + + void AddGeometryAndLoadExtension(const std::string& extension_id, + const std::string& window_id, + const gfx::Rect& bounds, + const gfx::Rect& screen_bounds, + ui::WindowShowState state); + + // Spins the UI threads' message loops to make sure any task + // posted to sync the geometry to the value store gets a chance to run. + void WaitForSync(); + + void LoadExtension(const std::string& extension_id); + void UnloadExtension(const std::string& extension_id); + + protected: + scoped_ptr<TestingProfile> profile_; + base::MessageLoopForUI ui_message_loop_; + content::TestBrowserThread ui_thread_; + scoped_ptr<TestExtensionPrefs> prefs_; + scoped_ptr<AppWindowGeometryCache> cache_; +}; + +void AppWindowGeometryCacheTest::AddGeometryAndLoadExtension( + const std::string& extension_id, + const std::string& window_id, + const gfx::Rect& bounds, + const gfx::Rect& screen_bounds, + ui::WindowShowState state) { + scoped_ptr<base::DictionaryValue> dict(new base::DictionaryValue); + base::DictionaryValue* value = new base::DictionaryValue; + value->SetInteger("x", bounds.x()); + value->SetInteger("y", bounds.y()); + value->SetInteger("w", bounds.width()); + value->SetInteger("h", bounds.height()); + value->SetInteger("screen_bounds_x", screen_bounds.x()); + value->SetInteger("screen_bounds_y", screen_bounds.y()); + value->SetInteger("screen_bounds_w", screen_bounds.width()); + value->SetInteger("screen_bounds_h", screen_bounds.height()); + value->SetInteger("state", state); + dict->SetWithoutPathExpansion(window_id, value); + prefs_->prefs()->SetGeometryCache(extension_id, dict.Pass()); + LoadExtension(extension_id); +} + +void AppWindowGeometryCacheTest::WaitForSync() { + content::RunAllPendingInMessageLoop(); +} + +void AppWindowGeometryCacheTest::LoadExtension( + const std::string& extension_id) { + cache_->LoadGeometryFromStorage(extension_id); + WaitForSync(); +} + +void AppWindowGeometryCacheTest::UnloadExtension( + const std::string& extension_id) { + scoped_refptr<Extension> extension = CreateExtension(extension_id); + cache_->OnExtensionUnloaded( + profile_.get(), + extension.get(), + UnloadedExtensionInfo::REASON_DISABLE); + WaitForSync(); +} + +// Test getting geometry from an empty store. +TEST_F(AppWindowGeometryCacheTest, GetGeometryEmptyStore) { + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + ASSERT_FALSE(cache_->GetGeometry(extension_id, kWindowId, NULL, NULL, NULL)); +} + +// Test getting geometry for an unknown extension. +TEST_F(AppWindowGeometryCacheTest, GetGeometryUnkownExtension) { + const std::string extension_id1 = prefs_->AddExtensionAndReturnId("ext1"); + const std::string extension_id2 = prefs_->AddExtensionAndReturnId("ext2"); + AddGeometryAndLoadExtension(extension_id1, + kWindowId, + gfx::Rect(4, 5, 31, 43), + gfx::Rect(0, 0, 1600, 900), + ui::SHOW_STATE_NORMAL); + ASSERT_FALSE(cache_->GetGeometry(extension_id2, kWindowId, NULL, NULL, NULL)); +} + +// Test getting geometry for an unknown window in a known extension. +TEST_F(AppWindowGeometryCacheTest, GetGeometryUnkownWindow) { + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + AddGeometryAndLoadExtension(extension_id, + kWindowId, + gfx::Rect(4, 5, 31, 43), + gfx::Rect(0, 0, 1600, 900), + ui::SHOW_STATE_NORMAL); + ASSERT_FALSE(cache_->GetGeometry(extension_id, kWindowId2, NULL, NULL, NULL)); +} + +// Test that loading geometry, screen_bounds and state from the store works +// correctly. +TEST_F(AppWindowGeometryCacheTest, GetGeometryAndStateFromStore) { + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + gfx::Rect bounds(4, 5, 31, 43); + gfx::Rect screen_bounds(0, 0, 1600, 900); + ui::WindowShowState state = ui::SHOW_STATE_NORMAL; + AddGeometryAndLoadExtension( + extension_id, kWindowId, bounds, screen_bounds, state); + gfx::Rect new_bounds; + gfx::Rect new_screen_bounds; + ui::WindowShowState new_state = ui::SHOW_STATE_DEFAULT; + ASSERT_TRUE(cache_->GetGeometry( + extension_id, kWindowId, &new_bounds, &new_screen_bounds, &new_state)); + ASSERT_EQ(bounds, new_bounds); + ASSERT_EQ(screen_bounds, new_screen_bounds); + ASSERT_EQ(state, new_state); +} + +// Test corrupt bounds will not be loaded. +TEST_F(AppWindowGeometryCacheTest, CorruptBounds) { + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + gfx::Rect bounds; + gfx::Rect screen_bounds(0, 0, 1600, 900); + ui::WindowShowState state = ui::SHOW_STATE_NORMAL; + AddGeometryAndLoadExtension( + extension_id, kWindowId, bounds, screen_bounds, state); + gfx::Rect new_bounds; + gfx::Rect new_screen_bounds; + ui::WindowShowState new_state = ui::SHOW_STATE_DEFAULT; + ASSERT_FALSE(cache_->GetGeometry( + extension_id, kWindowId, &new_bounds, &new_screen_bounds, &new_state)); + ASSERT_TRUE(new_bounds.IsEmpty()); + ASSERT_TRUE(new_screen_bounds.IsEmpty()); + ASSERT_EQ(new_state, ui::SHOW_STATE_DEFAULT); +} + +// Test corrupt screen bounds will not be loaded. +TEST_F(AppWindowGeometryCacheTest, CorruptScreenBounds) { + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + gfx::Rect bounds(4, 5, 31, 43); + gfx::Rect screen_bounds; + ui::WindowShowState state = ui::SHOW_STATE_NORMAL; + AddGeometryAndLoadExtension( + extension_id, kWindowId, bounds, screen_bounds, state); + gfx::Rect new_bounds; + gfx::Rect new_screen_bounds; + ui::WindowShowState new_state = ui::SHOW_STATE_DEFAULT; + ASSERT_FALSE(cache_->GetGeometry( + extension_id, kWindowId, &new_bounds, &new_screen_bounds, &new_state)); + ASSERT_TRUE(new_bounds.IsEmpty()); + ASSERT_TRUE(new_screen_bounds.IsEmpty()); + ASSERT_EQ(new_state, ui::SHOW_STATE_DEFAULT); +} + +// Test corrupt state will not be loaded. +TEST_F(AppWindowGeometryCacheTest, CorruptState) { + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + gfx::Rect bounds(4, 5, 31, 43); + gfx::Rect screen_bounds(0, 0, 1600, 900); + ui::WindowShowState state = ui::SHOW_STATE_DEFAULT; + AddGeometryAndLoadExtension( + extension_id, kWindowId, bounds, screen_bounds, state); + gfx::Rect new_bounds; + gfx::Rect new_screen_bounds; + ui::WindowShowState new_state = ui::SHOW_STATE_DEFAULT; + ASSERT_FALSE(cache_->GetGeometry( + extension_id, kWindowId, &new_bounds, &new_screen_bounds, &new_state)); + ASSERT_TRUE(new_bounds.IsEmpty()); + ASSERT_TRUE(new_screen_bounds.IsEmpty()); + ASSERT_EQ(new_state, ui::SHOW_STATE_DEFAULT); +} + +// Test saving geometry, screen_bounds and state to the cache and state store, +// and reading it back. +TEST_F(AppWindowGeometryCacheTest, SaveGeometryAndStateToStore) { + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + const std::string window_id(kWindowId); + + // inform cache of extension + LoadExtension(extension_id); + + // update geometry stored in cache + gfx::Rect bounds(4, 5, 31, 43); + gfx::Rect screen_bounds(0, 0, 1600, 900); + ui::WindowShowState state = ui::SHOW_STATE_NORMAL; + cache_->SaveGeometry(extension_id, window_id, bounds, screen_bounds, state); + + // make sure that immediately reading back geometry works + gfx::Rect new_bounds; + gfx::Rect new_screen_bounds; + ui::WindowShowState new_state = ui::SHOW_STATE_DEFAULT; + ASSERT_TRUE(cache_->GetGeometry( + extension_id, window_id, &new_bounds, &new_screen_bounds, &new_state)); + ASSERT_EQ(bounds, new_bounds); + ASSERT_EQ(screen_bounds, new_screen_bounds); + ASSERT_EQ(state, new_state); + + // unload extension to force cache to save data to the state store + UnloadExtension(extension_id); + + // check if geometry got stored correctly in the state store + const base::DictionaryValue* dict = + prefs_->prefs()->GetGeometryCache(extension_id); + ASSERT_TRUE(dict); + + ASSERT_TRUE(dict->HasKey(window_id)); + int v; + ASSERT_TRUE(dict->GetInteger(window_id + ".x", &v)); + ASSERT_EQ(bounds.x(), v); + ASSERT_TRUE(dict->GetInteger(window_id + ".y", &v)); + ASSERT_EQ(bounds.y(), v); + ASSERT_TRUE(dict->GetInteger(window_id + ".w", &v)); + ASSERT_EQ(bounds.width(), v); + ASSERT_TRUE(dict->GetInteger(window_id + ".h", &v)); + ASSERT_EQ(bounds.height(), v); + ASSERT_TRUE(dict->GetInteger(window_id + ".screen_bounds_x", &v)); + ASSERT_EQ(screen_bounds.x(), v); + ASSERT_TRUE(dict->GetInteger(window_id + ".screen_bounds_y", &v)); + ASSERT_EQ(screen_bounds.y(), v); + ASSERT_TRUE(dict->GetInteger(window_id + ".screen_bounds_w", &v)); + ASSERT_EQ(screen_bounds.width(), v); + ASSERT_TRUE(dict->GetInteger(window_id + ".screen_bounds_h", &v)); + ASSERT_EQ(screen_bounds.height(), v); + ASSERT_TRUE(dict->GetInteger(window_id + ".state", &v)); + ASSERT_EQ(state, v); + + // reload extension + LoadExtension(extension_id); + // and make sure the geometry got reloaded properly too + ASSERT_TRUE(cache_->GetGeometry( + extension_id, window_id, &new_bounds, &new_screen_bounds, &new_state)); + ASSERT_EQ(bounds, new_bounds); + ASSERT_EQ(screen_bounds, new_screen_bounds); + ASSERT_EQ(state, new_state); +} + +// Tests that we won't do writes to the state store for SaveGeometry calls +// which don't change the state we already have. +TEST_F(AppWindowGeometryCacheTest, NoDuplicateWrites) { + using testing::_; + using testing::Mock; + + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + gfx::Rect bounds1(100, 200, 300, 400); + gfx::Rect bounds2(200, 400, 600, 800); + gfx::Rect bounds2_duplicate(200, 400, 600, 800); + + gfx::Rect screen_bounds1(0, 0, 1600, 900); + gfx::Rect screen_bounds2(0, 0, 1366, 768); + gfx::Rect screen_bounds2_duplicate(0, 0, 1366, 768); + + MockPrefChangeCallback observer(prefs_->pref_service()); + PrefChangeRegistrar registrar; + registrar.Init(prefs_->pref_service()); + registrar.Add("extensions.settings", observer.GetCallback()); + + // Write the first bounds - it should do > 0 writes. + EXPECT_CALL(observer, OnPreferenceChanged(_)); + cache_->SaveGeometry( + extension_id, kWindowId, bounds1, screen_bounds1, ui::SHOW_STATE_NORMAL); + WaitForSync(); + Mock::VerifyAndClearExpectations(&observer); + + // Write a different bounds - it should also do > 0 writes. + EXPECT_CALL(observer, OnPreferenceChanged(_)); + cache_->SaveGeometry( + extension_id, kWindowId, bounds2, screen_bounds1, ui::SHOW_STATE_NORMAL); + WaitForSync(); + Mock::VerifyAndClearExpectations(&observer); + + // Write a different screen bounds - it should also do > 0 writes. + EXPECT_CALL(observer, OnPreferenceChanged(_)); + cache_->SaveGeometry( + extension_id, kWindowId, bounds2, screen_bounds2, ui::SHOW_STATE_NORMAL); + WaitForSync(); + Mock::VerifyAndClearExpectations(&observer); + + // Write a different state - it should also do > 0 writes. + EXPECT_CALL(observer, OnPreferenceChanged(_)); + cache_->SaveGeometry(extension_id, + kWindowId, + bounds2, + screen_bounds2, + ui::SHOW_STATE_MAXIMIZED); + WaitForSync(); + Mock::VerifyAndClearExpectations(&observer); + + // Write a bounds, screen bounds and state that's a duplicate of what we + // already have. This should not do any writes. + EXPECT_CALL(observer, OnPreferenceChanged(_)).Times(0); + cache_->SaveGeometry(extension_id, + kWindowId, + bounds2_duplicate, + screen_bounds2_duplicate, + ui::SHOW_STATE_MAXIMIZED); + WaitForSync(); + Mock::VerifyAndClearExpectations(&observer); +} + +// Tests that no more than kMaxCachedWindows windows will be cached. +TEST_F(AppWindowGeometryCacheTest, MaxWindows) { + const std::string extension_id = prefs_->AddExtensionAndReturnId("ext1"); + // inform cache of extension + LoadExtension(extension_id); + + gfx::Rect bounds(4, 5, 31, 43); + gfx::Rect screen_bounds(0, 0, 1600, 900); + for (size_t i = 0; i < AppWindowGeometryCache::kMaxCachedWindows + 1; ++i) { + std::string window_id = "window_" + base::IntToString(i); + cache_->SaveGeometry( + extension_id, window_id, bounds, screen_bounds, ui::SHOW_STATE_NORMAL); + } + + // The first added window should no longer have cached geometry. + EXPECT_FALSE(cache_->GetGeometry(extension_id, "window_0", NULL, NULL, NULL)); + // All other windows should still exist. + for (size_t i = 1; i < AppWindowGeometryCache::kMaxCachedWindows + 1; ++i) { + std::string window_id = "window_" + base::IntToString(i); + EXPECT_TRUE(cache_->GetGeometry(extension_id, window_id, NULL, NULL, NULL)); + } +} + +} // namespace extensions diff --git a/extensions/extensions.gyp b/extensions/extensions.gyp index 83f680f..3481eeb 100644 --- a/extensions/extensions.gyp +++ b/extensions/extensions.gyp @@ -376,6 +376,11 @@ 'browser/api/usb_private/usb_private_api.h', 'browser/api_activity_monitor.h', 'browser/app_sorting.h', + 'browser/app_window/app_delegate.h', + 'browser/app_window/app_web_contents_helper.cc', + 'browser/app_window/app_web_contents_helper.h', + 'browser/app_window/app_window_geometry_cache.cc', + 'browser/app_window/app_window_geometry_cache.h', 'browser/app_window/native_app_window.h', 'browser/app_window/size_constraints.cc', 'browser/app_window/size_constraints.h', |