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
);
257 content::WebContentsObserver::Observe(web_contents());
258 SetViewType(web_contents(), VIEW_TYPE_APP_WINDOW
);
259 app_delegate_
->InitWebContents(web_contents());
261 WebContentsModalDialogManager::CreateForWebContents(web_contents());
263 web_contents()->SetDelegate(this);
264 WebContentsModalDialogManager::FromWebContents(web_contents())
267 // Initialize the window
268 CreateParams new_params
= LoadDefaults(params
);
269 window_type_
= new_params
.window_type
;
270 window_key_
= new_params
.window_key
;
272 // Windows cannot be always-on-top in fullscreen mode for security reasons.
273 cached_always_on_top_
= new_params
.always_on_top
;
274 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
275 new_params
.always_on_top
= false;
277 requested_alpha_enabled_
= new_params
.alpha_enabled
;
279 is_ime_window_
= params
.is_ime_window
;
281 AppWindowClient
* app_window_client
= AppWindowClient::Get();
282 native_app_window_
.reset(
283 app_window_client
->CreateNativeAppWindow(this, &new_params
));
285 helper_
.reset(new AppWebContentsHelper(
286 browser_context_
, extension_id_
, web_contents(), app_delegate_
.get()));
288 popup_manager_
.reset(
289 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
290 popup_manager_
->RegisterWith(web_contents());
292 UpdateExtensionAppIcon();
293 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
295 if (new_params
.hidden
) {
296 // Although the window starts hidden by default, calling Hide() here
297 // notifies observers of the window being hidden.
300 // Panels are not activated by default.
301 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
304 // These states may cause the window to show, so they are ignored if the
305 // window is initially hidden.
306 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
308 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
310 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
314 OnNativeWindowChanged();
316 ExtensionRegistry::Get(browser_context_
)->AddObserver(this);
318 // Close when the browser process is exiting.
319 app_delegate_
->SetTerminatingCallback(
320 base::Bind(&NativeAppWindow::Close
,
321 base::Unretained(native_app_window_
.get())));
323 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
325 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
326 extensions::switches::kEnableAppsShowOnFirstPaint
)) {
327 // We want to show the window only when the content has been painted. For
328 // that to happen, we need to define a size for the content, otherwise the
329 // layout will happen in a 0x0 area.
330 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
331 gfx::Rect initial_bounds
= new_params
.GetInitialWindowBounds(frame_insets
);
332 initial_bounds
.Inset(frame_insets
);
333 app_delegate_
->ResizeWebContents(web_contents(), initial_bounds
.size());
337 AppWindow::~AppWindow() {
338 ExtensionRegistry::Get(browser_context_
)->RemoveObserver(this);
341 void AppWindow::RequestMediaAccessPermission(
342 content::WebContents
* web_contents
,
343 const content::MediaStreamRequest
& request
,
344 const content::MediaResponseCallback
& callback
) {
345 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
346 helper_
->RequestMediaAccessPermission(request
, callback
);
349 bool AppWindow::CheckMediaAccessPermission(content::WebContents
* web_contents
,
350 const GURL
& security_origin
,
351 content::MediaStreamType type
) {
352 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
353 return helper_
->CheckMediaAccessPermission(security_origin
, type
);
356 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
357 const content::OpenURLParams
& params
) {
358 DCHECK_EQ(web_contents(), source
);
359 return helper_
->OpenURLFromTab(params
);
362 void AppWindow::AddNewContents(WebContents
* source
,
363 WebContents
* new_contents
,
364 WindowOpenDisposition disposition
,
365 const gfx::Rect
& initial_rect
,
368 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
369 app_delegate_
->AddNewContents(browser_context_
,
377 bool AppWindow::PreHandleKeyboardEvent(
378 content::WebContents
* source
,
379 const content::NativeWebKeyboardEvent
& event
,
380 bool* is_keyboard_shortcut
) {
381 const Extension
* extension
= GetExtension();
385 // Here, we can handle a key event before the content gets it. When we are
386 // fullscreen and it is not forced, we want to allow the user to leave
387 // when ESC is pressed.
388 // However, if the application has the "overrideEscFullscreen" permission, we
389 // should let it override that behavior.
390 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
391 // action is not prevented.
392 // Thus, we should handle the KeyEvent here only if the permission is not set.
393 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
394 !IsForcedFullscreen() &&
395 !extension
->permissions_data()->HasAPIPermission(
396 APIPermission::kOverrideEscFullscreen
)) {
404 void AppWindow::HandleKeyboardEvent(
406 const content::NativeWebKeyboardEvent
& event
) {
407 // If the window is currently fullscreen and not forced, ESC should leave
408 // fullscreen. If this code is being called for ESC, that means that the
409 // KeyEvent's default behavior was not prevented by the content.
410 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
411 !IsForcedFullscreen()) {
416 native_app_window_
->HandleKeyboardEvent(event
);
419 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
421 bool last_unlocked_by_target
) {
422 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
423 helper_
->RequestToLockMouse();
426 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
427 const blink::WebGestureEvent
& event
) {
428 return AppWebContentsHelper::ShouldSuppressGestureEvent(event
);
431 void AppWindow::RenderViewCreated(content::RenderViewHost
* render_view_host
) {
432 app_delegate_
->RenderViewCreated(render_view_host
);
435 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
436 first_paint_complete_
= true;
437 if (show_on_first_paint_
) {
438 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
439 delayed_show_type_
== SHOW_INACTIVE
);
440 Show(delayed_show_type_
);
444 void AppWindow::OnNativeClose() {
445 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
446 if (app_window_contents_
) {
447 WebContentsModalDialogManager
* modal_dialog_manager
=
448 WebContentsModalDialogManager::FromWebContents(web_contents());
449 if (modal_dialog_manager
) // May be null in unit tests.
450 modal_dialog_manager
->SetDelegate(nullptr);
451 app_window_contents_
->NativeWindowClosed();
456 void AppWindow::OnNativeWindowChanged() {
457 SaveWindowPosition();
460 if (native_app_window_
&& cached_always_on_top_
&& !IsFullscreen() &&
461 !native_app_window_
->IsMaximized() &&
462 !native_app_window_
->IsMinimized()) {
463 UpdateNativeAlwaysOnTop();
467 if (app_window_contents_
&& native_app_window_
)
468 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
471 void AppWindow::OnNativeWindowActivated() {
472 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
475 content::WebContents
* AppWindow::web_contents() const {
476 return app_window_contents_
->GetWebContents();
479 const Extension
* AppWindow::GetExtension() const {
480 return ExtensionRegistry::Get(browser_context_
)
481 ->enabled_extensions()
482 .GetByID(extension_id_
);
485 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
487 gfx::NativeWindow
AppWindow::GetNativeWindow() {
488 return GetBaseWindow()->GetNativeWindow();
491 gfx::Rect
AppWindow::GetClientBounds() const {
492 gfx::Rect bounds
= native_app_window_
->GetBounds();
493 bounds
.Inset(native_app_window_
->GetFrameInsets());
497 base::string16
AppWindow::GetTitle() const {
498 const Extension
* extension
= GetExtension();
500 return base::string16();
502 // WebContents::GetTitle() will return the page's URL if there's no <title>
503 // specified. However, we'd prefer to show the name of the extension in that
504 // case, so we directly inspect the NavigationEntry's title.
505 base::string16 title
;
506 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
507 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
508 title
= base::UTF8ToUTF16(extension
->name());
510 title
= web_contents()->GetTitle();
512 base::RemoveChars(title
, base::ASCIIToUTF16("\n"), &title
);
516 void AppWindow::SetAppIconUrl(const GURL
& url
) {
517 // If the same url is being used for the badge, ignore it.
518 if (url
== badge_icon_url_
)
521 // Avoid using any previous icons that were being downloaded.
522 image_loader_ptr_factory_
.InvalidateWeakPtrs();
524 // Reset |app_icon_image_| to abort pending image load (if any).
525 app_icon_image_
.reset();
528 web_contents()->DownloadImage(
530 true, // is a favicon
531 0, // no maximum size
532 false, // normal cache policy
533 base::Bind(&AppWindow::DidDownloadFavicon
,
534 image_loader_ptr_factory_
.GetWeakPtr()));
537 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
538 // Avoid using any previous icons that were being downloaded.
539 image_loader_ptr_factory_
.InvalidateWeakPtrs();
541 // Reset |app_icon_image_| to abort pending image load (if any).
542 badge_icon_image_
.reset();
544 badge_icon_url_
= url
;
545 web_contents()->DownloadImage(
547 true, // is a favicon
548 0, // no maximum size
549 false, // normal cache policy
550 base::Bind(&AppWindow::DidDownloadFavicon
,
551 image_loader_ptr_factory_
.GetWeakPtr()));
554 void AppWindow::ClearBadge() {
555 badge_icon_image_
.reset();
556 badge_icon_url_
= GURL();
557 UpdateBadgeIcon(gfx::Image());
560 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
561 native_app_window_
->UpdateShape(region
.Pass());
564 void AppWindow::UpdateDraggableRegions(
565 const std::vector
<DraggableRegion
>& regions
) {
566 native_app_window_
->UpdateDraggableRegions(regions
);
569 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
573 native_app_window_
->UpdateWindowIcon();
574 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
577 void AppWindow::SetFullscreen(FullscreenType type
, bool enable
) {
578 DCHECK_NE(FULLSCREEN_TYPE_NONE
, type
);
581 #if !defined(OS_MACOSX)
582 // Do not enter fullscreen mode if disallowed by pref.
583 // TODO(bartfab): Add a test once it becomes possible to simulate a user
584 // gesture. http://crbug.com/174178
585 if (type
!= FULLSCREEN_TYPE_FORCED
) {
587 ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
589 if (!prefs
->GetBoolean(pref_names::kAppFullscreenAllowed
))
593 fullscreen_types_
|= type
;
595 fullscreen_types_
&= ~type
;
597 SetNativeWindowFullscreen();
600 bool AppWindow::IsFullscreen() const {
601 return fullscreen_types_
!= FULLSCREEN_TYPE_NONE
;
604 bool AppWindow::IsForcedFullscreen() const {
605 return (fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) != 0;
608 bool AppWindow::IsHtmlApiFullscreen() const {
609 return (fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0;
612 void AppWindow::Fullscreen() {
613 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API
, true);
616 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
618 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
620 void AppWindow::Restore() {
621 if (IsFullscreen()) {
622 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
623 SetNativeWindowFullscreen();
625 GetBaseWindow()->Restore();
629 void AppWindow::OSFullscreen() {
630 SetFullscreen(FULLSCREEN_TYPE_OS
, true);
633 void AppWindow::ForcedFullscreen() {
634 SetFullscreen(FULLSCREEN_TYPE_FORCED
, true);
637 void AppWindow::SetContentSizeConstraints(const gfx::Size
& min_size
,
638 const gfx::Size
& max_size
) {
639 SizeConstraints
constraints(min_size
, max_size
);
640 native_app_window_
->SetContentSizeConstraints(constraints
.GetMinimumSize(),
641 constraints
.GetMaximumSize());
643 gfx::Rect bounds
= GetClientBounds();
644 gfx::Size constrained_size
= constraints
.ClampSize(bounds
.size());
645 if (bounds
.size() != constrained_size
) {
646 bounds
.set_size(constrained_size
);
647 bounds
.Inset(-native_app_window_
->GetFrameInsets());
648 native_app_window_
->SetBounds(bounds
);
650 OnNativeWindowChanged();
653 void AppWindow::Show(ShowType show_type
) {
654 app_delegate_
->OnShow();
655 bool was_hidden
= is_hidden_
|| !has_been_shown_
;
658 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
659 switches::kEnableAppsShowOnFirstPaint
)) {
660 show_on_first_paint_
= true;
662 if (!first_paint_complete_
) {
663 delayed_show_type_
= show_type
;
670 GetBaseWindow()->Show();
673 GetBaseWindow()->ShowInactive();
676 AppWindowRegistry::Get(browser_context_
)->AppWindowShown(this, was_hidden
);
678 has_been_shown_
= true;
679 SendOnWindowShownIfShown();
682 void AppWindow::Hide() {
683 // This is there to prevent race conditions with Hide() being called before
684 // there was a non-empty paint. It should have no effect in a non-racy
685 // scenario where the application is hiding then showing a window: the second
686 // show will not be delayed.
688 show_on_first_paint_
= false;
689 GetBaseWindow()->Hide();
690 AppWindowRegistry::Get(browser_context_
)->AppWindowHidden(this);
691 app_delegate_
->OnHide();
694 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
695 if (cached_always_on_top_
== always_on_top
)
698 cached_always_on_top_
= always_on_top
;
700 // As a security measure, do not allow fullscreen windows or windows that
701 // overlap the taskbar to be on top. The property will be applied when the
702 // window exits fullscreen and moves away from the taskbar.
703 if (!IsFullscreen() && !IntersectsWithTaskbar())
704 native_app_window_
->SetAlwaysOnTop(always_on_top
);
706 OnNativeWindowChanged();
709 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
711 void AppWindow::SetInterceptAllKeys(bool want_all_keys
) {
712 native_app_window_
->SetInterceptAllKeys(want_all_keys
);
715 void AppWindow::WindowEventsReady() {
716 can_send_events_
= true;
717 SendOnWindowShownIfShown();
720 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
723 properties
->SetBoolean("fullscreen",
724 native_app_window_
->IsFullscreenOrPending());
725 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
726 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
727 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
728 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
729 properties
->SetBoolean(
731 requested_alpha_enabled_
&& native_app_window_
->CanHaveAlphaEnabled());
733 // These properties are undocumented and are to enable testing. Alpha is
735 // make the values easier to check.
736 SkColor transparent_white
= ~SK_ColorBLACK
;
737 properties
->SetInteger(
739 native_app_window_
->ActiveFrameColor() & transparent_white
);
740 properties
->SetInteger(
741 "inactiveFrameColor",
742 native_app_window_
->InactiveFrameColor() & transparent_white
);
744 gfx::Rect content_bounds
= GetClientBounds();
745 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
746 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
747 SetBoundsProperties(content_bounds
,
753 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
754 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
755 gfx::Size frame_min_size
= SizeConstraints::AddFrameToConstraints(
756 content_min_size
, frame_insets
);
757 gfx::Size frame_max_size
= SizeConstraints::AddFrameToConstraints(
758 content_max_size
, frame_insets
);
759 SetBoundsProperties(frame_bounds
,
766 //------------------------------------------------------------------------------
769 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
771 native_app_window_
->UpdateBadgeIcon();
774 void AppWindow::DidDownloadFavicon(
776 int http_status_code
,
777 const GURL
& image_url
,
778 const std::vector
<SkBitmap
>& bitmaps
,
779 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
780 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
785 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
786 // whose height >= the preferred size.
787 int largest_index
= 0;
788 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
789 if (bitmaps
[i
].height() < app_delegate_
->PreferredIconSize())
793 const SkBitmap
& largest
= bitmaps
[largest_index
];
794 if (image_url
== app_icon_url_
) {
795 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
799 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
802 void AppWindow::OnExtensionIconImageChanged(IconImage
* image
) {
803 DCHECK_EQ(app_icon_image_
.get(), image
);
805 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
808 void AppWindow::UpdateExtensionAppIcon() {
809 // Avoid using any previous app icons were being downloaded.
810 image_loader_ptr_factory_
.InvalidateWeakPtrs();
812 const Extension
* extension
= GetExtension();
816 gfx::ImageSkia app_default_icon
=
817 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
818 IDR_APP_DEFAULT_ICON
);
820 app_icon_image_
.reset(new IconImage(browser_context(),
822 IconsInfo::GetIcons(extension
),
823 app_delegate_
->PreferredIconSize(),
827 // Triggers actual image loading with 1x resources. The 2x resource will
828 // be handled by IconImage class when requested.
829 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
832 void AppWindow::SetNativeWindowFullscreen() {
833 native_app_window_
->SetFullscreen(fullscreen_types_
);
835 if (cached_always_on_top_
)
836 UpdateNativeAlwaysOnTop();
839 bool AppWindow::IntersectsWithTaskbar() const {
841 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
842 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
843 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
845 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
846 it
!= displays
.end();
848 gfx::Rect taskbar_bounds
= it
->bounds();
849 taskbar_bounds
.Subtract(it
->work_area());
850 if (taskbar_bounds
.IsEmpty())
853 if (window_bounds
.Intersects(taskbar_bounds
))
861 void AppWindow::UpdateNativeAlwaysOnTop() {
862 DCHECK(cached_always_on_top_
);
863 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
864 bool fullscreen
= IsFullscreen();
865 bool intersects_taskbar
= IntersectsWithTaskbar();
867 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
868 // When entering fullscreen or overlapping the taskbar, ensure windows are
869 // not always-on-top.
870 native_app_window_
->SetAlwaysOnTop(false);
871 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
872 // When exiting fullscreen and moving away from the taskbar, reinstate
874 native_app_window_
->SetAlwaysOnTop(true);
878 void AppWindow::SendOnWindowShownIfShown() {
879 if (!can_send_events_
|| !has_been_shown_
)
882 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
883 ::switches::kTestType
)) {
884 app_window_contents_
->DispatchWindowShownForTests();
888 void AppWindow::CloseContents(WebContents
* contents
) {
889 native_app_window_
->Close();
892 bool AppWindow::ShouldSuppressDialogs(WebContents
* source
) {
896 content::ColorChooser
* AppWindow::OpenColorChooser(
897 WebContents
* web_contents
,
898 SkColor initial_color
,
899 const std::vector
<content::ColorSuggestion
>& suggestions
) {
900 return app_delegate_
->ShowColorChooser(web_contents
, initial_color
);
903 void AppWindow::RunFileChooser(WebContents
* tab
,
904 const content::FileChooserParams
& params
) {
905 if (window_type_is_panel()) {
906 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
907 // dialogs to be unhosted but still close with the owning web contents.
909 LOG(WARNING
) << "File dialog opened by panel.";
913 app_delegate_
->RunFileChooser(tab
, params
);
916 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
918 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
919 native_app_window_
->SetBounds(pos
);
922 void AppWindow::NavigationStateChanged(content::WebContents
* source
,
923 content::InvalidateTypes changed_flags
) {
924 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
925 native_app_window_
->UpdateWindowTitle();
926 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
927 native_app_window_
->UpdateWindowIcon();
930 void AppWindow::EnterFullscreenModeForTab(content::WebContents
* source
,
931 const GURL
& origin
) {
932 ToggleFullscreenModeForTab(source
, true);
935 void AppWindow::ExitFullscreenModeForTab(content::WebContents
* source
) {
936 ToggleFullscreenModeForTab(source
, false);
939 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
940 bool enter_fullscreen
) {
941 const Extension
* extension
= GetExtension();
945 if (!IsExtensionWithPermissionOrSuggestInConsole(
946 APIPermission::kFullscreen
, extension
, source
->GetRenderViewHost())) {
950 SetFullscreen(FULLSCREEN_TYPE_HTML_API
, enter_fullscreen
);
953 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
955 return IsHtmlApiFullscreen();
958 blink::WebDisplayMode
AppWindow::GetDisplayMode(
959 const content::WebContents
* source
) const {
960 return IsFullscreen() ? blink::WebDisplayModeFullscreen
961 : blink::WebDisplayModeStandalone
;
964 void AppWindow::OnExtensionUnloaded(BrowserContext
* browser_context
,
965 const Extension
* extension
,
966 UnloadedExtensionInfo::Reason reason
) {
967 if (extension_id_
== extension
->id())
968 native_app_window_
->Close();
971 void AppWindow::OnExtensionWillBeInstalled(
972 BrowserContext
* browser_context
,
973 const Extension
* extension
,
976 const std::string
& old_name
) {
977 if (extension
->id() == extension_id())
978 native_app_window_
->UpdateShelfMenu();
980 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
982 app_delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
985 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
986 return app_delegate_
->IsWebContentsVisible(web_contents
);
989 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
990 return native_app_window_
.get();
993 void AppWindow::SaveWindowPosition() {
994 if (window_key_
.empty())
996 if (!native_app_window_
)
999 AppWindowGeometryCache
* cache
=
1000 AppWindowGeometryCache::Get(browser_context());
1002 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
1003 gfx::Rect screen_bounds
=
1004 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
1005 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
1006 cache
->SaveGeometry(
1007 extension_id(), window_key_
, bounds
, screen_bounds
, window_state
);
1010 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1011 const gfx::Rect
& cached_bounds
,
1012 const gfx::Rect
& cached_screen_bounds
,
1013 const gfx::Rect
& current_screen_bounds
,
1014 const gfx::Size
& minimum_size
,
1015 gfx::Rect
* bounds
) const {
1016 *bounds
= cached_bounds
;
1018 // Reposition and resize the bounds if the cached_screen_bounds is different
1019 // from the current screen bounds and the current screen bounds doesn't
1020 // completely contain the bounds.
1021 if (cached_screen_bounds
!= current_screen_bounds
&&
1022 !current_screen_bounds
.Contains(cached_bounds
)) {
1024 std::max(minimum_size
.width(),
1025 std::min(bounds
->width(), current_screen_bounds
.width())));
1027 std::max(minimum_size
.height(),
1028 std::min(bounds
->height(), current_screen_bounds
.height())));
1030 std::max(current_screen_bounds
.x(),
1031 std::min(bounds
->x(),
1032 current_screen_bounds
.right() - bounds
->width())));
1034 std::max(current_screen_bounds
.y(),
1035 std::min(bounds
->y(),
1036 current_screen_bounds
.bottom() - bounds
->height())));
1040 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1042 // Ensure width and height are specified.
1043 if (params
.content_spec
.bounds
.width() == 0 &&
1044 params
.window_spec
.bounds
.width() == 0) {
1045 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1047 if (params
.content_spec
.bounds
.height() == 0 &&
1048 params
.window_spec
.bounds
.height() == 0) {
1049 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1052 // If left and top are left undefined, the native app window will center
1053 // the window on the main screen in a platform-defined manner.
1055 // Load cached state if it exists.
1056 if (!params
.window_key
.empty()) {
1057 AppWindowGeometryCache
* cache
=
1058 AppWindowGeometryCache::Get(browser_context());
1060 gfx::Rect cached_bounds
;
1061 gfx::Rect cached_screen_bounds
;
1062 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1063 if (cache
->GetGeometry(extension_id(),
1066 &cached_screen_bounds
,
1068 // App window has cached screen bounds, make sure it fits on screen in
1069 // case the screen resolution changed.
1070 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1071 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1072 gfx::Rect current_screen_bounds
= display
.work_area();
1073 SizeConstraints
constraints(params
.GetWindowMinimumSize(gfx::Insets()),
1074 params
.GetWindowMaximumSize(gfx::Insets()));
1075 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1076 cached_screen_bounds
,
1077 current_screen_bounds
,
1078 constraints
.GetMinimumSize(),
1079 ¶ms
.window_spec
.bounds
);
1080 params
.state
= cached_state
;
1082 // Since we are restoring a cached state, reset the content bounds spec to
1083 // ensure it is not used.
1084 params
.content_spec
.ResetBounds();
1092 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1093 const std::vector
<DraggableRegion
>& regions
) {
1094 SkRegion
* sk_region
= new SkRegion
;
1095 for (std::vector
<DraggableRegion
>::const_iterator iter
= regions
.begin();
1096 iter
!= regions
.end();
1098 const DraggableRegion
& region
= *iter
;
1102 region
.bounds
.right(),
1103 region
.bounds
.bottom(),
1104 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);
1109 } // namespace extensions