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/render_view_host.h"
20 #include "content/public/browser/resource_dispatcher_host.h"
21 #include "content/public/browser/web_contents.h"
22 #include "content/public/common/content_switches.h"
23 #include "content/public/common/media_stream_request.h"
24 #include "extensions/browser/app_window/app_delegate.h"
25 #include "extensions/browser/app_window/app_web_contents_helper.h"
26 #include "extensions/browser/app_window/app_window_client.h"
27 #include "extensions/browser/app_window/app_window_geometry_cache.h"
28 #include "extensions/browser/app_window/app_window_registry.h"
29 #include "extensions/browser/app_window/native_app_window.h"
30 #include "extensions/browser/app_window/size_constraints.h"
31 #include "extensions/browser/extension_registry.h"
32 #include "extensions/browser/extension_system.h"
33 #include "extensions/browser/extensions_browser_client.h"
34 #include "extensions/browser/notification_types.h"
35 #include "extensions/browser/process_manager.h"
36 #include "extensions/browser/suggest_permission_util.h"
37 #include "extensions/browser/view_type_utils.h"
38 #include "extensions/common/draggable_region.h"
39 #include "extensions/common/extension.h"
40 #include "extensions/common/manifest_handlers/icons_handler.h"
41 #include "extensions/common/permissions/permissions_data.h"
42 #include "extensions/common/switches.h"
43 #include "extensions/grit/extensions_browser_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 "base/prefs/pref_service.h"
50 #include "extensions/browser/pref_names.h"
53 using content::BrowserContext
;
54 using content::ConsoleMessageLevel
;
55 using content::WebContents
;
56 using web_modal::WebContentsModalDialogHost
;
57 using web_modal::WebContentsModalDialogManager
;
59 namespace extensions
{
63 const int kDefaultWidth
= 512;
64 const int kDefaultHeight
= 384;
66 void SetConstraintProperty(const std::string
& name
,
68 base::DictionaryValue
* bounds_properties
) {
69 if (value
!= SizeConstraints::kUnboundedSize
)
70 bounds_properties
->SetInteger(name
, value
);
72 bounds_properties
->Set(name
, base::Value::CreateNullValue());
75 void SetBoundsProperties(const gfx::Rect
& bounds
,
76 const gfx::Size
& min_size
,
77 const gfx::Size
& max_size
,
78 const std::string
& bounds_name
,
79 base::DictionaryValue
* window_properties
) {
80 scoped_ptr
<base::DictionaryValue
> bounds_properties(
81 new base::DictionaryValue());
83 bounds_properties
->SetInteger("left", bounds
.x());
84 bounds_properties
->SetInteger("top", bounds
.y());
85 bounds_properties
->SetInteger("width", bounds
.width());
86 bounds_properties
->SetInteger("height", bounds
.height());
88 SetConstraintProperty("minWidth", min_size
.width(), bounds_properties
.get());
89 SetConstraintProperty(
90 "minHeight", min_size
.height(), bounds_properties
.get());
91 SetConstraintProperty("maxWidth", max_size
.width(), bounds_properties
.get());
92 SetConstraintProperty(
93 "maxHeight", max_size
.height(), bounds_properties
.get());
95 window_properties
->Set(bounds_name
, bounds_properties
.release());
98 // Combines the constraints of the content and window, and returns constraints
100 gfx::Size
GetCombinedWindowConstraints(const gfx::Size
& window_constraints
,
101 const gfx::Size
& content_constraints
,
102 const gfx::Insets
& frame_insets
) {
103 gfx::Size
combined_constraints(window_constraints
);
104 if (content_constraints
.width() > 0) {
105 combined_constraints
.set_width(
106 content_constraints
.width() + frame_insets
.width());
108 if (content_constraints
.height() > 0) {
109 combined_constraints
.set_height(
110 content_constraints
.height() + frame_insets
.height());
112 return combined_constraints
;
115 // Combines the constraints of the content and window, and returns constraints
117 gfx::Size
GetCombinedContentConstraints(const gfx::Size
& window_constraints
,
118 const gfx::Size
& content_constraints
,
119 const gfx::Insets
& frame_insets
) {
120 gfx::Size
combined_constraints(content_constraints
);
121 if (window_constraints
.width() > 0) {
122 combined_constraints
.set_width(
123 std::max(0, window_constraints
.width() - frame_insets
.width()));
125 if (window_constraints
.height() > 0) {
126 combined_constraints
.set_height(
127 std::max(0, window_constraints
.height() - frame_insets
.height()));
129 return combined_constraints
;
134 // AppWindow::BoundsSpecification
136 const int AppWindow::BoundsSpecification::kUnspecifiedPosition
= INT_MIN
;
138 AppWindow::BoundsSpecification::BoundsSpecification()
139 : bounds(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0) {}
141 AppWindow::BoundsSpecification::~BoundsSpecification() {}
143 void AppWindow::BoundsSpecification::ResetBounds() {
144 bounds
.SetRect(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0);
147 // AppWindow::CreateParams
149 AppWindow::CreateParams::CreateParams()
150 : window_type(AppWindow::WINDOW_TYPE_DEFAULT
),
151 frame(AppWindow::FRAME_CHROME
),
152 has_frame_color(false),
153 active_frame_color(SK_ColorBLACK
),
154 inactive_frame_color(SK_ColorBLACK
),
155 alpha_enabled(false),
156 is_ime_window(false),
157 creator_process_id(0),
158 state(ui::SHOW_STATE_DEFAULT
),
162 always_on_top(false),
163 visible_on_all_workspaces(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
,
226 AppWindow::AppWindow(BrowserContext
* context
,
227 AppDelegate
* app_delegate
,
228 const Extension
* extension
)
229 : browser_context_(context
),
230 extension_id_(extension
->id()),
231 window_type_(WINDOW_TYPE_DEFAULT
),
232 app_delegate_(app_delegate
),
233 fullscreen_types_(FULLSCREEN_TYPE_NONE
),
234 show_on_first_paint_(false),
235 first_paint_complete_(false),
236 has_been_shown_(false),
237 can_send_events_(false),
239 cached_always_on_top_(false),
240 requested_alpha_enabled_(false),
241 is_ime_window_(false),
242 image_loader_ptr_factory_(this) {
243 ExtensionsBrowserClient
* client
= 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
);
255 content::WebContentsObserver::Observe(web_contents());
256 SetViewType(web_contents(), VIEW_TYPE_APP_WINDOW
);
257 app_delegate_
->InitWebContents(web_contents());
259 WebContentsModalDialogManager::CreateForWebContents(web_contents());
261 web_contents()->SetDelegate(this);
262 WebContentsModalDialogManager::FromWebContents(web_contents())
265 // Initialize the window
266 CreateParams new_params
= LoadDefaults(params
);
267 window_type_
= new_params
.window_type
;
268 window_key_
= new_params
.window_key
;
270 // Windows cannot be always-on-top in fullscreen mode for security reasons.
271 cached_always_on_top_
= new_params
.always_on_top
;
272 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
273 new_params
.always_on_top
= false;
275 requested_alpha_enabled_
= new_params
.alpha_enabled
;
277 is_ime_window_
= params
.is_ime_window
;
279 AppWindowClient
* app_window_client
= AppWindowClient::Get();
280 native_app_window_
.reset(
281 app_window_client
->CreateNativeAppWindow(this, &new_params
));
283 helper_
.reset(new AppWebContentsHelper(
284 browser_context_
, extension_id_
, web_contents(), app_delegate_
.get()));
286 popup_manager_
.reset(
287 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
288 popup_manager_
->RegisterWith(web_contents());
290 UpdateExtensionAppIcon();
291 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
293 if (new_params
.hidden
) {
294 // Although the window starts hidden by default, calling Hide() here
295 // notifies observers of the window being hidden.
298 // Panels are not activated by default.
299 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
302 // These states may cause the window to show, so they are ignored if the
303 // window is initially hidden.
304 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
306 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
308 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
312 OnNativeWindowChanged();
314 ExtensionRegistry::Get(browser_context_
)->AddObserver(this);
316 // Close when the browser process is exiting.
317 app_delegate_
->SetTerminatingCallback(
318 base::Bind(&NativeAppWindow::Close
,
319 base::Unretained(native_app_window_
.get())));
321 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
323 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
324 extensions::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 app_delegate_
->ResizeWebContents(web_contents(), initial_bounds
.size());
335 AppWindow::~AppWindow() {
336 ExtensionRegistry::Get(browser_context_
)->RemoveObserver(this);
339 void AppWindow::RequestMediaAccessPermission(
340 content::WebContents
* web_contents
,
341 const content::MediaStreamRequest
& request
,
342 const content::MediaResponseCallback
& callback
) {
343 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
344 helper_
->RequestMediaAccessPermission(request
, callback
);
347 bool AppWindow::CheckMediaAccessPermission(content::WebContents
* web_contents
,
348 const GURL
& security_origin
,
349 content::MediaStreamType type
) {
350 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
351 return helper_
->CheckMediaAccessPermission(security_origin
, type
);
354 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
355 const content::OpenURLParams
& params
) {
356 DCHECK_EQ(web_contents(), source
);
357 return helper_
->OpenURLFromTab(params
);
360 void AppWindow::AddNewContents(WebContents
* source
,
361 WebContents
* new_contents
,
362 WindowOpenDisposition disposition
,
363 const gfx::Rect
& initial_rect
,
366 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
367 app_delegate_
->AddNewContents(browser_context_
,
375 bool AppWindow::PreHandleKeyboardEvent(
376 content::WebContents
* source
,
377 const content::NativeWebKeyboardEvent
& event
,
378 bool* is_keyboard_shortcut
) {
379 const Extension
* extension
= GetExtension();
383 // Here, we can handle a key event before the content gets it. When we are
384 // fullscreen and it is not forced, we want to allow the user to leave
385 // when ESC is pressed.
386 // However, if the application has the "overrideEscFullscreen" permission, we
387 // should let it override that behavior.
388 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
389 // action is not prevented.
390 // Thus, we should handle the KeyEvent here only if the permission is not set.
391 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
392 !IsForcedFullscreen() &&
393 !extension
->permissions_data()->HasAPIPermission(
394 APIPermission::kOverrideEscFullscreen
)) {
402 void AppWindow::HandleKeyboardEvent(
404 const content::NativeWebKeyboardEvent
& event
) {
405 // If the window is currently fullscreen and not forced, ESC should leave
406 // fullscreen. If this code is being called for ESC, that means that the
407 // KeyEvent's default behavior was not prevented by the content.
408 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
409 !IsForcedFullscreen()) {
414 native_app_window_
->HandleKeyboardEvent(event
);
417 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
419 bool last_unlocked_by_target
) {
420 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
421 helper_
->RequestToLockMouse();
424 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
425 const blink::WebGestureEvent
& event
) {
426 return AppWebContentsHelper::ShouldSuppressGestureEvent(event
);
429 void AppWindow::RenderViewCreated(content::RenderViewHost
* render_view_host
) {
430 app_delegate_
->RenderViewCreated(render_view_host
);
433 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
434 first_paint_complete_
= true;
435 if (show_on_first_paint_
) {
436 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
437 delayed_show_type_
== SHOW_INACTIVE
);
438 Show(delayed_show_type_
);
442 void AppWindow::OnNativeClose() {
443 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
444 if (app_window_contents_
) {
445 WebContentsModalDialogManager
* modal_dialog_manager
=
446 WebContentsModalDialogManager::FromWebContents(web_contents());
447 if (modal_dialog_manager
) // May be null in unit tests.
448 modal_dialog_manager
->SetDelegate(nullptr);
449 app_window_contents_
->NativeWindowClosed();
454 void AppWindow::OnNativeWindowChanged() {
455 SaveWindowPosition();
458 if (native_app_window_
&& cached_always_on_top_
&& !IsFullscreen() &&
459 !native_app_window_
->IsMaximized() &&
460 !native_app_window_
->IsMinimized()) {
461 UpdateNativeAlwaysOnTop();
465 if (app_window_contents_
&& native_app_window_
)
466 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
469 void AppWindow::OnNativeWindowActivated() {
470 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
473 content::WebContents
* AppWindow::web_contents() const {
474 return app_window_contents_
->GetWebContents();
477 const Extension
* AppWindow::GetExtension() const {
478 return ExtensionRegistry::Get(browser_context_
)
479 ->enabled_extensions()
480 .GetByID(extension_id_
);
483 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
485 gfx::NativeWindow
AppWindow::GetNativeWindow() {
486 return GetBaseWindow()->GetNativeWindow();
489 gfx::Rect
AppWindow::GetClientBounds() const {
490 gfx::Rect bounds
= native_app_window_
->GetBounds();
491 bounds
.Inset(native_app_window_
->GetFrameInsets());
495 base::string16
AppWindow::GetTitle() const {
496 const Extension
* extension
= GetExtension();
498 return base::string16();
500 // WebContents::GetTitle() will return the page's URL if there's no <title>
501 // specified. However, we'd prefer to show the name of the extension in that
502 // case, so we directly inspect the NavigationEntry's title.
503 base::string16 title
;
504 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
505 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
506 title
= base::UTF8ToUTF16(extension
->name());
508 title
= web_contents()->GetTitle();
510 base::RemoveChars(title
, base::ASCIIToUTF16("\n"), &title
);
514 void AppWindow::SetAppIconUrl(const GURL
& url
) {
515 // If the same url is being used for the badge, ignore it.
516 if (url
== badge_icon_url_
)
519 // Avoid using any previous icons that were being downloaded.
520 image_loader_ptr_factory_
.InvalidateWeakPtrs();
522 // Reset |app_icon_image_| to abort pending image load (if any).
523 app_icon_image_
.reset();
526 web_contents()->DownloadImage(
528 true, // is a favicon
529 0, // no maximum size
530 false, // normal cache policy
531 base::Bind(&AppWindow::DidDownloadFavicon
,
532 image_loader_ptr_factory_
.GetWeakPtr()));
535 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
536 // Avoid using any previous icons that were being downloaded.
537 image_loader_ptr_factory_
.InvalidateWeakPtrs();
539 // Reset |app_icon_image_| to abort pending image load (if any).
540 badge_icon_image_
.reset();
542 badge_icon_url_
= url
;
543 web_contents()->DownloadImage(
545 true, // is a favicon
546 0, // no maximum size
547 false, // normal cache policy
548 base::Bind(&AppWindow::DidDownloadFavicon
,
549 image_loader_ptr_factory_
.GetWeakPtr()));
552 void AppWindow::ClearBadge() {
553 badge_icon_image_
.reset();
554 badge_icon_url_
= GURL();
555 UpdateBadgeIcon(gfx::Image());
558 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
559 native_app_window_
->UpdateShape(region
.Pass());
562 void AppWindow::UpdateDraggableRegions(
563 const std::vector
<DraggableRegion
>& regions
) {
564 native_app_window_
->UpdateDraggableRegions(regions
);
567 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
571 native_app_window_
->UpdateWindowIcon();
572 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
575 void AppWindow::SetFullscreen(FullscreenType type
, bool enable
) {
576 DCHECK_NE(FULLSCREEN_TYPE_NONE
, type
);
579 #if !defined(OS_MACOSX)
580 // Do not enter fullscreen mode if disallowed by pref.
581 // TODO(bartfab): Add a test once it becomes possible to simulate a user
582 // gesture. http://crbug.com/174178
583 if (type
!= FULLSCREEN_TYPE_FORCED
) {
585 ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
587 if (!prefs
->GetBoolean(pref_names::kAppFullscreenAllowed
))
591 fullscreen_types_
|= type
;
593 fullscreen_types_
&= ~type
;
595 SetNativeWindowFullscreen();
598 bool AppWindow::IsFullscreen() const {
599 return fullscreen_types_
!= FULLSCREEN_TYPE_NONE
;
602 bool AppWindow::IsForcedFullscreen() const {
603 return (fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) != 0;
606 bool AppWindow::IsHtmlApiFullscreen() const {
607 return (fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0;
610 void AppWindow::Fullscreen() {
611 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API
, true);
614 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
616 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
618 void AppWindow::Restore() {
619 if (IsFullscreen()) {
620 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
621 SetNativeWindowFullscreen();
623 GetBaseWindow()->Restore();
627 void AppWindow::OSFullscreen() {
628 SetFullscreen(FULLSCREEN_TYPE_OS
, true);
631 void AppWindow::ForcedFullscreen() {
632 SetFullscreen(FULLSCREEN_TYPE_FORCED
, true);
635 void AppWindow::SetContentSizeConstraints(const gfx::Size
& min_size
,
636 const gfx::Size
& max_size
) {
637 SizeConstraints
constraints(min_size
, max_size
);
638 native_app_window_
->SetContentSizeConstraints(constraints
.GetMinimumSize(),
639 constraints
.GetMaximumSize());
641 gfx::Rect bounds
= GetClientBounds();
642 gfx::Size constrained_size
= constraints
.ClampSize(bounds
.size());
643 if (bounds
.size() != constrained_size
) {
644 bounds
.set_size(constrained_size
);
645 bounds
.Inset(-native_app_window_
->GetFrameInsets());
646 native_app_window_
->SetBounds(bounds
);
648 OnNativeWindowChanged();
651 void AppWindow::Show(ShowType show_type
) {
652 app_delegate_
->OnShow();
653 bool was_hidden
= is_hidden_
|| !has_been_shown_
;
656 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
657 switches::kEnableAppsShowOnFirstPaint
)) {
658 show_on_first_paint_
= true;
660 if (!first_paint_complete_
) {
661 delayed_show_type_
= show_type
;
668 GetBaseWindow()->Show();
671 GetBaseWindow()->ShowInactive();
674 AppWindowRegistry::Get(browser_context_
)->AppWindowShown(this, was_hidden
);
676 has_been_shown_
= true;
677 SendOnWindowShownIfShown();
680 void AppWindow::Hide() {
681 // This is there to prevent race conditions with Hide() being called before
682 // there was a non-empty paint. It should have no effect in a non-racy
683 // scenario where the application is hiding then showing a window: the second
684 // show will not be delayed.
686 show_on_first_paint_
= false;
687 GetBaseWindow()->Hide();
688 AppWindowRegistry::Get(browser_context_
)->AppWindowHidden(this);
689 app_delegate_
->OnHide();
692 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
693 if (cached_always_on_top_
== always_on_top
)
696 cached_always_on_top_
= always_on_top
;
698 // As a security measure, do not allow fullscreen windows or windows that
699 // overlap the taskbar to be on top. The property will be applied when the
700 // window exits fullscreen and moves away from the taskbar.
701 if (!IsFullscreen() && !IntersectsWithTaskbar())
702 native_app_window_
->SetAlwaysOnTop(always_on_top
);
704 OnNativeWindowChanged();
707 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
709 void AppWindow::SetInterceptAllKeys(bool want_all_keys
) {
710 native_app_window_
->SetInterceptAllKeys(want_all_keys
);
713 void AppWindow::WindowEventsReady() {
714 can_send_events_
= true;
715 SendOnWindowShownIfShown();
718 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
721 properties
->SetBoolean("fullscreen",
722 native_app_window_
->IsFullscreenOrPending());
723 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
724 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
725 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
726 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
727 properties
->SetBoolean(
729 requested_alpha_enabled_
&& native_app_window_
->CanHaveAlphaEnabled());
731 // These properties are undocumented and are to enable testing. Alpha is
733 // make the values easier to check.
734 SkColor transparent_white
= ~SK_ColorBLACK
;
735 properties
->SetInteger(
737 native_app_window_
->ActiveFrameColor() & transparent_white
);
738 properties
->SetInteger(
739 "inactiveFrameColor",
740 native_app_window_
->InactiveFrameColor() & transparent_white
);
742 gfx::Rect content_bounds
= GetClientBounds();
743 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
744 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
745 SetBoundsProperties(content_bounds
,
751 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
752 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
753 gfx::Size frame_min_size
= SizeConstraints::AddFrameToConstraints(
754 content_min_size
, frame_insets
);
755 gfx::Size frame_max_size
= SizeConstraints::AddFrameToConstraints(
756 content_max_size
, frame_insets
);
757 SetBoundsProperties(frame_bounds
,
764 //------------------------------------------------------------------------------
767 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
769 native_app_window_
->UpdateBadgeIcon();
772 void AppWindow::DidDownloadFavicon(
774 int http_status_code
,
775 const GURL
& image_url
,
776 const std::vector
<SkBitmap
>& bitmaps
,
777 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
778 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
783 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
784 // whose height >= the preferred size.
785 int largest_index
= 0;
786 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
787 if (bitmaps
[i
].height() < app_delegate_
->PreferredIconSize())
791 const SkBitmap
& largest
= bitmaps
[largest_index
];
792 if (image_url
== app_icon_url_
) {
793 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
797 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
800 void AppWindow::OnExtensionIconImageChanged(IconImage
* image
) {
801 DCHECK_EQ(app_icon_image_
.get(), image
);
803 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
806 void AppWindow::UpdateExtensionAppIcon() {
807 // Avoid using any previous app icons were being downloaded.
808 image_loader_ptr_factory_
.InvalidateWeakPtrs();
810 const Extension
* extension
= GetExtension();
814 gfx::ImageSkia app_default_icon
=
815 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
816 IDR_APP_DEFAULT_ICON
);
818 app_icon_image_
.reset(new IconImage(browser_context(),
820 IconsInfo::GetIcons(extension
),
821 app_delegate_
->PreferredIconSize(),
825 // Triggers actual image loading with 1x resources. The 2x resource will
826 // be handled by IconImage class when requested.
827 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
830 void AppWindow::SetNativeWindowFullscreen() {
831 native_app_window_
->SetFullscreen(fullscreen_types_
);
833 if (cached_always_on_top_
)
834 UpdateNativeAlwaysOnTop();
837 bool AppWindow::IntersectsWithTaskbar() const {
839 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
840 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
841 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
843 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
844 it
!= displays
.end();
846 gfx::Rect taskbar_bounds
= it
->bounds();
847 taskbar_bounds
.Subtract(it
->work_area());
848 if (taskbar_bounds
.IsEmpty())
851 if (window_bounds
.Intersects(taskbar_bounds
))
859 void AppWindow::UpdateNativeAlwaysOnTop() {
860 DCHECK(cached_always_on_top_
);
861 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
862 bool fullscreen
= IsFullscreen();
863 bool intersects_taskbar
= IntersectsWithTaskbar();
865 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
866 // When entering fullscreen or overlapping the taskbar, ensure windows are
867 // not always-on-top.
868 native_app_window_
->SetAlwaysOnTop(false);
869 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
870 // When exiting fullscreen and moving away from the taskbar, reinstate
872 native_app_window_
->SetAlwaysOnTop(true);
876 void AppWindow::SendOnWindowShownIfShown() {
877 if (!can_send_events_
|| !has_been_shown_
)
880 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
881 ::switches::kTestType
)) {
882 app_window_contents_
->DispatchWindowShownForTests();
886 void AppWindow::CloseContents(WebContents
* contents
) {
887 native_app_window_
->Close();
890 bool AppWindow::ShouldSuppressDialogs(WebContents
* source
) {
894 content::ColorChooser
* AppWindow::OpenColorChooser(
895 WebContents
* web_contents
,
896 SkColor initial_color
,
897 const std::vector
<content::ColorSuggestion
>& suggestions
) {
898 return app_delegate_
->ShowColorChooser(web_contents
, initial_color
);
901 void AppWindow::RunFileChooser(WebContents
* tab
,
902 const content::FileChooserParams
& params
) {
903 if (window_type_is_panel()) {
904 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
905 // dialogs to be unhosted but still close with the owning web contents.
907 LOG(WARNING
) << "File dialog opened by panel.";
911 app_delegate_
->RunFileChooser(tab
, params
);
914 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
916 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
917 native_app_window_
->SetBounds(pos
);
920 void AppWindow::NavigationStateChanged(content::WebContents
* source
,
921 content::InvalidateTypes changed_flags
) {
922 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
923 native_app_window_
->UpdateWindowTitle();
924 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
925 native_app_window_
->UpdateWindowIcon();
928 void AppWindow::EnterFullscreenModeForTab(content::WebContents
* source
,
929 const GURL
& origin
) {
930 ToggleFullscreenModeForTab(source
, true);
933 void AppWindow::ExitFullscreenModeForTab(content::WebContents
* source
) {
934 ToggleFullscreenModeForTab(source
, false);
937 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
938 bool enter_fullscreen
) {
939 const Extension
* extension
= GetExtension();
943 if (!IsExtensionWithPermissionOrSuggestInConsole(
944 APIPermission::kFullscreen
, extension
, source
->GetRenderViewHost())) {
948 SetFullscreen(FULLSCREEN_TYPE_HTML_API
, enter_fullscreen
);
951 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
953 return IsHtmlApiFullscreen();
956 void AppWindow::OnExtensionUnloaded(BrowserContext
* browser_context
,
957 const Extension
* extension
,
958 UnloadedExtensionInfo::Reason reason
) {
959 if (extension_id_
== extension
->id())
960 native_app_window_
->Close();
963 void AppWindow::OnExtensionWillBeInstalled(
964 BrowserContext
* browser_context
,
965 const Extension
* extension
,
968 const std::string
& old_name
) {
969 if (extension
->id() == extension_id())
970 native_app_window_
->UpdateShelfMenu();
972 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
974 app_delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
977 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
978 return app_delegate_
->IsWebContentsVisible(web_contents
);
981 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
982 return native_app_window_
.get();
985 void AppWindow::SaveWindowPosition() {
986 if (window_key_
.empty())
988 if (!native_app_window_
)
991 AppWindowGeometryCache
* cache
=
992 AppWindowGeometryCache::Get(browser_context());
994 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
995 gfx::Rect screen_bounds
=
996 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
997 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
999 extension_id(), window_key_
, bounds
, screen_bounds
, window_state
);
1002 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1003 const gfx::Rect
& cached_bounds
,
1004 const gfx::Rect
& cached_screen_bounds
,
1005 const gfx::Rect
& current_screen_bounds
,
1006 const gfx::Size
& minimum_size
,
1007 gfx::Rect
* bounds
) const {
1008 *bounds
= cached_bounds
;
1010 // Reposition and resize the bounds if the cached_screen_bounds is different
1011 // from the current screen bounds and the current screen bounds doesn't
1012 // completely contain the bounds.
1013 if (cached_screen_bounds
!= current_screen_bounds
&&
1014 !current_screen_bounds
.Contains(cached_bounds
)) {
1016 std::max(minimum_size
.width(),
1017 std::min(bounds
->width(), current_screen_bounds
.width())));
1019 std::max(minimum_size
.height(),
1020 std::min(bounds
->height(), current_screen_bounds
.height())));
1022 std::max(current_screen_bounds
.x(),
1023 std::min(bounds
->x(),
1024 current_screen_bounds
.right() - bounds
->width())));
1026 std::max(current_screen_bounds
.y(),
1027 std::min(bounds
->y(),
1028 current_screen_bounds
.bottom() - bounds
->height())));
1032 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1034 // Ensure width and height are specified.
1035 if (params
.content_spec
.bounds
.width() == 0 &&
1036 params
.window_spec
.bounds
.width() == 0) {
1037 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1039 if (params
.content_spec
.bounds
.height() == 0 &&
1040 params
.window_spec
.bounds
.height() == 0) {
1041 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1044 // If left and top are left undefined, the native app window will center
1045 // the window on the main screen in a platform-defined manner.
1047 // Load cached state if it exists.
1048 if (!params
.window_key
.empty()) {
1049 AppWindowGeometryCache
* cache
=
1050 AppWindowGeometryCache::Get(browser_context());
1052 gfx::Rect cached_bounds
;
1053 gfx::Rect cached_screen_bounds
;
1054 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1055 if (cache
->GetGeometry(extension_id(),
1058 &cached_screen_bounds
,
1060 // App window has cached screen bounds, make sure it fits on screen in
1061 // case the screen resolution changed.
1062 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1063 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1064 gfx::Rect current_screen_bounds
= display
.work_area();
1065 SizeConstraints
constraints(params
.GetWindowMinimumSize(gfx::Insets()),
1066 params
.GetWindowMaximumSize(gfx::Insets()));
1067 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1068 cached_screen_bounds
,
1069 current_screen_bounds
,
1070 constraints
.GetMinimumSize(),
1071 ¶ms
.window_spec
.bounds
);
1072 params
.state
= cached_state
;
1074 // Since we are restoring a cached state, reset the content bounds spec to
1075 // ensure it is not used.
1076 params
.content_spec
.ResetBounds();
1084 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1085 const std::vector
<DraggableRegion
>& regions
) {
1086 SkRegion
* sk_region
= new SkRegion
;
1087 for (std::vector
<DraggableRegion
>::const_iterator iter
= regions
.begin();
1088 iter
!= regions
.end();
1090 const DraggableRegion
& region
= *iter
;
1094 region
.bounds
.right(),
1095 region
.bounds
.bottom(),
1096 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);
1101 } // namespace extensions