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 "extensions/browser/app_window/app_window.h"
11 #include "base/command_line.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/values.h"
15 #include "components/web_modal/web_contents_modal_dialog_manager.h"
16 #include "content/public/browser/browser_context.h"
17 #include "content/public/browser/invalidate_type.h"
18 #include "content/public/browser/navigation_entry.h"
19 #include "content/public/browser/notification_details.h"
20 #include "content/public/browser/notification_service.h"
21 #include "content/public/browser/notification_source.h"
22 #include "content/public/browser/notification_types.h"
23 #include "content/public/browser/render_view_host.h"
24 #include "content/public/browser/resource_dispatcher_host.h"
25 #include "content/public/browser/web_contents.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/media_stream_request.h"
28 #include "extensions/browser/app_window/app_delegate.h"
29 #include "extensions/browser/app_window/app_web_contents_helper.h"
30 #include "extensions/browser/app_window/app_window_client.h"
31 #include "extensions/browser/app_window/app_window_geometry_cache.h"
32 #include "extensions/browser/app_window/app_window_registry.h"
33 #include "extensions/browser/app_window/native_app_window.h"
34 #include "extensions/browser/app_window/size_constraints.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/notification_types.h"
39 #include "extensions/browser/process_manager.h"
40 #include "extensions/browser/suggest_permission_util.h"
41 #include "extensions/browser/view_type_utils.h"
42 #include "extensions/common/draggable_region.h"
43 #include "extensions/common/extension.h"
44 #include "extensions/common/manifest_handlers/icons_handler.h"
45 #include "extensions/common/permissions/permissions_data.h"
46 #include "extensions/common/switches.h"
47 #include "extensions/grit/extensions_browser_resources.h"
48 #include "third_party/skia/include/core/SkRegion.h"
49 #include "ui/base/resource/resource_bundle.h"
50 #include "ui/gfx/screen.h"
52 #if !defined(OS_MACOSX)
53 #include "base/prefs/pref_service.h"
54 #include "extensions/browser/pref_names.h"
57 using content::BrowserContext;
58 using content::ConsoleMessageLevel;
59 using content::WebContents;
60 using web_modal::WebContentsModalDialogHost;
61 using web_modal::WebContentsModalDialogManager;
63 namespace extensions {
67 const int kDefaultWidth = 512;
68 const int kDefaultHeight = 384;
70 void SetConstraintProperty(const std::string& name,
72 base::DictionaryValue* bounds_properties) {
73 if (value != SizeConstraints::kUnboundedSize)
74 bounds_properties->SetInteger(name, value);
76 bounds_properties->Set(name, base::Value::CreateNullValue());
79 void SetBoundsProperties(const gfx::Rect& bounds,
80 const gfx::Size& min_size,
81 const gfx::Size& max_size,
82 const std::string& bounds_name,
83 base::DictionaryValue* window_properties) {
84 scoped_ptr<base::DictionaryValue> bounds_properties(
85 new base::DictionaryValue());
87 bounds_properties->SetInteger("left", bounds.x());
88 bounds_properties->SetInteger("top", bounds.y());
89 bounds_properties->SetInteger("width", bounds.width());
90 bounds_properties->SetInteger("height", bounds.height());
92 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
93 SetConstraintProperty(
94 "minHeight", min_size.height(), bounds_properties.get());
95 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
96 SetConstraintProperty(
97 "maxHeight", max_size.height(), bounds_properties.get());
99 window_properties->Set(bounds_name, bounds_properties.release());
102 // Combines the constraints of the content and window, and returns constraints
104 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
105 const gfx::Size& content_constraints,
106 const gfx::Insets& frame_insets) {
107 gfx::Size combined_constraints(window_constraints);
108 if (content_constraints.width() > 0) {
109 combined_constraints.set_width(
110 content_constraints.width() + frame_insets.width());
112 if (content_constraints.height() > 0) {
113 combined_constraints.set_height(
114 content_constraints.height() + frame_insets.height());
116 return combined_constraints;
119 // Combines the constraints of the content and window, and returns constraints
121 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
122 const gfx::Size& content_constraints,
123 const gfx::Insets& frame_insets) {
124 gfx::Size combined_constraints(content_constraints);
125 if (window_constraints.width() > 0) {
126 combined_constraints.set_width(
127 std::max(0, window_constraints.width() - frame_insets.width()));
129 if (window_constraints.height() > 0) {
130 combined_constraints.set_height(
131 std::max(0, window_constraints.height() - frame_insets.height()));
133 return combined_constraints;
138 // AppWindow::BoundsSpecification
140 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
142 AppWindow::BoundsSpecification::BoundsSpecification()
143 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
145 AppWindow::BoundsSpecification::~BoundsSpecification() {}
147 void AppWindow::BoundsSpecification::ResetBounds() {
148 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
151 // AppWindow::CreateParams
153 AppWindow::CreateParams::CreateParams()
154 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
155 frame(AppWindow::FRAME_CHROME),
156 has_frame_color(false),
157 active_frame_color(SK_ColorBLACK),
158 inactive_frame_color(SK_ColorBLACK),
159 alpha_enabled(false),
160 is_ime_window(false),
161 creator_process_id(0),
162 state(ui::SHOW_STATE_DEFAULT),
166 always_on_top(false),
167 visible_on_all_workspaces(false) {
170 AppWindow::CreateParams::~CreateParams() {}
172 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
173 const gfx::Insets& frame_insets) const {
174 // Combine into a single window bounds.
175 gfx::Rect combined_bounds(window_spec.bounds);
176 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
177 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
178 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
179 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
180 if (content_spec.bounds.width() > 0) {
181 combined_bounds.set_width(
182 content_spec.bounds.width() + frame_insets.width());
184 if (content_spec.bounds.height() > 0) {
185 combined_bounds.set_height(
186 content_spec.bounds.height() + frame_insets.height());
189 // Constrain the bounds.
190 SizeConstraints constraints(
191 GetCombinedWindowConstraints(
192 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
193 GetCombinedWindowConstraints(
194 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
195 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
197 return combined_bounds;
200 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
201 const gfx::Insets& frame_insets) const {
202 return GetCombinedContentConstraints(window_spec.minimum_size,
203 content_spec.minimum_size,
207 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
208 const gfx::Insets& frame_insets) const {
209 return GetCombinedContentConstraints(window_spec.maximum_size,
210 content_spec.maximum_size,
214 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
215 const gfx::Insets& frame_insets) const {
216 return GetCombinedWindowConstraints(window_spec.minimum_size,
217 content_spec.minimum_size,
221 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
222 const gfx::Insets& frame_insets) const {
223 return GetCombinedWindowConstraints(window_spec.maximum_size,
224 content_spec.maximum_size,
230 AppWindow::AppWindow(BrowserContext* context,
231 AppDelegate* app_delegate,
232 const Extension* extension)
233 : browser_context_(context),
234 extension_id_(extension->id()),
235 window_type_(WINDOW_TYPE_DEFAULT),
236 app_delegate_(app_delegate),
237 image_loader_ptr_factory_(this),
238 fullscreen_types_(FULLSCREEN_TYPE_NONE),
239 show_on_first_paint_(false),
240 first_paint_complete_(false),
241 has_been_shown_(false),
242 can_send_events_(false),
244 cached_always_on_top_(false),
245 requested_alpha_enabled_(false) {
246 ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
247 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
248 << "Only off the record window may be opened in the guest mode.";
251 void AppWindow::Init(const GURL& url,
252 AppWindowContents* app_window_contents,
253 const CreateParams& params) {
254 // Initialize the render interface and web contents
255 app_window_contents_.reset(app_window_contents);
256 app_window_contents_->Initialize(browser_context(), url);
257 WebContents* web_contents = app_window_contents_->GetWebContents();
258 if (CommandLine::ForCurrentProcess()->HasSwitch(
259 switches::kEnableAppsShowOnFirstPaint)) {
260 content::WebContentsObserver::Observe(web_contents);
262 app_delegate_->InitWebContents(web_contents);
264 WebContentsModalDialogManager::CreateForWebContents(web_contents);
266 web_contents->SetDelegate(this);
267 WebContentsModalDialogManager::FromWebContents(web_contents)
269 SetViewType(web_contents, VIEW_TYPE_APP_WINDOW);
271 // Initialize the window
272 CreateParams new_params = LoadDefaults(params);
273 window_type_ = new_params.window_type;
274 window_key_ = new_params.window_key;
276 // Windows cannot be always-on-top in fullscreen mode for security reasons.
277 cached_always_on_top_ = new_params.always_on_top;
278 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
279 new_params.always_on_top = false;
281 requested_alpha_enabled_ = new_params.alpha_enabled;
283 AppWindowClient* app_window_client = AppWindowClient::Get();
284 native_app_window_.reset(
285 app_window_client->CreateNativeAppWindow(this, &new_params));
287 helper_.reset(new AppWebContentsHelper(
288 browser_context_, extension_id_, web_contents, app_delegate_.get()));
290 popup_manager_.reset(
291 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
292 popup_manager_->RegisterWith(web_contents);
294 UpdateExtensionAppIcon();
295 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
297 if (new_params.hidden) {
298 // Although the window starts hidden by default, calling Hide() here
299 // notifies observers of the window being hidden.
302 // Panels are not activated by default.
303 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
307 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
309 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
311 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
314 OnNativeWindowChanged();
316 // When the render view host is changed, the native window needs to know
317 // about it in case it has any setup to do to make the renderer appear
318 // properly. In particular, on Windows, the view's clickthrough region needs
320 ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
322 NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
323 content::Source<content::BrowserContext>(
324 client->GetOriginalContext(browser_context_)));
325 // Update the app menu if an ephemeral app becomes installed.
327 NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
328 content::Source<content::BrowserContext>(
329 client->GetOriginalContext(browser_context_)));
331 // Close when the browser process is exiting.
332 app_delegate_->SetTerminatingCallback(
333 base::Bind(&NativeAppWindow::Close,
334 base::Unretained(native_app_window_.get())));
336 app_window_contents_->LoadContents(new_params.creator_process_id);
338 if (CommandLine::ForCurrentProcess()->HasSwitch(
339 extensions::switches::kEnableAppsShowOnFirstPaint)) {
340 // We want to show the window only when the content has been painted. For
341 // that to happen, we need to define a size for the content, otherwise the
342 // layout will happen in a 0x0 area.
343 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
344 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
345 initial_bounds.Inset(frame_insets);
346 app_delegate_->ResizeWebContents(web_contents, initial_bounds.size());
350 AppWindow::~AppWindow() {
353 void AppWindow::RequestMediaAccessPermission(
354 content::WebContents* web_contents,
355 const content::MediaStreamRequest& request,
356 const content::MediaResponseCallback& callback) {
357 DCHECK_EQ(AppWindow::web_contents(), web_contents);
358 helper_->RequestMediaAccessPermission(request, callback);
361 bool AppWindow::CheckMediaAccessPermission(content::WebContents* web_contents,
362 const GURL& security_origin,
363 content::MediaStreamType type) {
364 DCHECK_EQ(AppWindow::web_contents(), web_contents);
365 return helper_->CheckMediaAccessPermission(security_origin, type);
368 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
369 const content::OpenURLParams& params) {
370 DCHECK_EQ(web_contents(), source);
371 return helper_->OpenURLFromTab(params);
374 void AppWindow::AddNewContents(WebContents* source,
375 WebContents* new_contents,
376 WindowOpenDisposition disposition,
377 const gfx::Rect& initial_pos,
380 DCHECK(new_contents->GetBrowserContext() == browser_context_);
381 app_delegate_->AddNewContents(browser_context_,
389 bool AppWindow::PreHandleKeyboardEvent(
390 content::WebContents* source,
391 const content::NativeWebKeyboardEvent& event,
392 bool* is_keyboard_shortcut) {
393 const Extension* extension = GetExtension();
397 // Here, we can handle a key event before the content gets it. When we are
398 // fullscreen and it is not forced, we want to allow the user to leave
399 // when ESC is pressed.
400 // However, if the application has the "overrideEscFullscreen" permission, we
401 // should let it override that behavior.
402 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
403 // action is not prevented.
404 // Thus, we should handle the KeyEvent here only if the permission is not set.
405 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
406 !IsForcedFullscreen() &&
407 !extension->permissions_data()->HasAPIPermission(
408 APIPermission::kOverrideEscFullscreen)) {
416 void AppWindow::HandleKeyboardEvent(
418 const content::NativeWebKeyboardEvent& event) {
419 // If the window is currently fullscreen and not forced, ESC should leave
420 // fullscreen. If this code is being called for ESC, that means that the
421 // KeyEvent's default behavior was not prevented by the content.
422 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
423 !IsForcedFullscreen()) {
428 native_app_window_->HandleKeyboardEvent(event);
431 void AppWindow::RequestToLockMouse(WebContents* web_contents,
433 bool last_unlocked_by_target) {
434 DCHECK_EQ(AppWindow::web_contents(), web_contents);
435 helper_->RequestToLockMouse();
438 bool AppWindow::PreHandleGestureEvent(WebContents* source,
439 const blink::WebGestureEvent& event) {
440 return AppWebContentsHelper::ShouldSuppressGestureEvent(event);
443 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
444 first_paint_complete_ = true;
445 if (show_on_first_paint_) {
446 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
447 delayed_show_type_ == SHOW_INACTIVE);
448 Show(delayed_show_type_);
452 void AppWindow::OnNativeClose() {
453 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
454 if (app_window_contents_) {
455 WebContents* web_contents = app_window_contents_->GetWebContents();
456 WebContentsModalDialogManager::FromWebContents(web_contents)
458 app_window_contents_->NativeWindowClosed();
463 void AppWindow::OnNativeWindowChanged() {
464 SaveWindowPosition();
467 if (native_app_window_ && cached_always_on_top_ && !IsFullscreen() &&
468 !native_app_window_->IsMaximized() &&
469 !native_app_window_->IsMinimized()) {
470 UpdateNativeAlwaysOnTop();
474 if (app_window_contents_ && native_app_window_)
475 app_window_contents_->NativeWindowChanged(native_app_window_.get());
478 void AppWindow::OnNativeWindowActivated() {
479 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
482 content::WebContents* AppWindow::web_contents() const {
483 return app_window_contents_->GetWebContents();
486 const Extension* AppWindow::GetExtension() const {
487 return ExtensionRegistry::Get(browser_context_)
488 ->enabled_extensions()
489 .GetByID(extension_id_);
492 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
494 gfx::NativeWindow AppWindow::GetNativeWindow() {
495 return GetBaseWindow()->GetNativeWindow();
498 gfx::Rect AppWindow::GetClientBounds() const {
499 gfx::Rect bounds = native_app_window_->GetBounds();
500 bounds.Inset(native_app_window_->GetFrameInsets());
504 base::string16 AppWindow::GetTitle() const {
505 const Extension* extension = GetExtension();
507 return base::string16();
509 // WebContents::GetTitle() will return the page's URL if there's no <title>
510 // specified. However, we'd prefer to show the name of the extension in that
511 // case, so we directly inspect the NavigationEntry's title.
512 base::string16 title;
513 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
514 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
515 title = base::UTF8ToUTF16(extension->name());
517 title = web_contents()->GetTitle();
519 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
523 void AppWindow::SetAppIconUrl(const GURL& url) {
524 // If the same url is being used for the badge, ignore it.
525 if (url == badge_icon_url_)
528 // Avoid using any previous icons that were being downloaded.
529 image_loader_ptr_factory_.InvalidateWeakPtrs();
531 // Reset |app_icon_image_| to abort pending image load (if any).
532 app_icon_image_.reset();
535 web_contents()->DownloadImage(
537 true, // is a favicon
538 0, // no maximum size
539 base::Bind(&AppWindow::DidDownloadFavicon,
540 image_loader_ptr_factory_.GetWeakPtr()));
543 void AppWindow::SetBadgeIconUrl(const GURL& url) {
544 // Avoid using any previous icons that were being downloaded.
545 image_loader_ptr_factory_.InvalidateWeakPtrs();
547 // Reset |app_icon_image_| to abort pending image load (if any).
548 badge_icon_image_.reset();
550 badge_icon_url_ = url;
551 web_contents()->DownloadImage(
553 true, // is a favicon
554 0, // no maximum size
555 base::Bind(&AppWindow::DidDownloadFavicon,
556 image_loader_ptr_factory_.GetWeakPtr()));
559 void AppWindow::ClearBadge() {
560 badge_icon_image_.reset();
561 badge_icon_url_ = GURL();
562 UpdateBadgeIcon(gfx::Image());
565 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
566 native_app_window_->UpdateShape(region.Pass());
569 void AppWindow::UpdateDraggableRegions(
570 const std::vector<DraggableRegion>& regions) {
571 native_app_window_->UpdateDraggableRegions(regions);
574 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
578 native_app_window_->UpdateWindowIcon();
579 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
582 void AppWindow::SetFullscreen(FullscreenType type, bool enable) {
583 DCHECK_NE(FULLSCREEN_TYPE_NONE, type);
586 #if !defined(OS_MACOSX)
587 // Do not enter fullscreen mode if disallowed by pref.
588 // TODO(bartfab): Add a test once it becomes possible to simulate a user
589 // gesture. http://crbug.com/174178
590 if (type != FULLSCREEN_TYPE_FORCED) {
592 ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
594 if (!prefs->GetBoolean(pref_names::kAppFullscreenAllowed))
598 fullscreen_types_ |= type;
600 fullscreen_types_ &= ~type;
602 SetNativeWindowFullscreen();
605 bool AppWindow::IsFullscreen() const {
606 return fullscreen_types_ != FULLSCREEN_TYPE_NONE;
609 bool AppWindow::IsForcedFullscreen() const {
610 return (fullscreen_types_ & FULLSCREEN_TYPE_FORCED) != 0;
613 bool AppWindow::IsHtmlApiFullscreen() const {
614 return (fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0;
617 void AppWindow::Fullscreen() {
618 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API, true);
621 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
623 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
625 void AppWindow::Restore() {
626 if (IsFullscreen()) {
627 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
628 SetNativeWindowFullscreen();
630 GetBaseWindow()->Restore();
634 void AppWindow::OSFullscreen() {
635 SetFullscreen(FULLSCREEN_TYPE_OS, true);
638 void AppWindow::ForcedFullscreen() {
639 SetFullscreen(FULLSCREEN_TYPE_FORCED, true);
642 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
643 const gfx::Size& max_size) {
644 SizeConstraints constraints(min_size, max_size);
645 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
646 constraints.GetMaximumSize());
648 gfx::Rect bounds = GetClientBounds();
649 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
650 if (bounds.size() != constrained_size) {
651 bounds.set_size(constrained_size);
652 bounds.Inset(-native_app_window_->GetFrameInsets());
653 native_app_window_->SetBounds(bounds);
655 OnNativeWindowChanged();
658 void AppWindow::Show(ShowType show_type) {
659 bool was_hidden = is_hidden_ || !has_been_shown_;
662 if (CommandLine::ForCurrentProcess()->HasSwitch(
663 switches::kEnableAppsShowOnFirstPaint)) {
664 show_on_first_paint_ = true;
666 if (!first_paint_complete_) {
667 delayed_show_type_ = show_type;
674 GetBaseWindow()->Show();
677 GetBaseWindow()->ShowInactive();
680 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this, was_hidden);
682 has_been_shown_ = true;
683 SendOnWindowShownIfShown();
686 void AppWindow::Hide() {
687 // This is there to prevent race conditions with Hide() being called before
688 // there was a non-empty paint. It should have no effect in a non-racy
689 // scenario where the application is hiding then showing a window: the second
690 // show will not be delayed.
692 show_on_first_paint_ = false;
693 GetBaseWindow()->Hide();
694 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
697 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
698 if (cached_always_on_top_ == always_on_top)
701 cached_always_on_top_ = always_on_top;
703 // As a security measure, do not allow fullscreen windows or windows that
704 // overlap the taskbar to be on top. The property will be applied when the
705 // window exits fullscreen and moves away from the taskbar.
706 if (!IsFullscreen() && !IntersectsWithTaskbar())
707 native_app_window_->SetAlwaysOnTop(always_on_top);
709 OnNativeWindowChanged();
712 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
714 void AppWindow::WindowEventsReady() {
715 can_send_events_ = true;
716 SendOnWindowShownIfShown();
719 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
722 properties->SetBoolean("fullscreen",
723 native_app_window_->IsFullscreenOrPending());
724 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
725 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
726 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
727 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
728 properties->SetBoolean(
730 requested_alpha_enabled_ && native_app_window_->CanHaveAlphaEnabled());
732 // These properties are undocumented and are to enable testing. Alpha is
734 // make the values easier to check.
735 SkColor transparent_white = ~SK_ColorBLACK;
736 properties->SetInteger(
738 native_app_window_->ActiveFrameColor() & transparent_white);
739 properties->SetInteger(
740 "inactiveFrameColor",
741 native_app_window_->InactiveFrameColor() & transparent_white);
743 gfx::Rect content_bounds = GetClientBounds();
744 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
745 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
746 SetBoundsProperties(content_bounds,
752 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
753 gfx::Rect frame_bounds = native_app_window_->GetBounds();
754 gfx::Size frame_min_size = SizeConstraints::AddFrameToConstraints(
755 content_min_size, frame_insets);
756 gfx::Size frame_max_size = SizeConstraints::AddFrameToConstraints(
757 content_max_size, frame_insets);
758 SetBoundsProperties(frame_bounds,
765 //------------------------------------------------------------------------------
768 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
770 native_app_window_->UpdateBadgeIcon();
773 void AppWindow::DidDownloadFavicon(
775 int http_status_code,
776 const GURL& image_url,
777 const std::vector<SkBitmap>& bitmaps,
778 const std::vector<gfx::Size>& original_bitmap_sizes) {
779 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
784 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
785 // whose height >= the preferred size.
786 int largest_index = 0;
787 for (size_t i = 1; i < bitmaps.size(); ++i) {
788 if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
792 const SkBitmap& largest = bitmaps[largest_index];
793 if (image_url == app_icon_url_) {
794 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
798 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
801 void AppWindow::OnExtensionIconImageChanged(IconImage* image) {
802 DCHECK_EQ(app_icon_image_.get(), image);
804 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
807 void AppWindow::UpdateExtensionAppIcon() {
808 // Avoid using any previous app icons were being downloaded.
809 image_loader_ptr_factory_.InvalidateWeakPtrs();
811 const Extension* extension = GetExtension();
815 gfx::ImageSkia app_default_icon =
816 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
817 IDR_APP_DEFAULT_ICON);
819 app_icon_image_.reset(new IconImage(browser_context(),
821 IconsInfo::GetIcons(extension),
822 app_delegate_->PreferredIconSize(),
826 // Triggers actual image loading with 1x resources. The 2x resource will
827 // be handled by IconImage class when requested.
828 app_icon_image_->image_skia().GetRepresentation(1.0f);
831 void AppWindow::SetNativeWindowFullscreen() {
832 native_app_window_->SetFullscreen(fullscreen_types_);
834 if (cached_always_on_top_)
835 UpdateNativeAlwaysOnTop();
838 bool AppWindow::IntersectsWithTaskbar() const {
840 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
841 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
842 std::vector<gfx::Display> displays = screen->GetAllDisplays();
844 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
845 it != displays.end();
847 gfx::Rect taskbar_bounds = it->bounds();
848 taskbar_bounds.Subtract(it->work_area());
849 if (taskbar_bounds.IsEmpty())
852 if (window_bounds.Intersects(taskbar_bounds))
860 void AppWindow::UpdateNativeAlwaysOnTop() {
861 DCHECK(cached_always_on_top_);
862 bool is_on_top = native_app_window_->IsAlwaysOnTop();
863 bool fullscreen = IsFullscreen();
864 bool intersects_taskbar = IntersectsWithTaskbar();
866 if (is_on_top && (fullscreen || intersects_taskbar)) {
867 // When entering fullscreen or overlapping the taskbar, ensure windows are
868 // not always-on-top.
869 native_app_window_->SetAlwaysOnTop(false);
870 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
871 // When exiting fullscreen and moving away from the taskbar, reinstate
873 native_app_window_->SetAlwaysOnTop(true);
877 void AppWindow::SendOnWindowShownIfShown() {
878 if (!can_send_events_ || !has_been_shown_)
881 if (CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestType)) {
882 app_window_contents_->DispatchWindowShownForTests();
886 void AppWindow::CloseContents(WebContents* contents) {
887 native_app_window_->Close();
890 bool AppWindow::ShouldSuppressDialogs() { return true; }
892 content::ColorChooser* AppWindow::OpenColorChooser(
893 WebContents* web_contents,
894 SkColor initial_color,
895 const std::vector<content::ColorSuggestion>& suggestions) {
896 return app_delegate_->ShowColorChooser(web_contents, initial_color);
899 void AppWindow::RunFileChooser(WebContents* tab,
900 const content::FileChooserParams& params) {
901 if (window_type_is_panel()) {
902 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
903 // dialogs to be unhosted but still close with the owning web contents.
905 LOG(WARNING) << "File dialog opened by panel.";
909 app_delegate_->RunFileChooser(tab, params);
912 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
914 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
915 native_app_window_->SetBounds(pos);
918 void AppWindow::NavigationStateChanged(const content::WebContents* source,
919 content::InvalidateTypes changed_flags) {
920 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
921 native_app_window_->UpdateWindowTitle();
922 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
923 native_app_window_->UpdateWindowIcon();
926 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
927 bool enter_fullscreen) {
928 const Extension* extension = GetExtension();
932 if (!IsExtensionWithPermissionOrSuggestInConsole(
933 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
937 SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
940 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
942 return IsHtmlApiFullscreen();
945 void AppWindow::Observe(int type,
946 const content::NotificationSource& source,
947 const content::NotificationDetails& details) {
949 case NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
950 const Extension* unloaded_extension =
951 content::Details<UnloadedExtensionInfo>(details)->extension;
952 if (extension_id_ == unloaded_extension->id())
953 native_app_window_->Close();
956 case NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
957 const Extension* installed_extension =
958 content::Details<const InstalledExtensionInfo>(details)->extension;
959 DCHECK(installed_extension);
960 if (installed_extension->id() == extension_id())
961 native_app_window_->UpdateShelfMenu();
965 NOTREACHED() << "Received unexpected notification";
969 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
971 app_delegate_->SetWebContentsBlocked(web_contents, blocked);
974 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
975 return app_delegate_->IsWebContentsVisible(web_contents);
978 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
979 return native_app_window_.get();
982 void AppWindow::SaveWindowPosition() {
983 if (window_key_.empty())
985 if (!native_app_window_)
988 AppWindowGeometryCache* cache =
989 AppWindowGeometryCache::Get(browser_context());
991 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
992 gfx::Rect screen_bounds =
993 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
994 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
996 extension_id(), window_key_, bounds, screen_bounds, window_state);
999 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1000 const gfx::Rect& cached_bounds,
1001 const gfx::Rect& cached_screen_bounds,
1002 const gfx::Rect& current_screen_bounds,
1003 const gfx::Size& minimum_size,
1004 gfx::Rect* bounds) const {
1005 *bounds = cached_bounds;
1007 // Reposition and resize the bounds if the cached_screen_bounds is different
1008 // from the current screen bounds and the current screen bounds doesn't
1009 // completely contain the bounds.
1010 if (cached_screen_bounds != current_screen_bounds &&
1011 !current_screen_bounds.Contains(cached_bounds)) {
1013 std::max(minimum_size.width(),
1014 std::min(bounds->width(), current_screen_bounds.width())));
1016 std::max(minimum_size.height(),
1017 std::min(bounds->height(), current_screen_bounds.height())));
1019 std::max(current_screen_bounds.x(),
1020 std::min(bounds->x(),
1021 current_screen_bounds.right() - bounds->width())));
1023 std::max(current_screen_bounds.y(),
1024 std::min(bounds->y(),
1025 current_screen_bounds.bottom() - bounds->height())));
1029 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1031 // Ensure width and height are specified.
1032 if (params.content_spec.bounds.width() == 0 &&
1033 params.window_spec.bounds.width() == 0) {
1034 params.content_spec.bounds.set_width(kDefaultWidth);
1036 if (params.content_spec.bounds.height() == 0 &&
1037 params.window_spec.bounds.height() == 0) {
1038 params.content_spec.bounds.set_height(kDefaultHeight);
1041 // If left and top are left undefined, the native app window will center
1042 // the window on the main screen in a platform-defined manner.
1044 // Load cached state if it exists.
1045 if (!params.window_key.empty()) {
1046 AppWindowGeometryCache* cache =
1047 AppWindowGeometryCache::Get(browser_context());
1049 gfx::Rect cached_bounds;
1050 gfx::Rect cached_screen_bounds;
1051 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1052 if (cache->GetGeometry(extension_id(),
1055 &cached_screen_bounds,
1057 // App window has cached screen bounds, make sure it fits on screen in
1058 // case the screen resolution changed.
1059 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1060 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1061 gfx::Rect current_screen_bounds = display.work_area();
1062 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1063 params.GetWindowMaximumSize(gfx::Insets()));
1064 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1065 cached_screen_bounds,
1066 current_screen_bounds,
1067 constraints.GetMinimumSize(),
1068 ¶ms.window_spec.bounds);
1069 params.state = cached_state;
1071 // Since we are restoring a cached state, reset the content bounds spec to
1072 // ensure it is not used.
1073 params.content_spec.ResetBounds();
1081 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1082 const std::vector<DraggableRegion>& regions) {
1083 SkRegion* sk_region = new SkRegion;
1084 for (std::vector<DraggableRegion>::const_iterator iter = regions.begin();
1085 iter != regions.end();
1087 const DraggableRegion& region = *iter;
1091 region.bounds.right(),
1092 region.bounds.bottom(),
1093 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1098 } // namespace extensions