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.
5 #include "apps/app_window.h"
9 #include "apps/app_window_geometry_cache.h"
10 #include "apps/app_window_registry.h"
11 #include "apps/apps_client.h"
12 #include "apps/size_constraints.h"
13 #include "apps/ui/native_app_window.h"
14 #include "apps/ui/web_contents_sizer.h"
15 #include "base/command_line.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/values.h"
19 #include "chrome/browser/chrome_notification_types.h"
20 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
21 #include "chrome/browser/extensions/suggest_permission_util.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "components/web_modal/web_contents_modal_dialog_manager.h"
24 #include "content/public/browser/browser_context.h"
25 #include "content/public/browser/invalidate_type.h"
26 #include "content/public/browser/navigation_entry.h"
27 #include "content/public/browser/notification_details.h"
28 #include "content/public/browser/notification_service.h"
29 #include "content/public/browser/notification_source.h"
30 #include "content/public/browser/notification_types.h"
31 #include "content/public/browser/render_view_host.h"
32 #include "content/public/browser/resource_dispatcher_host.h"
33 #include "content/public/browser/web_contents.h"
34 #include "content/public/common/media_stream_request.h"
35 #include "extensions/browser/extension_registry.h"
36 #include "extensions/browser/extension_system.h"
37 #include "extensions/browser/extensions_browser_client.h"
38 #include "extensions/browser/process_manager.h"
39 #include "extensions/browser/view_type_utils.h"
40 #include "extensions/common/extension.h"
41 #include "extensions/common/extension_messages.h"
42 #include "extensions/common/manifest_handlers/icons_handler.h"
43 #include "grit/theme_resources.h"
44 #include "third_party/skia/include/core/SkRegion.h"
45 #include "ui/base/resource/resource_bundle.h"
46 #include "ui/gfx/screen.h"
48 #if !defined(OS_MACOSX)
49 #include "apps/pref_names.h"
50 #include "base/prefs/pref_service.h"
53 using content::BrowserContext;
54 using content::ConsoleMessageLevel;
55 using content::WebContents;
56 using extensions::APIPermission;
57 using web_modal::WebContentsModalDialogHost;
58 using web_modal::WebContentsModalDialogManager;
64 const int kDefaultWidth = 512;
65 const int kDefaultHeight = 384;
67 bool IsFullscreen(int fullscreen_types) {
68 return fullscreen_types != apps::AppWindow::FULLSCREEN_TYPE_NONE;
71 void SetConstraintProperty(const std::string& name,
73 base::DictionaryValue* bounds_properties) {
74 if (value != SizeConstraints::kUnboundedSize)
75 bounds_properties->SetInteger(name, value);
77 bounds_properties->Set(name, base::Value::CreateNullValue());
80 void SetBoundsProperties(const gfx::Rect& bounds,
81 const gfx::Size& min_size,
82 const gfx::Size& max_size,
83 const std::string& bounds_name,
84 base::DictionaryValue* window_properties) {
85 scoped_ptr<base::DictionaryValue> bounds_properties(
86 new base::DictionaryValue());
88 bounds_properties->SetInteger("left", bounds.x());
89 bounds_properties->SetInteger("top", bounds.y());
90 bounds_properties->SetInteger("width", bounds.width());
91 bounds_properties->SetInteger("height", bounds.height());
93 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
94 SetConstraintProperty(
95 "minHeight", min_size.height(), bounds_properties.get());
96 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
97 SetConstraintProperty(
98 "maxHeight", max_size.height(), bounds_properties.get());
100 window_properties->Set(bounds_name, bounds_properties.release());
103 // Combines the constraints of the content and window, and returns constraints
105 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
106 const gfx::Size& content_constraints,
107 const gfx::Insets& frame_insets) {
108 gfx::Size combined_constraints(window_constraints);
109 if (content_constraints.width() > 0) {
110 combined_constraints.set_width(
111 content_constraints.width() + frame_insets.width());
113 if (content_constraints.height() > 0) {
114 combined_constraints.set_height(
115 content_constraints.height() + frame_insets.height());
117 return combined_constraints;
120 // Combines the constraints of the content and window, and returns constraints
122 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
123 const gfx::Size& content_constraints,
124 const gfx::Insets& frame_insets) {
125 gfx::Size combined_constraints(content_constraints);
126 if (window_constraints.width() > 0) {
127 combined_constraints.set_width(
128 std::max(0, window_constraints.width() - frame_insets.width()));
130 if (window_constraints.height() > 0) {
131 combined_constraints.set_height(
132 std::max(0, window_constraints.height() - frame_insets.height()));
134 return combined_constraints;
139 // AppWindow::BoundsSpecification
141 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
143 AppWindow::BoundsSpecification::BoundsSpecification()
144 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
146 AppWindow::BoundsSpecification::~BoundsSpecification() {}
148 void AppWindow::BoundsSpecification::ResetBounds() {
149 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
152 // AppWindow::CreateParams
154 AppWindow::CreateParams::CreateParams()
155 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
156 frame(AppWindow::FRAME_CHROME),
157 has_frame_color(false),
158 transparent_background(false),
159 creator_process_id(0),
160 state(ui::SHOW_STATE_DEFAULT),
164 always_on_top(false) {}
166 AppWindow::CreateParams::~CreateParams() {}
168 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
169 const gfx::Insets& frame_insets) const {
170 // Combine into a single window bounds.
171 gfx::Rect combined_bounds(window_spec.bounds);
172 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
173 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
174 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
175 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
176 if (content_spec.bounds.width() > 0) {
177 combined_bounds.set_width(
178 content_spec.bounds.width() + frame_insets.width());
180 if (content_spec.bounds.height() > 0) {
181 combined_bounds.set_height(
182 content_spec.bounds.height() + frame_insets.height());
185 // Constrain the bounds.
186 SizeConstraints constraints(
187 GetCombinedWindowConstraints(
188 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
189 GetCombinedWindowConstraints(
190 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
191 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
193 return combined_bounds;
196 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
197 const gfx::Insets& frame_insets) const {
198 return GetCombinedContentConstraints(window_spec.minimum_size,
199 content_spec.minimum_size,
203 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
204 const gfx::Insets& frame_insets) const {
205 return GetCombinedContentConstraints(window_spec.maximum_size,
206 content_spec.maximum_size,
210 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
211 const gfx::Insets& frame_insets) const {
212 return GetCombinedWindowConstraints(window_spec.minimum_size,
213 content_spec.minimum_size,
217 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
218 const gfx::Insets& frame_insets) const {
219 return GetCombinedWindowConstraints(window_spec.maximum_size,
220 content_spec.maximum_size,
224 // AppWindow::Delegate
226 AppWindow::Delegate::~Delegate() {}
230 AppWindow::AppWindow(BrowserContext* context,
232 const extensions::Extension* extension)
233 : browser_context_(context),
234 extension_id_(extension->id()),
235 window_type_(WINDOW_TYPE_DEFAULT),
237 image_loader_ptr_factory_(this),
238 fullscreen_types_(FULLSCREEN_TYPE_NONE),
239 show_on_first_paint_(false),
240 first_paint_complete_(false),
241 cached_always_on_top_(false) {
242 extensions::ExtensionsBrowserClient* client =
243 extensions::ExtensionsBrowserClient::Get();
244 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
245 << "Only off the record window may be opened in the guest mode.";
248 void AppWindow::Init(const GURL& url,
249 AppWindowContents* app_window_contents,
250 const CreateParams& params) {
251 // Initialize the render interface and web contents
252 app_window_contents_.reset(app_window_contents);
253 app_window_contents_->Initialize(browser_context(), url);
254 WebContents* web_contents = app_window_contents_->GetWebContents();
255 if (CommandLine::ForCurrentProcess()->HasSwitch(
256 switches::kEnableAppsShowOnFirstPaint)) {
257 content::WebContentsObserver::Observe(web_contents);
259 delegate_->InitWebContents(web_contents);
260 WebContentsModalDialogManager::CreateForWebContents(web_contents);
261 // TODO(jamescook): Delegate out this creation.
262 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
265 web_contents->SetDelegate(this);
266 WebContentsModalDialogManager::FromWebContents(web_contents)
268 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_WINDOW);
270 // Initialize the window
271 CreateParams new_params = LoadDefaults(params);
272 window_type_ = new_params.window_type;
273 window_key_ = new_params.window_key;
275 // Windows cannot be always-on-top in fullscreen mode for security reasons.
276 cached_always_on_top_ = new_params.always_on_top;
277 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
278 new_params.always_on_top = false;
280 native_app_window_.reset(delegate_->CreateNativeAppWindow(this, new_params));
282 if (new_params.hidden) {
283 // Although the window starts hidden by default, calling Hide() here
284 // notifies observers of the window being hidden.
287 // Panels are not activated by default.
288 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
292 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
294 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
296 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
299 OnNativeWindowChanged();
301 // When the render view host is changed, the native window needs to know
302 // about it in case it has any setup to do to make the renderer appear
303 // properly. In particular, on Windows, the view's clickthrough region needs
305 extensions::ExtensionsBrowserClient* client =
306 extensions::ExtensionsBrowserClient::Get();
308 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
309 content::Source<content::BrowserContext>(
310 client->GetOriginalContext(browser_context_)));
311 // Close when the browser process is exiting.
313 chrome::NOTIFICATION_APP_TERMINATING,
314 content::NotificationService::AllSources());
315 // Update the app menu if an ephemeral app becomes installed.
317 chrome::NOTIFICATION_EXTENSION_INSTALLED,
318 content::Source<content::BrowserContext>(
319 client->GetOriginalContext(browser_context_)));
321 app_window_contents_->LoadContents(new_params.creator_process_id);
323 if (CommandLine::ForCurrentProcess()->HasSwitch(
324 switches::kEnableAppsShowOnFirstPaint)) {
325 // We want to show the window only when the content has been painted. For
326 // that to happen, we need to define a size for the content, otherwise the
327 // layout will happen in a 0x0 area.
328 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
329 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
330 initial_bounds.Inset(frame_insets);
331 apps::ResizeWebContents(web_contents, initial_bounds.size());
334 // Prevent the browser process from shutting down while this window is open.
335 AppsClient::Get()->IncrementKeepAliveCount();
337 UpdateExtensionAppIcon();
339 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
342 AppWindow::~AppWindow() {
343 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
345 registrar_.RemoveAll();
347 // Remove shutdown prevention.
348 AppsClient::Get()->DecrementKeepAliveCount();
351 void AppWindow::RequestMediaAccessPermission(
352 content::WebContents* web_contents,
353 const content::MediaStreamRequest& request,
354 const content::MediaResponseCallback& callback) {
355 const extensions::Extension* extension = GetExtension();
359 delegate_->RequestMediaAccessPermission(
360 web_contents, request, callback, extension);
363 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
364 const content::OpenURLParams& params) {
365 // Don't allow the current tab to be navigated. It would be nice to map all
366 // anchor tags (even those without target="_blank") to new tabs, but right
367 // now we can't distinguish between those and <meta> refreshes or window.href
368 // navigations, which we don't want to allow.
369 // TOOD(mihaip): Can we check for user gestures instead?
370 WindowOpenDisposition disposition = params.disposition;
371 if (disposition == CURRENT_TAB) {
372 AddMessageToDevToolsConsole(
373 content::CONSOLE_MESSAGE_LEVEL_ERROR,
375 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
376 params.url.spec().c_str()));
380 // These dispositions aren't really navigations.
381 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
382 disposition == IGNORE_ACTION) {
386 WebContents* contents =
387 delegate_->OpenURLFromTab(browser_context_, source, params);
389 AddMessageToDevToolsConsole(
390 content::CONSOLE_MESSAGE_LEVEL_ERROR,
392 "Can't navigate to \"%s\"; apps do not support navigation.",
393 params.url.spec().c_str()));
399 void AppWindow::AddNewContents(WebContents* source,
400 WebContents* new_contents,
401 WindowOpenDisposition disposition,
402 const gfx::Rect& initial_pos,
405 DCHECK(new_contents->GetBrowserContext() == browser_context_);
406 delegate_->AddNewContents(browser_context_,
414 bool AppWindow::PreHandleKeyboardEvent(
415 content::WebContents* source,
416 const content::NativeWebKeyboardEvent& event,
417 bool* is_keyboard_shortcut) {
418 const extensions::Extension* extension = GetExtension();
422 // Here, we can handle a key event before the content gets it. When we are
423 // fullscreen and it is not forced, we want to allow the user to leave
424 // when ESC is pressed.
425 // However, if the application has the "overrideEscFullscreen" permission, we
426 // should let it override that behavior.
427 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
428 // action is not prevented.
429 // Thus, we should handle the KeyEvent here only if the permission is not set.
430 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
431 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
432 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0) &&
433 !extension->HasAPIPermission(APIPermission::kOverrideEscFullscreen)) {
441 void AppWindow::HandleKeyboardEvent(
443 const content::NativeWebKeyboardEvent& event) {
444 // If the window is currently fullscreen and not forced, ESC should leave
445 // fullscreen. If this code is being called for ESC, that means that the
446 // KeyEvent's default behavior was not prevented by the content.
447 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
448 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
449 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0)) {
454 native_app_window_->HandleKeyboardEvent(event);
457 void AppWindow::RequestToLockMouse(WebContents* web_contents,
459 bool last_unlocked_by_target) {
460 const extensions::Extension* extension = GetExtension();
464 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
465 APIPermission::kPointerLock,
467 web_contents->GetRenderViewHost());
469 web_contents->GotResponseToLockMouseRequest(has_permission);
472 bool AppWindow::PreHandleGestureEvent(WebContents* source,
473 const blink::WebGestureEvent& event) {
474 // Disable pinch zooming in app windows.
475 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
476 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
477 event.type == blink::WebGestureEvent::GesturePinchEnd;
480 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
481 first_paint_complete_ = true;
482 if (show_on_first_paint_) {
483 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
484 delayed_show_type_ == SHOW_INACTIVE);
485 Show(delayed_show_type_);
489 void AppWindow::OnNativeClose() {
490 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
491 if (app_window_contents_) {
492 WebContents* web_contents = app_window_contents_->GetWebContents();
493 WebContentsModalDialogManager::FromWebContents(web_contents)
495 app_window_contents_->NativeWindowClosed();
500 void AppWindow::OnNativeWindowChanged() {
501 SaveWindowPosition();
504 if (native_app_window_ && cached_always_on_top_ &&
505 !IsFullscreen(fullscreen_types_) && !native_app_window_->IsMaximized() &&
506 !native_app_window_->IsMinimized()) {
507 UpdateNativeAlwaysOnTop();
511 if (app_window_contents_ && native_app_window_)
512 app_window_contents_->NativeWindowChanged(native_app_window_.get());
515 void AppWindow::OnNativeWindowActivated() {
516 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
519 content::WebContents* AppWindow::web_contents() const {
520 return app_window_contents_->GetWebContents();
523 const extensions::Extension* AppWindow::GetExtension() const {
524 return extensions::ExtensionRegistry::Get(browser_context_)
525 ->enabled_extensions()
526 .GetByID(extension_id_);
529 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
531 gfx::NativeWindow AppWindow::GetNativeWindow() {
532 return GetBaseWindow()->GetNativeWindow();
535 gfx::Rect AppWindow::GetClientBounds() const {
536 gfx::Rect bounds = native_app_window_->GetBounds();
537 bounds.Inset(native_app_window_->GetFrameInsets());
541 base::string16 AppWindow::GetTitle() const {
542 base::string16 title;
543 const extensions::Extension* extension = GetExtension();
547 // WebContents::GetTitle() will return the page's URL if there's no <title>
548 // specified. However, we'd prefer to show the name of the extension in that
549 // case, so we directly inspect the NavigationEntry's title.
550 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
551 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
552 title = base::UTF8ToUTF16(extension->name());
554 title = web_contents()->GetTitle();
556 const base::char16 kBadChars[] = {'\n', 0};
557 base::RemoveChars(title, kBadChars, &title);
561 void AppWindow::SetAppIconUrl(const GURL& url) {
562 // If the same url is being used for the badge, ignore it.
563 if (url == badge_icon_url_)
566 // Avoid using any previous icons that were being downloaded.
567 image_loader_ptr_factory_.InvalidateWeakPtrs();
569 // Reset |app_icon_image_| to abort pending image load (if any).
570 app_icon_image_.reset();
573 web_contents()->DownloadImage(
575 true, // is a favicon
576 0, // no maximum size
577 base::Bind(&AppWindow::DidDownloadFavicon,
578 image_loader_ptr_factory_.GetWeakPtr()));
581 void AppWindow::SetBadgeIconUrl(const GURL& url) {
582 // Avoid using any previous icons that were being downloaded.
583 image_loader_ptr_factory_.InvalidateWeakPtrs();
585 // Reset |app_icon_image_| to abort pending image load (if any).
586 badge_icon_image_.reset();
588 badge_icon_url_ = url;
589 web_contents()->DownloadImage(
591 true, // is a favicon
592 0, // no maximum size
593 base::Bind(&AppWindow::DidDownloadFavicon,
594 image_loader_ptr_factory_.GetWeakPtr()));
597 void AppWindow::ClearBadge() {
598 badge_icon_image_.reset();
599 badge_icon_url_ = GURL();
600 UpdateBadgeIcon(gfx::Image());
603 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
604 native_app_window_->UpdateShape(region.Pass());
607 void AppWindow::UpdateDraggableRegions(
608 const std::vector<extensions::DraggableRegion>& regions) {
609 native_app_window_->UpdateDraggableRegions(regions);
612 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
616 native_app_window_->UpdateWindowIcon();
617 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
620 void AppWindow::Fullscreen() {
621 #if !defined(OS_MACOSX)
622 // Do not enter fullscreen mode if disallowed by pref.
624 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
626 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
629 fullscreen_types_ |= FULLSCREEN_TYPE_WINDOW_API;
630 SetNativeWindowFullscreen();
633 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
635 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
637 void AppWindow::Restore() {
638 if (IsFullscreen(fullscreen_types_)) {
639 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
640 SetNativeWindowFullscreen();
642 GetBaseWindow()->Restore();
646 void AppWindow::OSFullscreen() {
647 #if !defined(OS_MACOSX)
648 // Do not enter fullscreen mode if disallowed by pref.
650 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
652 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
655 fullscreen_types_ |= FULLSCREEN_TYPE_OS;
656 SetNativeWindowFullscreen();
659 void AppWindow::ForcedFullscreen() {
660 fullscreen_types_ |= FULLSCREEN_TYPE_FORCED;
661 SetNativeWindowFullscreen();
664 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
665 const gfx::Size& max_size) {
666 SizeConstraints constraints(min_size, max_size);
667 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
668 constraints.GetMaximumSize());
670 gfx::Rect bounds = GetClientBounds();
671 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
672 if (bounds.size() != constrained_size) {
673 bounds.set_size(constrained_size);
674 bounds.Inset(-native_app_window_->GetFrameInsets());
675 native_app_window_->SetBounds(bounds);
677 OnNativeWindowChanged();
680 void AppWindow::Show(ShowType show_type) {
681 if (CommandLine::ForCurrentProcess()->HasSwitch(
682 switches::kEnableAppsShowOnFirstPaint)) {
683 show_on_first_paint_ = true;
685 if (!first_paint_complete_) {
686 delayed_show_type_ = show_type;
693 GetBaseWindow()->Show();
696 GetBaseWindow()->ShowInactive();
699 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this);
702 void AppWindow::Hide() {
703 // This is there to prevent race conditions with Hide() being called before
704 // there was a non-empty paint. It should have no effect in a non-racy
705 // scenario where the application is hiding then showing a window: the second
706 // show will not be delayed.
707 show_on_first_paint_ = false;
708 GetBaseWindow()->Hide();
709 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
712 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
713 if (cached_always_on_top_ == always_on_top)
716 cached_always_on_top_ = always_on_top;
718 // As a security measure, do not allow fullscreen windows or windows that
719 // overlap the taskbar to be on top. The property will be applied when the
720 // window exits fullscreen and moves away from the taskbar.
721 if (!IsFullscreen(fullscreen_types_) && !IntersectsWithTaskbar())
722 native_app_window_->SetAlwaysOnTop(always_on_top);
724 OnNativeWindowChanged();
727 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
729 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
732 properties->SetBoolean("fullscreen",
733 native_app_window_->IsFullscreenOrPending());
734 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
735 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
736 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
737 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
739 // These properties are undocumented and are to enable testing. Alpha is
741 // make the values easier to check.
742 SkColor transparent_white = ~SK_ColorBLACK;
743 properties->SetInteger(
745 native_app_window_->ActiveFrameColor() & transparent_white);
746 properties->SetInteger(
747 "inactiveFrameColor",
748 native_app_window_->InactiveFrameColor() & transparent_white);
750 gfx::Rect content_bounds = GetClientBounds();
751 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
752 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
753 SetBoundsProperties(content_bounds,
759 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
760 gfx::Rect frame_bounds = native_app_window_->GetBounds();
761 gfx::Size frame_min_size =
762 SizeConstraints::AddFrameToConstraints(content_min_size, frame_insets);
763 gfx::Size frame_max_size =
764 SizeConstraints::AddFrameToConstraints(content_max_size, frame_insets);
765 SetBoundsProperties(frame_bounds,
772 //------------------------------------------------------------------------------
775 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
777 native_app_window_->UpdateBadgeIcon();
780 void AppWindow::DidDownloadFavicon(
782 int http_status_code,
783 const GURL& image_url,
784 const std::vector<SkBitmap>& bitmaps,
785 const std::vector<gfx::Size>& original_bitmap_sizes) {
786 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
791 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
792 // whose height >= the preferred size.
793 int largest_index = 0;
794 for (size_t i = 1; i < bitmaps.size(); ++i) {
795 if (bitmaps[i].height() < delegate_->PreferredIconSize())
799 const SkBitmap& largest = bitmaps[largest_index];
800 if (image_url == app_icon_url_) {
801 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
805 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
808 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
809 DCHECK_EQ(app_icon_image_.get(), image);
811 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
814 void AppWindow::UpdateExtensionAppIcon() {
815 // Avoid using any previous app icons were being downloaded.
816 image_loader_ptr_factory_.InvalidateWeakPtrs();
818 const gfx::ImageSkia& default_icon =
819 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
820 IDR_APP_DEFAULT_ICON);
822 const extensions::Extension* extension = GetExtension();
826 app_icon_image_.reset(
827 new extensions::IconImage(browser_context(),
829 extensions::IconsInfo::GetIcons(extension),
830 delegate_->PreferredIconSize(),
834 // Triggers actual image loading with 1x resources. The 2x resource will
835 // be handled by IconImage class when requested.
836 app_icon_image_->image_skia().GetRepresentation(1.0f);
839 void AppWindow::SetNativeWindowFullscreen() {
840 native_app_window_->SetFullscreen(fullscreen_types_);
842 if (cached_always_on_top_)
843 UpdateNativeAlwaysOnTop();
846 bool AppWindow::IntersectsWithTaskbar() const {
848 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
849 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
850 std::vector<gfx::Display> displays = screen->GetAllDisplays();
852 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
853 it != displays.end();
855 gfx::Rect taskbar_bounds = it->bounds();
856 taskbar_bounds.Subtract(it->work_area());
857 if (taskbar_bounds.IsEmpty())
860 if (window_bounds.Intersects(taskbar_bounds))
868 void AppWindow::UpdateNativeAlwaysOnTop() {
869 DCHECK(cached_always_on_top_);
870 bool is_on_top = native_app_window_->IsAlwaysOnTop();
871 bool fullscreen = IsFullscreen(fullscreen_types_);
872 bool intersects_taskbar = IntersectsWithTaskbar();
874 if (is_on_top && (fullscreen || intersects_taskbar)) {
875 // When entering fullscreen or overlapping the taskbar, ensure windows are
876 // not always-on-top.
877 native_app_window_->SetAlwaysOnTop(false);
878 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
879 // When exiting fullscreen and moving away from the taskbar, reinstate
881 native_app_window_->SetAlwaysOnTop(true);
885 void AppWindow::CloseContents(WebContents* contents) {
886 native_app_window_->Close();
889 bool AppWindow::ShouldSuppressDialogs() { return true; }
891 content::ColorChooser* AppWindow::OpenColorChooser(
892 WebContents* web_contents,
893 SkColor initial_color,
894 const std::vector<content::ColorSuggestion>& suggestionss) {
895 return delegate_->ShowColorChooser(web_contents, initial_color);
898 void AppWindow::RunFileChooser(WebContents* tab,
899 const content::FileChooserParams& params) {
900 if (window_type_is_panel()) {
901 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
902 // dialogs to be unhosted but still close with the owning web contents.
904 LOG(WARNING) << "File dialog opened by panel.";
908 delegate_->RunFileChooser(tab, params);
911 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
913 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
914 native_app_window_->SetBounds(pos);
917 void AppWindow::NavigationStateChanged(const content::WebContents* source,
918 unsigned changed_flags) {
919 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
920 native_app_window_->UpdateWindowTitle();
921 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
922 native_app_window_->UpdateWindowIcon();
925 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
926 bool enter_fullscreen) {
927 #if !defined(OS_MACOSX)
928 // Do not enter fullscreen mode if disallowed by pref.
929 // TODO(bartfab): Add a test once it becomes possible to simulate a user
930 // gesture. http://crbug.com/174178
932 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
934 if (enter_fullscreen && !prefs->GetBoolean(prefs::kAppFullscreenAllowed)) {
939 const extensions::Extension* extension = GetExtension();
943 if (!IsExtensionWithPermissionOrSuggestInConsole(
944 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
948 if (enter_fullscreen)
949 fullscreen_types_ |= FULLSCREEN_TYPE_HTML_API;
951 fullscreen_types_ &= ~FULLSCREEN_TYPE_HTML_API;
952 SetNativeWindowFullscreen();
955 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
957 return ((fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0);
960 void AppWindow::Observe(int type,
961 const content::NotificationSource& source,
962 const content::NotificationDetails& details) {
964 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
965 const extensions::Extension* unloaded_extension =
966 content::Details<extensions::UnloadedExtensionInfo>(details)
968 if (extension_id_ == unloaded_extension->id())
969 native_app_window_->Close();
972 case chrome::NOTIFICATION_EXTENSION_INSTALLED: {
973 const extensions::Extension* installed_extension =
974 content::Details<const extensions::InstalledExtensionInfo>(details)
976 DCHECK(installed_extension);
977 if (installed_extension->id() == extension_id())
978 native_app_window_->UpdateShelfMenu();
981 case chrome::NOTIFICATION_APP_TERMINATING:
982 native_app_window_->Close();
985 NOTREACHED() << "Received unexpected notification";
989 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
991 delegate_->SetWebContentsBlocked(web_contents, blocked);
994 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
995 return delegate_->IsWebContentsVisible(web_contents);
998 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
999 return native_app_window_.get();
1002 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
1003 const std::string& message) {
1004 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
1005 rvh->Send(new ExtensionMsg_AddMessageToConsole(
1006 rvh->GetRoutingID(), level, message));
1009 void AppWindow::SaveWindowPosition() {
1010 if (window_key_.empty())
1012 if (!native_app_window_)
1015 AppWindowGeometryCache* cache =
1016 AppWindowGeometryCache::Get(browser_context());
1018 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
1019 gfx::Rect screen_bounds =
1020 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
1021 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1022 cache->SaveGeometry(
1023 extension_id(), window_key_, bounds, screen_bounds, window_state);
1026 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1027 const gfx::Rect& cached_bounds,
1028 const gfx::Rect& cached_screen_bounds,
1029 const gfx::Rect& current_screen_bounds,
1030 const gfx::Size& minimum_size,
1031 gfx::Rect* bounds) const {
1032 *bounds = cached_bounds;
1034 // Reposition and resize the bounds if the cached_screen_bounds is different
1035 // from the current screen bounds and the current screen bounds doesn't
1036 // completely contain the bounds.
1037 if (cached_screen_bounds != current_screen_bounds &&
1038 !current_screen_bounds.Contains(cached_bounds)) {
1040 std::max(minimum_size.width(),
1041 std::min(bounds->width(), current_screen_bounds.width())));
1043 std::max(minimum_size.height(),
1044 std::min(bounds->height(), current_screen_bounds.height())));
1046 std::max(current_screen_bounds.x(),
1047 std::min(bounds->x(),
1048 current_screen_bounds.right() - bounds->width())));
1050 std::max(current_screen_bounds.y(),
1051 std::min(bounds->y(),
1052 current_screen_bounds.bottom() - bounds->height())));
1056 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1058 // Ensure width and height are specified.
1059 if (params.content_spec.bounds.width() == 0 &&
1060 params.window_spec.bounds.width() == 0) {
1061 params.content_spec.bounds.set_width(kDefaultWidth);
1063 if (params.content_spec.bounds.height() == 0 &&
1064 params.window_spec.bounds.height() == 0) {
1065 params.content_spec.bounds.set_height(kDefaultHeight);
1068 // If left and top are left undefined, the native app window will center
1069 // the window on the main screen in a platform-defined manner.
1071 // Load cached state if it exists.
1072 if (!params.window_key.empty()) {
1073 AppWindowGeometryCache* cache =
1074 AppWindowGeometryCache::Get(browser_context());
1076 gfx::Rect cached_bounds;
1077 gfx::Rect cached_screen_bounds;
1078 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1079 if (cache->GetGeometry(extension_id(),
1082 &cached_screen_bounds,
1084 // App window has cached screen bounds, make sure it fits on screen in
1085 // case the screen resolution changed.
1086 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1087 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1088 gfx::Rect current_screen_bounds = display.work_area();
1089 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1090 params.GetWindowMaximumSize(gfx::Insets()));
1091 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1092 cached_screen_bounds,
1093 current_screen_bounds,
1094 constraints.GetMinimumSize(),
1095 ¶ms.window_spec.bounds);
1096 params.state = cached_state;
1098 // Since we are restoring a cached state, reset the content bounds spec to
1099 // ensure it is not used.
1100 params.content_spec.ResetBounds();
1108 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1109 const std::vector<extensions::DraggableRegion>& regions) {
1110 SkRegion* sk_region = new SkRegion;
1111 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
1113 iter != regions.end();
1115 const extensions::DraggableRegion& region = *iter;
1119 region.bounds.right(),
1120 region.bounds.bottom(),
1121 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);