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 fullscreen_types_(FULLSCREEN_TYPE_NONE
),
238 show_on_first_paint_(false),
239 first_paint_complete_(false),
240 has_been_shown_(false),
241 can_send_events_(false),
243 cached_always_on_top_(false),
244 requested_alpha_enabled_(false),
245 image_loader_ptr_factory_(this) {
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
);
258 content::WebContentsObserver::Observe(web_contents());
259 app_delegate_
->InitWebContents(web_contents());
261 WebContentsModalDialogManager::CreateForWebContents(web_contents());
263 web_contents()->SetDelegate(this);
264 WebContentsModalDialogManager::FromWebContents(web_contents())
266 SetViewType(web_contents(), VIEW_TYPE_APP_WINDOW
);
268 // Initialize the window
269 CreateParams new_params
= LoadDefaults(params
);
270 window_type_
= new_params
.window_type
;
271 window_key_
= new_params
.window_key
;
273 // Windows cannot be always-on-top in fullscreen mode for security reasons.
274 cached_always_on_top_
= new_params
.always_on_top
;
275 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
276 new_params
.always_on_top
= false;
278 requested_alpha_enabled_
= new_params
.alpha_enabled
;
280 AppWindowClient
* app_window_client
= AppWindowClient::Get();
281 native_app_window_
.reset(
282 app_window_client
->CreateNativeAppWindow(this, &new_params
));
284 helper_
.reset(new AppWebContentsHelper(
285 browser_context_
, extension_id_
, web_contents(), app_delegate_
.get()));
287 popup_manager_
.reset(
288 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
289 popup_manager_
->RegisterWith(web_contents());
291 UpdateExtensionAppIcon();
292 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
294 if (new_params
.hidden
) {
295 // Although the window starts hidden by default, calling Hide() here
296 // notifies observers of the window being hidden.
299 // Panels are not activated by default.
300 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
303 // These states may cause the window to show, so they are ignored if the
304 // window is initially hidden.
305 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
307 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
309 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
313 OnNativeWindowChanged();
315 // When the render view host is changed, the native window needs to know
316 // about it in case it has any setup to do to make the renderer appear
317 // properly. In particular, on Windows, the view's clickthrough region needs
319 ExtensionsBrowserClient
* client
= ExtensionsBrowserClient::Get();
321 NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
322 content::Source
<content::BrowserContext
>(
323 client
->GetOriginalContext(browser_context_
)));
324 // Update the app menu if an ephemeral app becomes installed.
326 NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
327 content::Source
<content::BrowserContext
>(
328 client
->GetOriginalContext(browser_context_
)));
330 // Close when the browser process is exiting.
331 app_delegate_
->SetTerminatingCallback(
332 base::Bind(&NativeAppWindow::Close
,
333 base::Unretained(native_app_window_
.get())));
335 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
337 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
338 extensions::switches::kEnableAppsShowOnFirstPaint
)) {
339 // We want to show the window only when the content has been painted. For
340 // that to happen, we need to define a size for the content, otherwise the
341 // layout will happen in a 0x0 area.
342 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
343 gfx::Rect initial_bounds
= new_params
.GetInitialWindowBounds(frame_insets
);
344 initial_bounds
.Inset(frame_insets
);
345 app_delegate_
->ResizeWebContents(web_contents(), initial_bounds
.size());
349 AppWindow::~AppWindow() {
352 void AppWindow::RequestMediaAccessPermission(
353 content::WebContents
* web_contents
,
354 const content::MediaStreamRequest
& request
,
355 const content::MediaResponseCallback
& callback
) {
356 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
357 helper_
->RequestMediaAccessPermission(request
, callback
);
360 bool AppWindow::CheckMediaAccessPermission(content::WebContents
* web_contents
,
361 const GURL
& security_origin
,
362 content::MediaStreamType type
) {
363 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
364 return helper_
->CheckMediaAccessPermission(security_origin
, type
);
367 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
368 const content::OpenURLParams
& params
) {
369 DCHECK_EQ(web_contents(), source
);
370 return helper_
->OpenURLFromTab(params
);
373 void AppWindow::AddNewContents(WebContents
* source
,
374 WebContents
* new_contents
,
375 WindowOpenDisposition disposition
,
376 const gfx::Rect
& initial_pos
,
379 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
380 app_delegate_
->AddNewContents(browser_context_
,
388 bool AppWindow::PreHandleKeyboardEvent(
389 content::WebContents
* source
,
390 const content::NativeWebKeyboardEvent
& event
,
391 bool* is_keyboard_shortcut
) {
392 const Extension
* extension
= GetExtension();
396 // Here, we can handle a key event before the content gets it. When we are
397 // fullscreen and it is not forced, we want to allow the user to leave
398 // when ESC is pressed.
399 // However, if the application has the "overrideEscFullscreen" permission, we
400 // should let it override that behavior.
401 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
402 // action is not prevented.
403 // Thus, we should handle the KeyEvent here only if the permission is not set.
404 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
405 !IsForcedFullscreen() &&
406 !extension
->permissions_data()->HasAPIPermission(
407 APIPermission::kOverrideEscFullscreen
)) {
415 void AppWindow::HandleKeyboardEvent(
417 const content::NativeWebKeyboardEvent
& event
) {
418 // If the window is currently fullscreen and not forced, ESC should leave
419 // fullscreen. If this code is being called for ESC, that means that the
420 // KeyEvent's default behavior was not prevented by the content.
421 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
422 !IsForcedFullscreen()) {
427 native_app_window_
->HandleKeyboardEvent(event
);
430 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
432 bool last_unlocked_by_target
) {
433 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
434 helper_
->RequestToLockMouse();
437 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
438 const blink::WebGestureEvent
& event
) {
439 return AppWebContentsHelper::ShouldSuppressGestureEvent(event
);
442 void AppWindow::RenderViewCreated(content::RenderViewHost
* render_view_host
) {
443 app_delegate_
->RenderViewCreated(render_view_host
);
446 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
447 first_paint_complete_
= true;
448 if (show_on_first_paint_
) {
449 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
450 delayed_show_type_
== SHOW_INACTIVE
);
451 Show(delayed_show_type_
);
455 void AppWindow::OnNativeClose() {
456 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
457 if (app_window_contents_
) {
458 WebContentsModalDialogManager
* modal_dialog_manager
=
459 WebContentsModalDialogManager::FromWebContents(web_contents());
460 if (modal_dialog_manager
) // May be null in unit tests.
461 modal_dialog_manager
->SetDelegate(nullptr);
462 app_window_contents_
->NativeWindowClosed();
467 void AppWindow::OnNativeWindowChanged() {
468 SaveWindowPosition();
471 if (native_app_window_
&& cached_always_on_top_
&& !IsFullscreen() &&
472 !native_app_window_
->IsMaximized() &&
473 !native_app_window_
->IsMinimized()) {
474 UpdateNativeAlwaysOnTop();
478 if (app_window_contents_
&& native_app_window_
)
479 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
482 void AppWindow::OnNativeWindowActivated() {
483 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
486 content::WebContents
* AppWindow::web_contents() const {
487 return app_window_contents_
->GetWebContents();
490 const Extension
* AppWindow::GetExtension() const {
491 return ExtensionRegistry::Get(browser_context_
)
492 ->enabled_extensions()
493 .GetByID(extension_id_
);
496 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
498 gfx::NativeWindow
AppWindow::GetNativeWindow() {
499 return GetBaseWindow()->GetNativeWindow();
502 gfx::Rect
AppWindow::GetClientBounds() const {
503 gfx::Rect bounds
= native_app_window_
->GetBounds();
504 bounds
.Inset(native_app_window_
->GetFrameInsets());
508 base::string16
AppWindow::GetTitle() const {
509 const Extension
* extension
= GetExtension();
511 return base::string16();
513 // WebContents::GetTitle() will return the page's URL if there's no <title>
514 // specified. However, we'd prefer to show the name of the extension in that
515 // case, so we directly inspect the NavigationEntry's title.
516 base::string16 title
;
517 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
518 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
519 title
= base::UTF8ToUTF16(extension
->name());
521 title
= web_contents()->GetTitle();
523 base::RemoveChars(title
, base::ASCIIToUTF16("\n"), &title
);
527 void AppWindow::SetAppIconUrl(const GURL
& url
) {
528 // If the same url is being used for the badge, ignore it.
529 if (url
== badge_icon_url_
)
532 // Avoid using any previous icons that were being downloaded.
533 image_loader_ptr_factory_
.InvalidateWeakPtrs();
535 // Reset |app_icon_image_| to abort pending image load (if any).
536 app_icon_image_
.reset();
539 web_contents()->DownloadImage(
541 true, // is a favicon
542 0, // no maximum size
543 base::Bind(&AppWindow::DidDownloadFavicon
,
544 image_loader_ptr_factory_
.GetWeakPtr()));
547 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
548 // Avoid using any previous icons that were being downloaded.
549 image_loader_ptr_factory_
.InvalidateWeakPtrs();
551 // Reset |app_icon_image_| to abort pending image load (if any).
552 badge_icon_image_
.reset();
554 badge_icon_url_
= url
;
555 web_contents()->DownloadImage(
557 true, // is a favicon
558 0, // no maximum size
559 base::Bind(&AppWindow::DidDownloadFavicon
,
560 image_loader_ptr_factory_
.GetWeakPtr()));
563 void AppWindow::ClearBadge() {
564 badge_icon_image_
.reset();
565 badge_icon_url_
= GURL();
566 UpdateBadgeIcon(gfx::Image());
569 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
570 native_app_window_
->UpdateShape(region
.Pass());
573 void AppWindow::UpdateDraggableRegions(
574 const std::vector
<DraggableRegion
>& regions
) {
575 native_app_window_
->UpdateDraggableRegions(regions
);
578 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
582 native_app_window_
->UpdateWindowIcon();
583 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
586 void AppWindow::SetFullscreen(FullscreenType type
, bool enable
) {
587 DCHECK_NE(FULLSCREEN_TYPE_NONE
, type
);
590 #if !defined(OS_MACOSX)
591 // Do not enter fullscreen mode if disallowed by pref.
592 // TODO(bartfab): Add a test once it becomes possible to simulate a user
593 // gesture. http://crbug.com/174178
594 if (type
!= FULLSCREEN_TYPE_FORCED
) {
596 ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
598 if (!prefs
->GetBoolean(pref_names::kAppFullscreenAllowed
))
602 fullscreen_types_
|= type
;
604 fullscreen_types_
&= ~type
;
606 SetNativeWindowFullscreen();
609 bool AppWindow::IsFullscreen() const {
610 return fullscreen_types_
!= FULLSCREEN_TYPE_NONE
;
613 bool AppWindow::IsForcedFullscreen() const {
614 return (fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) != 0;
617 bool AppWindow::IsHtmlApiFullscreen() const {
618 return (fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0;
621 void AppWindow::Fullscreen() {
622 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API
, true);
625 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
627 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
629 void AppWindow::Restore() {
630 if (IsFullscreen()) {
631 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
632 SetNativeWindowFullscreen();
634 GetBaseWindow()->Restore();
638 void AppWindow::OSFullscreen() {
639 SetFullscreen(FULLSCREEN_TYPE_OS
, true);
642 void AppWindow::ForcedFullscreen() {
643 SetFullscreen(FULLSCREEN_TYPE_FORCED
, true);
646 void AppWindow::SetContentSizeConstraints(const gfx::Size
& min_size
,
647 const gfx::Size
& max_size
) {
648 SizeConstraints
constraints(min_size
, max_size
);
649 native_app_window_
->SetContentSizeConstraints(constraints
.GetMinimumSize(),
650 constraints
.GetMaximumSize());
652 gfx::Rect bounds
= GetClientBounds();
653 gfx::Size constrained_size
= constraints
.ClampSize(bounds
.size());
654 if (bounds
.size() != constrained_size
) {
655 bounds
.set_size(constrained_size
);
656 bounds
.Inset(-native_app_window_
->GetFrameInsets());
657 native_app_window_
->SetBounds(bounds
);
659 OnNativeWindowChanged();
662 void AppWindow::Show(ShowType show_type
) {
663 bool was_hidden
= is_hidden_
|| !has_been_shown_
;
666 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
667 switches::kEnableAppsShowOnFirstPaint
)) {
668 show_on_first_paint_
= true;
670 if (!first_paint_complete_
) {
671 delayed_show_type_
= show_type
;
678 GetBaseWindow()->Show();
681 GetBaseWindow()->ShowInactive();
684 AppWindowRegistry::Get(browser_context_
)->AppWindowShown(this, was_hidden
);
686 has_been_shown_
= true;
687 SendOnWindowShownIfShown();
690 void AppWindow::Hide() {
691 // This is there to prevent race conditions with Hide() being called before
692 // there was a non-empty paint. It should have no effect in a non-racy
693 // scenario where the application is hiding then showing a window: the second
694 // show will not be delayed.
696 show_on_first_paint_
= false;
697 GetBaseWindow()->Hide();
698 AppWindowRegistry::Get(browser_context_
)->AppWindowHidden(this);
701 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
702 if (cached_always_on_top_
== always_on_top
)
705 cached_always_on_top_
= always_on_top
;
707 // As a security measure, do not allow fullscreen windows or windows that
708 // overlap the taskbar to be on top. The property will be applied when the
709 // window exits fullscreen and moves away from the taskbar.
710 if (!IsFullscreen() && !IntersectsWithTaskbar())
711 native_app_window_
->SetAlwaysOnTop(always_on_top
);
713 OnNativeWindowChanged();
716 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
718 void AppWindow::SetInterceptAllKeys(bool want_all_keys
) {
719 native_app_window_
->SetInterceptAllKeys(want_all_keys
);
722 void AppWindow::WindowEventsReady() {
723 can_send_events_
= true;
724 SendOnWindowShownIfShown();
727 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
730 properties
->SetBoolean("fullscreen",
731 native_app_window_
->IsFullscreenOrPending());
732 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
733 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
734 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
735 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
736 properties
->SetBoolean(
738 requested_alpha_enabled_
&& native_app_window_
->CanHaveAlphaEnabled());
740 // These properties are undocumented and are to enable testing. Alpha is
742 // make the values easier to check.
743 SkColor transparent_white
= ~SK_ColorBLACK
;
744 properties
->SetInteger(
746 native_app_window_
->ActiveFrameColor() & transparent_white
);
747 properties
->SetInteger(
748 "inactiveFrameColor",
749 native_app_window_
->InactiveFrameColor() & transparent_white
);
751 gfx::Rect content_bounds
= GetClientBounds();
752 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
753 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
754 SetBoundsProperties(content_bounds
,
760 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
761 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
762 gfx::Size frame_min_size
= SizeConstraints::AddFrameToConstraints(
763 content_min_size
, frame_insets
);
764 gfx::Size frame_max_size
= SizeConstraints::AddFrameToConstraints(
765 content_max_size
, frame_insets
);
766 SetBoundsProperties(frame_bounds
,
773 //------------------------------------------------------------------------------
776 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
778 native_app_window_
->UpdateBadgeIcon();
781 void AppWindow::DidDownloadFavicon(
783 int http_status_code
,
784 const GURL
& image_url
,
785 const std::vector
<SkBitmap
>& bitmaps
,
786 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
787 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
792 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
793 // whose height >= the preferred size.
794 int largest_index
= 0;
795 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
796 if (bitmaps
[i
].height() < app_delegate_
->PreferredIconSize())
800 const SkBitmap
& largest
= bitmaps
[largest_index
];
801 if (image_url
== app_icon_url_
) {
802 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
806 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
809 void AppWindow::OnExtensionIconImageChanged(IconImage
* image
) {
810 DCHECK_EQ(app_icon_image_
.get(), image
);
812 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
815 void AppWindow::UpdateExtensionAppIcon() {
816 // Avoid using any previous app icons were being downloaded.
817 image_loader_ptr_factory_
.InvalidateWeakPtrs();
819 const Extension
* extension
= GetExtension();
823 gfx::ImageSkia app_default_icon
=
824 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
825 IDR_APP_DEFAULT_ICON
);
827 app_icon_image_
.reset(new IconImage(browser_context(),
829 IconsInfo::GetIcons(extension
),
830 app_delegate_
->PreferredIconSize(),
834 // Triggers actual image loading with 1x resources. The 2x resource will
835 // be handled by IconImage class when requested.
836 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
839 void AppWindow::SetNativeWindowFullscreen() {
840 native_app_window_
->SetFullscreen(fullscreen_types_
);
842 if (cached_always_on_top_
)
843 UpdateNativeAlwaysOnTop();
846 bool AppWindow::IntersectsWithTaskbar() const {
848 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
849 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
850 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
852 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
853 it
!= displays
.end();
855 gfx::Rect taskbar_bounds
= it
->bounds();
856 taskbar_bounds
.Subtract(it
->work_area());
857 if (taskbar_bounds
.IsEmpty())
860 if (window_bounds
.Intersects(taskbar_bounds
))
868 void AppWindow::UpdateNativeAlwaysOnTop() {
869 DCHECK(cached_always_on_top_
);
870 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
871 bool fullscreen
= IsFullscreen();
872 bool intersects_taskbar
= IntersectsWithTaskbar();
874 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
875 // When entering fullscreen or overlapping the taskbar, ensure windows are
876 // not always-on-top.
877 native_app_window_
->SetAlwaysOnTop(false);
878 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
879 // When exiting fullscreen and moving away from the taskbar, reinstate
881 native_app_window_
->SetAlwaysOnTop(true);
885 void AppWindow::SendOnWindowShownIfShown() {
886 if (!can_send_events_
|| !has_been_shown_
)
889 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
890 ::switches::kTestType
)) {
891 app_window_contents_
->DispatchWindowShownForTests();
895 void AppWindow::CloseContents(WebContents
* contents
) {
896 native_app_window_
->Close();
899 bool AppWindow::ShouldSuppressDialogs(WebContents
* source
) {
903 content::ColorChooser
* AppWindow::OpenColorChooser(
904 WebContents
* web_contents
,
905 SkColor initial_color
,
906 const std::vector
<content::ColorSuggestion
>& suggestions
) {
907 return app_delegate_
->ShowColorChooser(web_contents
, initial_color
);
910 void AppWindow::RunFileChooser(WebContents
* tab
,
911 const content::FileChooserParams
& params
) {
912 if (window_type_is_panel()) {
913 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
914 // dialogs to be unhosted but still close with the owning web contents.
916 LOG(WARNING
) << "File dialog opened by panel.";
920 app_delegate_
->RunFileChooser(tab
, params
);
923 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
925 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
926 native_app_window_
->SetBounds(pos
);
929 void AppWindow::NavigationStateChanged(content::WebContents
* source
,
930 content::InvalidateTypes changed_flags
) {
931 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
932 native_app_window_
->UpdateWindowTitle();
933 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
934 native_app_window_
->UpdateWindowIcon();
937 void AppWindow::EnterFullscreenModeForTab(content::WebContents
* source
,
938 const GURL
& origin
) {
939 ToggleFullscreenModeForTab(source
, true);
942 void AppWindow::ExitFullscreenModeForTab(content::WebContents
* source
) {
943 ToggleFullscreenModeForTab(source
, false);
946 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
947 bool enter_fullscreen
) {
948 const Extension
* extension
= GetExtension();
952 if (!IsExtensionWithPermissionOrSuggestInConsole(
953 APIPermission::kFullscreen
, extension
, source
->GetRenderViewHost())) {
957 SetFullscreen(FULLSCREEN_TYPE_HTML_API
, enter_fullscreen
);
960 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
962 return IsHtmlApiFullscreen();
965 void AppWindow::Observe(int type
,
966 const content::NotificationSource
& source
,
967 const content::NotificationDetails
& details
) {
969 case NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
: {
970 const Extension
* unloaded_extension
=
971 content::Details
<UnloadedExtensionInfo
>(details
)->extension
;
972 if (extension_id_
== unloaded_extension
->id())
973 native_app_window_
->Close();
976 case NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
: {
977 const Extension
* installed_extension
=
978 content::Details
<const InstalledExtensionInfo
>(details
)->extension
;
979 DCHECK(installed_extension
);
980 if (installed_extension
->id() == extension_id())
981 native_app_window_
->UpdateShelfMenu();
985 NOTREACHED() << "Received unexpected notification";
989 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
991 app_delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
994 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
995 return app_delegate_
->IsWebContentsVisible(web_contents
);
998 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
999 return native_app_window_
.get();
1002 void AppWindow::SaveWindowPosition() {
1003 if (window_key_
.empty())
1005 if (!native_app_window_
)
1008 AppWindowGeometryCache
* cache
=
1009 AppWindowGeometryCache::Get(browser_context());
1011 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
1012 gfx::Rect screen_bounds
=
1013 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
1014 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
1015 cache
->SaveGeometry(
1016 extension_id(), window_key_
, bounds
, screen_bounds
, window_state
);
1019 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1020 const gfx::Rect
& cached_bounds
,
1021 const gfx::Rect
& cached_screen_bounds
,
1022 const gfx::Rect
& current_screen_bounds
,
1023 const gfx::Size
& minimum_size
,
1024 gfx::Rect
* bounds
) const {
1025 *bounds
= cached_bounds
;
1027 // Reposition and resize the bounds if the cached_screen_bounds is different
1028 // from the current screen bounds and the current screen bounds doesn't
1029 // completely contain the bounds.
1030 if (cached_screen_bounds
!= current_screen_bounds
&&
1031 !current_screen_bounds
.Contains(cached_bounds
)) {
1033 std::max(minimum_size
.width(),
1034 std::min(bounds
->width(), current_screen_bounds
.width())));
1036 std::max(minimum_size
.height(),
1037 std::min(bounds
->height(), current_screen_bounds
.height())));
1039 std::max(current_screen_bounds
.x(),
1040 std::min(bounds
->x(),
1041 current_screen_bounds
.right() - bounds
->width())));
1043 std::max(current_screen_bounds
.y(),
1044 std::min(bounds
->y(),
1045 current_screen_bounds
.bottom() - bounds
->height())));
1049 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1051 // Ensure width and height are specified.
1052 if (params
.content_spec
.bounds
.width() == 0 &&
1053 params
.window_spec
.bounds
.width() == 0) {
1054 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1056 if (params
.content_spec
.bounds
.height() == 0 &&
1057 params
.window_spec
.bounds
.height() == 0) {
1058 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1061 // If left and top are left undefined, the native app window will center
1062 // the window on the main screen in a platform-defined manner.
1064 // Load cached state if it exists.
1065 if (!params
.window_key
.empty()) {
1066 AppWindowGeometryCache
* cache
=
1067 AppWindowGeometryCache::Get(browser_context());
1069 gfx::Rect cached_bounds
;
1070 gfx::Rect cached_screen_bounds
;
1071 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1072 if (cache
->GetGeometry(extension_id(),
1075 &cached_screen_bounds
,
1077 // App window has cached screen bounds, make sure it fits on screen in
1078 // case the screen resolution changed.
1079 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1080 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1081 gfx::Rect current_screen_bounds
= display
.work_area();
1082 SizeConstraints
constraints(params
.GetWindowMinimumSize(gfx::Insets()),
1083 params
.GetWindowMaximumSize(gfx::Insets()));
1084 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1085 cached_screen_bounds
,
1086 current_screen_bounds
,
1087 constraints
.GetMinimumSize(),
1088 ¶ms
.window_spec
.bounds
);
1089 params
.state
= cached_state
;
1091 // Since we are restoring a cached state, reset the content bounds spec to
1092 // ensure it is not used.
1093 params
.content_spec
.ResetBounds();
1101 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1102 const std::vector
<DraggableRegion
>& regions
) {
1103 SkRegion
* sk_region
= new SkRegion
;
1104 for (std::vector
<DraggableRegion
>::const_iterator iter
= regions
.begin();
1105 iter
!= regions
.end();
1107 const DraggableRegion
& region
= *iter
;
1111 region
.bounds
.right(),
1112 region
.bounds
.bottom(),
1113 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);
1118 } // namespace extensions