1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "apps/app_window.h"
11 #include "apps/app_delegate.h"
12 #include "apps/app_web_contents_helper.h"
13 #include "apps/app_window_geometry_cache.h"
14 #include "apps/app_window_registry.h"
15 #include "apps/size_constraints.h"
16 #include "apps/ui/apps_client.h"
17 #include "apps/ui/native_app_window.h"
18 #include "apps/ui/web_contents_sizer.h"
19 #include "base/command_line.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/values.h"
23 #include "chrome/browser/chrome_notification_types.h"
24 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
25 #include "chrome/browser/extensions/suggest_permission_util.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "components/web_modal/web_contents_modal_dialog_manager.h"
28 #include "content/public/browser/browser_context.h"
29 #include "content/public/browser/invalidate_type.h"
30 #include "content/public/browser/navigation_entry.h"
31 #include "content/public/browser/notification_details.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_source.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/render_view_host.h"
36 #include "content/public/browser/resource_dispatcher_host.h"
37 #include "content/public/browser/web_contents.h"
38 #include "content/public/common/content_switches.h"
39 #include "content/public/common/media_stream_request.h"
40 #include "extensions/browser/extension_registry.h"
41 #include "extensions/browser/extension_system.h"
42 #include "extensions/browser/extensions_browser_client.h"
43 #include "extensions/browser/notification_types.h"
44 #include "extensions/browser/process_manager.h"
45 #include "extensions/browser/view_type_utils.h"
46 #include "extensions/common/draggable_region.h"
47 #include "extensions/common/extension.h"
48 #include "extensions/common/manifest_handlers/icons_handler.h"
49 #include "extensions/common/permissions/permissions_data.h"
50 #include "grit/theme_resources.h"
51 #include "third_party/skia/include/core/SkRegion.h"
52 #include "ui/base/resource/resource_bundle.h"
53 #include "ui/gfx/screen.h"
55 #if !defined(OS_MACOSX)
56 #include "apps/pref_names.h"
57 #include "base/prefs/pref_service.h"
60 using content::BrowserContext
;
61 using content::ConsoleMessageLevel
;
62 using content::WebContents
;
63 using extensions::APIPermission
;
64 using web_modal::WebContentsModalDialogHost
;
65 using web_modal::WebContentsModalDialogManager
;
71 const int kDefaultWidth
= 512;
72 const int kDefaultHeight
= 384;
74 void SetConstraintProperty(const std::string
& name
,
76 base::DictionaryValue
* bounds_properties
) {
77 if (value
!= SizeConstraints::kUnboundedSize
)
78 bounds_properties
->SetInteger(name
, value
);
80 bounds_properties
->Set(name
, base::Value::CreateNullValue());
83 void SetBoundsProperties(const gfx::Rect
& bounds
,
84 const gfx::Size
& min_size
,
85 const gfx::Size
& max_size
,
86 const std::string
& bounds_name
,
87 base::DictionaryValue
* window_properties
) {
88 scoped_ptr
<base::DictionaryValue
> bounds_properties(
89 new base::DictionaryValue());
91 bounds_properties
->SetInteger("left", bounds
.x());
92 bounds_properties
->SetInteger("top", bounds
.y());
93 bounds_properties
->SetInteger("width", bounds
.width());
94 bounds_properties
->SetInteger("height", bounds
.height());
96 SetConstraintProperty("minWidth", min_size
.width(), bounds_properties
.get());
97 SetConstraintProperty(
98 "minHeight", min_size
.height(), bounds_properties
.get());
99 SetConstraintProperty("maxWidth", max_size
.width(), bounds_properties
.get());
100 SetConstraintProperty(
101 "maxHeight", max_size
.height(), bounds_properties
.get());
103 window_properties
->Set(bounds_name
, bounds_properties
.release());
106 // Combines the constraints of the content and window, and returns constraints
108 gfx::Size
GetCombinedWindowConstraints(const gfx::Size
& window_constraints
,
109 const gfx::Size
& content_constraints
,
110 const gfx::Insets
& frame_insets
) {
111 gfx::Size
combined_constraints(window_constraints
);
112 if (content_constraints
.width() > 0) {
113 combined_constraints
.set_width(
114 content_constraints
.width() + frame_insets
.width());
116 if (content_constraints
.height() > 0) {
117 combined_constraints
.set_height(
118 content_constraints
.height() + frame_insets
.height());
120 return combined_constraints
;
123 // Combines the constraints of the content and window, and returns constraints
125 gfx::Size
GetCombinedContentConstraints(const gfx::Size
& window_constraints
,
126 const gfx::Size
& content_constraints
,
127 const gfx::Insets
& frame_insets
) {
128 gfx::Size
combined_constraints(content_constraints
);
129 if (window_constraints
.width() > 0) {
130 combined_constraints
.set_width(
131 std::max(0, window_constraints
.width() - frame_insets
.width()));
133 if (window_constraints
.height() > 0) {
134 combined_constraints
.set_height(
135 std::max(0, window_constraints
.height() - frame_insets
.height()));
137 return combined_constraints
;
142 // AppWindow::BoundsSpecification
144 const int AppWindow::BoundsSpecification::kUnspecifiedPosition
= INT_MIN
;
146 AppWindow::BoundsSpecification::BoundsSpecification()
147 : bounds(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0) {}
149 AppWindow::BoundsSpecification::~BoundsSpecification() {}
151 void AppWindow::BoundsSpecification::ResetBounds() {
152 bounds
.SetRect(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0);
155 // AppWindow::CreateParams
157 AppWindow::CreateParams::CreateParams()
158 : window_type(AppWindow::WINDOW_TYPE_DEFAULT
),
159 frame(AppWindow::FRAME_CHROME
),
160 has_frame_color(false),
161 active_frame_color(SK_ColorBLACK
),
162 inactive_frame_color(SK_ColorBLACK
),
163 transparent_background(false),
164 creator_process_id(0),
165 state(ui::SHOW_STATE_DEFAULT
),
169 always_on_top(false) {}
171 AppWindow::CreateParams::~CreateParams() {}
173 gfx::Rect
AppWindow::CreateParams::GetInitialWindowBounds(
174 const gfx::Insets
& frame_insets
) const {
175 // Combine into a single window bounds.
176 gfx::Rect
combined_bounds(window_spec
.bounds
);
177 if (content_spec
.bounds
.x() != BoundsSpecification::kUnspecifiedPosition
)
178 combined_bounds
.set_x(content_spec
.bounds
.x() - frame_insets
.left());
179 if (content_spec
.bounds
.y() != BoundsSpecification::kUnspecifiedPosition
)
180 combined_bounds
.set_y(content_spec
.bounds
.y() - frame_insets
.top());
181 if (content_spec
.bounds
.width() > 0) {
182 combined_bounds
.set_width(
183 content_spec
.bounds
.width() + frame_insets
.width());
185 if (content_spec
.bounds
.height() > 0) {
186 combined_bounds
.set_height(
187 content_spec
.bounds
.height() + frame_insets
.height());
190 // Constrain the bounds.
191 SizeConstraints
constraints(
192 GetCombinedWindowConstraints(
193 window_spec
.minimum_size
, content_spec
.minimum_size
, frame_insets
),
194 GetCombinedWindowConstraints(
195 window_spec
.maximum_size
, content_spec
.maximum_size
, frame_insets
));
196 combined_bounds
.set_size(constraints
.ClampSize(combined_bounds
.size()));
198 return combined_bounds
;
201 gfx::Size
AppWindow::CreateParams::GetContentMinimumSize(
202 const gfx::Insets
& frame_insets
) const {
203 return GetCombinedContentConstraints(window_spec
.minimum_size
,
204 content_spec
.minimum_size
,
208 gfx::Size
AppWindow::CreateParams::GetContentMaximumSize(
209 const gfx::Insets
& frame_insets
) const {
210 return GetCombinedContentConstraints(window_spec
.maximum_size
,
211 content_spec
.maximum_size
,
215 gfx::Size
AppWindow::CreateParams::GetWindowMinimumSize(
216 const gfx::Insets
& frame_insets
) const {
217 return GetCombinedWindowConstraints(window_spec
.minimum_size
,
218 content_spec
.minimum_size
,
222 gfx::Size
AppWindow::CreateParams::GetWindowMaximumSize(
223 const gfx::Insets
& frame_insets
) const {
224 return GetCombinedWindowConstraints(window_spec
.maximum_size
,
225 content_spec
.maximum_size
,
231 AppWindow::AppWindow(BrowserContext
* context
,
232 AppDelegate
* app_delegate
,
233 const extensions::Extension
* extension
)
234 : browser_context_(context
),
235 extension_id_(extension
->id()),
236 window_type_(WINDOW_TYPE_DEFAULT
),
237 app_delegate_(app_delegate
),
238 image_loader_ptr_factory_(this),
239 fullscreen_types_(FULLSCREEN_TYPE_NONE
),
240 show_on_first_paint_(false),
241 first_paint_complete_(false),
242 has_been_shown_(false),
243 can_send_events_(false),
245 cached_always_on_top_(false),
246 requested_transparent_background_(false) {
247 extensions::ExtensionsBrowserClient
* client
=
248 extensions::ExtensionsBrowserClient::Get();
249 CHECK(!client
->IsGuestSession(context
) || context
->IsOffTheRecord())
250 << "Only off the record window may be opened in the guest mode.";
253 void AppWindow::Init(const GURL
& url
,
254 AppWindowContents
* app_window_contents
,
255 const CreateParams
& params
) {
256 // Initialize the render interface and web contents
257 app_window_contents_
.reset(app_window_contents
);
258 app_window_contents_
->Initialize(browser_context(), url
);
259 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
260 if (CommandLine::ForCurrentProcess()->HasSwitch(
261 switches::kEnableAppsShowOnFirstPaint
)) {
262 content::WebContentsObserver::Observe(web_contents
);
264 app_delegate_
->InitWebContents(web_contents
);
266 WebContentsModalDialogManager::CreateForWebContents(web_contents
);
267 // TODO(jamescook): Delegate out this creation.
268 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
271 web_contents
->SetDelegate(this);
272 WebContentsModalDialogManager::FromWebContents(web_contents
)
274 extensions::SetViewType(web_contents
, extensions::VIEW_TYPE_APP_WINDOW
);
276 // Initialize the window
277 CreateParams new_params
= LoadDefaults(params
);
278 window_type_
= new_params
.window_type
;
279 window_key_
= new_params
.window_key
;
281 // Windows cannot be always-on-top in fullscreen mode for security reasons.
282 cached_always_on_top_
= new_params
.always_on_top
;
283 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
284 new_params
.always_on_top
= false;
286 requested_transparent_background_
= new_params
.transparent_background
;
288 AppsClient
* apps_client
= AppsClient::Get();
289 native_app_window_
.reset(
290 apps_client
->CreateNativeAppWindow(this, new_params
));
292 helper_
.reset(new AppWebContentsHelper(
293 browser_context_
, extension_id_
, web_contents
, app_delegate_
.get()));
295 popup_manager_
.reset(
296 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
297 popup_manager_
->RegisterWith(web_contents
);
299 // Prevent the browser process from shutting down while this window exists.
300 apps_client
->IncrementKeepAliveCount();
301 UpdateExtensionAppIcon();
302 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
304 if (new_params
.hidden
) {
305 // Although the window starts hidden by default, calling Hide() here
306 // notifies observers of the window being hidden.
309 // Panels are not activated by default.
310 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
314 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
316 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
318 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
321 OnNativeWindowChanged();
323 // When the render view host is changed, the native window needs to know
324 // about it in case it has any setup to do to make the renderer appear
325 // properly. In particular, on Windows, the view's clickthrough region needs
327 extensions::ExtensionsBrowserClient
* client
=
328 extensions::ExtensionsBrowserClient::Get();
330 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
331 content::Source
<content::BrowserContext
>(
332 client
->GetOriginalContext(browser_context_
)));
333 // Close when the browser process is exiting.
335 chrome::NOTIFICATION_APP_TERMINATING
,
336 content::NotificationService::AllSources());
337 // Update the app menu if an ephemeral app becomes installed.
340 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
341 content::Source
<content::BrowserContext
>(
342 client
->GetOriginalContext(browser_context_
)));
344 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
346 if (CommandLine::ForCurrentProcess()->HasSwitch(
347 switches::kEnableAppsShowOnFirstPaint
)) {
348 // We want to show the window only when the content has been painted. For
349 // that to happen, we need to define a size for the content, otherwise the
350 // layout will happen in a 0x0 area.
351 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
352 gfx::Rect initial_bounds
= new_params
.GetInitialWindowBounds(frame_insets
);
353 initial_bounds
.Inset(frame_insets
);
354 apps::ResizeWebContents(web_contents
, initial_bounds
.size());
358 AppWindow::~AppWindow() {
359 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
361 registrar_
.RemoveAll();
363 // Remove shutdown prevention.
364 AppsClient::Get()->DecrementKeepAliveCount();
367 void AppWindow::RequestMediaAccessPermission(
368 content::WebContents
* web_contents
,
369 const content::MediaStreamRequest
& request
,
370 const content::MediaResponseCallback
& callback
) {
371 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
372 helper_
->RequestMediaAccessPermission(request
, callback
);
375 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
376 const content::OpenURLParams
& params
) {
377 DCHECK_EQ(web_contents(), source
);
378 return helper_
->OpenURLFromTab(params
);
381 void AppWindow::AddNewContents(WebContents
* source
,
382 WebContents
* new_contents
,
383 WindowOpenDisposition disposition
,
384 const gfx::Rect
& initial_pos
,
387 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
388 app_delegate_
->AddNewContents(browser_context_
,
396 bool AppWindow::PreHandleKeyboardEvent(
397 content::WebContents
* source
,
398 const content::NativeWebKeyboardEvent
& event
,
399 bool* is_keyboard_shortcut
) {
400 const extensions::Extension
* extension
= GetExtension();
404 // Here, we can handle a key event before the content gets it. When we are
405 // fullscreen and it is not forced, we want to allow the user to leave
406 // when ESC is pressed.
407 // However, if the application has the "overrideEscFullscreen" permission, we
408 // should let it override that behavior.
409 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
410 // action is not prevented.
411 // Thus, we should handle the KeyEvent here only if the permission is not set.
412 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
413 !IsForcedFullscreen() &&
414 !extension
->permissions_data()->HasAPIPermission(
415 APIPermission::kOverrideEscFullscreen
)) {
423 void AppWindow::HandleKeyboardEvent(
425 const content::NativeWebKeyboardEvent
& event
) {
426 // If the window is currently fullscreen and not forced, ESC should leave
427 // fullscreen. If this code is being called for ESC, that means that the
428 // KeyEvent's default behavior was not prevented by the content.
429 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
430 !IsForcedFullscreen()) {
435 native_app_window_
->HandleKeyboardEvent(event
);
438 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
440 bool last_unlocked_by_target
) {
441 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
442 helper_
->RequestToLockMouse();
445 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
446 const blink::WebGestureEvent
& event
) {
447 return AppWebContentsHelper::ShouldSuppressGestureEvent(event
);
450 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
451 first_paint_complete_
= true;
452 if (show_on_first_paint_
) {
453 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
454 delayed_show_type_
== SHOW_INACTIVE
);
455 Show(delayed_show_type_
);
459 void AppWindow::OnNativeClose() {
460 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
461 if (app_window_contents_
) {
462 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
463 WebContentsModalDialogManager::FromWebContents(web_contents
)
465 app_window_contents_
->NativeWindowClosed();
470 void AppWindow::OnNativeWindowChanged() {
471 SaveWindowPosition();
474 if (native_app_window_
&& cached_always_on_top_
&& !IsFullscreen() &&
475 !native_app_window_
->IsMaximized() &&
476 !native_app_window_
->IsMinimized()) {
477 UpdateNativeAlwaysOnTop();
481 if (app_window_contents_
&& native_app_window_
)
482 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
485 void AppWindow::OnNativeWindowActivated() {
486 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
489 content::WebContents
* AppWindow::web_contents() const {
490 return app_window_contents_
->GetWebContents();
493 const extensions::Extension
* AppWindow::GetExtension() const {
494 return extensions::ExtensionRegistry::Get(browser_context_
)
495 ->enabled_extensions()
496 .GetByID(extension_id_
);
499 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
501 gfx::NativeWindow
AppWindow::GetNativeWindow() {
502 return GetBaseWindow()->GetNativeWindow();
505 gfx::Rect
AppWindow::GetClientBounds() const {
506 gfx::Rect bounds
= native_app_window_
->GetBounds();
507 bounds
.Inset(native_app_window_
->GetFrameInsets());
511 base::string16
AppWindow::GetTitle() const {
512 const extensions::Extension
* extension
= GetExtension();
514 return base::string16();
516 // WebContents::GetTitle() will return the page's URL if there's no <title>
517 // specified. However, we'd prefer to show the name of the extension in that
518 // case, so we directly inspect the NavigationEntry's title.
519 base::string16 title
;
520 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
521 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
522 title
= base::UTF8ToUTF16(extension
->name());
524 title
= web_contents()->GetTitle();
526 base::RemoveChars(title
, base::ASCIIToUTF16("\n"), &title
);
530 void AppWindow::SetAppIconUrl(const GURL
& url
) {
531 // If the same url is being used for the badge, ignore it.
532 if (url
== badge_icon_url_
)
535 // Avoid using any previous icons that were being downloaded.
536 image_loader_ptr_factory_
.InvalidateWeakPtrs();
538 // Reset |app_icon_image_| to abort pending image load (if any).
539 app_icon_image_
.reset();
542 web_contents()->DownloadImage(
544 true, // is a favicon
545 0, // no maximum size
546 base::Bind(&AppWindow::DidDownloadFavicon
,
547 image_loader_ptr_factory_
.GetWeakPtr()));
550 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
551 // Avoid using any previous icons that were being downloaded.
552 image_loader_ptr_factory_
.InvalidateWeakPtrs();
554 // Reset |app_icon_image_| to abort pending image load (if any).
555 badge_icon_image_
.reset();
557 badge_icon_url_
= url
;
558 web_contents()->DownloadImage(
560 true, // is a favicon
561 0, // no maximum size
562 base::Bind(&AppWindow::DidDownloadFavicon
,
563 image_loader_ptr_factory_
.GetWeakPtr()));
566 void AppWindow::ClearBadge() {
567 badge_icon_image_
.reset();
568 badge_icon_url_
= GURL();
569 UpdateBadgeIcon(gfx::Image());
572 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
573 native_app_window_
->UpdateShape(region
.Pass());
576 void AppWindow::UpdateDraggableRegions(
577 const std::vector
<extensions::DraggableRegion
>& regions
) {
578 native_app_window_
->UpdateDraggableRegions(regions
);
581 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
585 native_app_window_
->UpdateWindowIcon();
586 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
589 void AppWindow::SetFullscreen(FullscreenType type
, bool enable
) {
590 DCHECK_NE(FULLSCREEN_TYPE_NONE
, type
);
593 #if !defined(OS_MACOSX)
594 // Do not enter fullscreen mode if disallowed by pref.
595 // TODO(bartfab): Add a test once it becomes possible to simulate a user
596 // gesture. http://crbug.com/174178
597 if (type
!= FULLSCREEN_TYPE_FORCED
) {
599 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
601 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
605 fullscreen_types_
|= type
;
607 fullscreen_types_
&= ~type
;
609 SetNativeWindowFullscreen();
612 bool AppWindow::IsFullscreen() const {
613 return fullscreen_types_
!= FULLSCREEN_TYPE_NONE
;
616 bool AppWindow::IsForcedFullscreen() const {
617 return (fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) != 0;
620 bool AppWindow::IsHtmlApiFullscreen() const {
621 return (fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0;
624 void AppWindow::Fullscreen() {
625 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API
, true);
628 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
630 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
632 void AppWindow::Restore() {
633 if (IsFullscreen()) {
634 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
635 SetNativeWindowFullscreen();
637 GetBaseWindow()->Restore();
641 void AppWindow::OSFullscreen() {
642 SetFullscreen(FULLSCREEN_TYPE_OS
, true);
645 void AppWindow::ForcedFullscreen() {
646 SetFullscreen(FULLSCREEN_TYPE_FORCED
, true);
649 void AppWindow::SetContentSizeConstraints(const gfx::Size
& min_size
,
650 const gfx::Size
& max_size
) {
651 SizeConstraints
constraints(min_size
, max_size
);
652 native_app_window_
->SetContentSizeConstraints(constraints
.GetMinimumSize(),
653 constraints
.GetMaximumSize());
655 gfx::Rect bounds
= GetClientBounds();
656 gfx::Size constrained_size
= constraints
.ClampSize(bounds
.size());
657 if (bounds
.size() != constrained_size
) {
658 bounds
.set_size(constrained_size
);
659 bounds
.Inset(-native_app_window_
->GetFrameInsets());
660 native_app_window_
->SetBounds(bounds
);
662 OnNativeWindowChanged();
665 void AppWindow::Show(ShowType show_type
) {
668 if (CommandLine::ForCurrentProcess()->HasSwitch(
669 switches::kEnableAppsShowOnFirstPaint
)) {
670 show_on_first_paint_
= true;
672 if (!first_paint_complete_
) {
673 delayed_show_type_
= show_type
;
680 GetBaseWindow()->Show();
683 GetBaseWindow()->ShowInactive();
686 AppWindowRegistry::Get(browser_context_
)->AppWindowShown(this);
688 has_been_shown_
= true;
689 SendOnWindowShownIfShown();
692 void AppWindow::Hide() {
693 // This is there to prevent race conditions with Hide() being called before
694 // there was a non-empty paint. It should have no effect in a non-racy
695 // scenario where the application is hiding then showing a window: the second
696 // show will not be delayed.
698 show_on_first_paint_
= false;
699 GetBaseWindow()->Hide();
700 AppWindowRegistry::Get(browser_context_
)->AppWindowHidden(this);
703 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
704 if (cached_always_on_top_
== always_on_top
)
707 cached_always_on_top_
= always_on_top
;
709 // As a security measure, do not allow fullscreen windows or windows that
710 // overlap the taskbar to be on top. The property will be applied when the
711 // window exits fullscreen and moves away from the taskbar.
712 if (!IsFullscreen() && !IntersectsWithTaskbar())
713 native_app_window_
->SetAlwaysOnTop(always_on_top
);
715 OnNativeWindowChanged();
718 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
720 void AppWindow::WindowEventsReady() {
721 can_send_events_
= true;
722 SendOnWindowShownIfShown();
725 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
728 properties
->SetBoolean("fullscreen",
729 native_app_window_
->IsFullscreenOrPending());
730 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
731 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
732 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
733 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
734 properties
->SetBoolean("alphaEnabled",
735 requested_transparent_background_
&&
736 native_app_window_
->CanHaveAlphaEnabled());
738 // These properties are undocumented and are to enable testing. Alpha is
740 // make the values easier to check.
741 SkColor transparent_white
= ~SK_ColorBLACK
;
742 properties
->SetInteger(
744 native_app_window_
->ActiveFrameColor() & transparent_white
);
745 properties
->SetInteger(
746 "inactiveFrameColor",
747 native_app_window_
->InactiveFrameColor() & transparent_white
);
749 gfx::Rect content_bounds
= GetClientBounds();
750 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
751 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
752 SetBoundsProperties(content_bounds
,
758 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
759 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
760 gfx::Size frame_min_size
=
761 SizeConstraints::AddFrameToConstraints(content_min_size
, frame_insets
);
762 gfx::Size frame_max_size
=
763 SizeConstraints::AddFrameToConstraints(content_max_size
, frame_insets
);
764 SetBoundsProperties(frame_bounds
,
771 //------------------------------------------------------------------------------
774 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
776 native_app_window_
->UpdateBadgeIcon();
779 void AppWindow::DidDownloadFavicon(
781 int http_status_code
,
782 const GURL
& image_url
,
783 const std::vector
<SkBitmap
>& bitmaps
,
784 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
785 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
790 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
791 // whose height >= the preferred size.
792 int largest_index
= 0;
793 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
794 if (bitmaps
[i
].height() < app_delegate_
->PreferredIconSize())
798 const SkBitmap
& largest
= bitmaps
[largest_index
];
799 if (image_url
== app_icon_url_
) {
800 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
804 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
807 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage
* image
) {
808 DCHECK_EQ(app_icon_image_
.get(), image
);
810 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
813 void AppWindow::UpdateExtensionAppIcon() {
814 // Avoid using any previous app icons were being downloaded.
815 image_loader_ptr_factory_
.InvalidateWeakPtrs();
817 const gfx::ImageSkia
& default_icon
=
818 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
819 IDR_APP_DEFAULT_ICON
);
821 const extensions::Extension
* extension
= GetExtension();
825 app_icon_image_
.reset(
826 new extensions::IconImage(browser_context(),
828 extensions::IconsInfo::GetIcons(extension
),
829 app_delegate_
->PreferredIconSize(),
833 // Triggers actual image loading with 1x resources. The 2x resource will
834 // be handled by IconImage class when requested.
835 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
838 void AppWindow::SetNativeWindowFullscreen() {
839 native_app_window_
->SetFullscreen(fullscreen_types_
);
841 if (cached_always_on_top_
)
842 UpdateNativeAlwaysOnTop();
845 bool AppWindow::IntersectsWithTaskbar() const {
847 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
848 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
849 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
851 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
852 it
!= displays
.end();
854 gfx::Rect taskbar_bounds
= it
->bounds();
855 taskbar_bounds
.Subtract(it
->work_area());
856 if (taskbar_bounds
.IsEmpty())
859 if (window_bounds
.Intersects(taskbar_bounds
))
867 void AppWindow::UpdateNativeAlwaysOnTop() {
868 DCHECK(cached_always_on_top_
);
869 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
870 bool fullscreen
= IsFullscreen();
871 bool intersects_taskbar
= IntersectsWithTaskbar();
873 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
874 // When entering fullscreen or overlapping the taskbar, ensure windows are
875 // not always-on-top.
876 native_app_window_
->SetAlwaysOnTop(false);
877 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
878 // When exiting fullscreen and moving away from the taskbar, reinstate
880 native_app_window_
->SetAlwaysOnTop(true);
884 void AppWindow::SendOnWindowShownIfShown() {
885 if (!can_send_events_
|| !has_been_shown_
)
888 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType
)) {
889 app_window_contents_
->DispatchWindowShownForTests();
893 void AppWindow::CloseContents(WebContents
* contents
) {
894 native_app_window_
->Close();
897 bool AppWindow::ShouldSuppressDialogs() { return true; }
899 content::ColorChooser
* AppWindow::OpenColorChooser(
900 WebContents
* web_contents
,
901 SkColor initial_color
,
902 const std::vector
<content::ColorSuggestion
>& suggestions
) {
903 return app_delegate_
->ShowColorChooser(web_contents
, initial_color
);
906 void AppWindow::RunFileChooser(WebContents
* tab
,
907 const content::FileChooserParams
& params
) {
908 if (window_type_is_panel()) {
909 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
910 // dialogs to be unhosted but still close with the owning web contents.
912 LOG(WARNING
) << "File dialog opened by panel.";
916 app_delegate_
->RunFileChooser(tab
, params
);
919 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
921 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
922 native_app_window_
->SetBounds(pos
);
925 void AppWindow::NavigationStateChanged(const content::WebContents
* source
,
926 unsigned changed_flags
) {
927 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
928 native_app_window_
->UpdateWindowTitle();
929 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
930 native_app_window_
->UpdateWindowIcon();
933 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
934 bool enter_fullscreen
) {
935 const extensions::Extension
* extension
= GetExtension();
939 if (!IsExtensionWithPermissionOrSuggestInConsole(
940 APIPermission::kFullscreen
, extension
, source
->GetRenderViewHost())) {
944 SetFullscreen(FULLSCREEN_TYPE_HTML_API
, enter_fullscreen
);
947 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
949 return IsHtmlApiFullscreen();
952 void AppWindow::Observe(int type
,
953 const content::NotificationSource
& source
,
954 const content::NotificationDetails
& details
) {
956 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
: {
957 const extensions::Extension
* unloaded_extension
=
958 content::Details
<extensions::UnloadedExtensionInfo
>(details
)
960 if (extension_id_
== unloaded_extension
->id())
961 native_app_window_
->Close();
964 case extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
: {
965 const extensions::Extension
* installed_extension
=
966 content::Details
<const extensions::InstalledExtensionInfo
>(details
)
968 DCHECK(installed_extension
);
969 if (installed_extension
->id() == extension_id())
970 native_app_window_
->UpdateShelfMenu();
973 case chrome::NOTIFICATION_APP_TERMINATING
:
974 native_app_window_
->Close();
977 NOTREACHED() << "Received unexpected notification";
981 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
983 app_delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
986 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
987 return app_delegate_
->IsWebContentsVisible(web_contents
);
990 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
991 return native_app_window_
.get();
994 void AppWindow::SaveWindowPosition() {
995 if (window_key_
.empty())
997 if (!native_app_window_
)
1000 AppWindowGeometryCache
* cache
=
1001 AppWindowGeometryCache::Get(browser_context());
1003 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
1004 gfx::Rect screen_bounds
=
1005 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
1006 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
1007 cache
->SaveGeometry(
1008 extension_id(), window_key_
, bounds
, screen_bounds
, window_state
);
1011 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1012 const gfx::Rect
& cached_bounds
,
1013 const gfx::Rect
& cached_screen_bounds
,
1014 const gfx::Rect
& current_screen_bounds
,
1015 const gfx::Size
& minimum_size
,
1016 gfx::Rect
* bounds
) const {
1017 *bounds
= cached_bounds
;
1019 // Reposition and resize the bounds if the cached_screen_bounds is different
1020 // from the current screen bounds and the current screen bounds doesn't
1021 // completely contain the bounds.
1022 if (cached_screen_bounds
!= current_screen_bounds
&&
1023 !current_screen_bounds
.Contains(cached_bounds
)) {
1025 std::max(minimum_size
.width(),
1026 std::min(bounds
->width(), current_screen_bounds
.width())));
1028 std::max(minimum_size
.height(),
1029 std::min(bounds
->height(), current_screen_bounds
.height())));
1031 std::max(current_screen_bounds
.x(),
1032 std::min(bounds
->x(),
1033 current_screen_bounds
.right() - bounds
->width())));
1035 std::max(current_screen_bounds
.y(),
1036 std::min(bounds
->y(),
1037 current_screen_bounds
.bottom() - bounds
->height())));
1041 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1043 // Ensure width and height are specified.
1044 if (params
.content_spec
.bounds
.width() == 0 &&
1045 params
.window_spec
.bounds
.width() == 0) {
1046 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1048 if (params
.content_spec
.bounds
.height() == 0 &&
1049 params
.window_spec
.bounds
.height() == 0) {
1050 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1053 // If left and top are left undefined, the native app window will center
1054 // the window on the main screen in a platform-defined manner.
1056 // Load cached state if it exists.
1057 if (!params
.window_key
.empty()) {
1058 AppWindowGeometryCache
* cache
=
1059 AppWindowGeometryCache::Get(browser_context());
1061 gfx::Rect cached_bounds
;
1062 gfx::Rect cached_screen_bounds
;
1063 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1064 if (cache
->GetGeometry(extension_id(),
1067 &cached_screen_bounds
,
1069 // App window has cached screen bounds, make sure it fits on screen in
1070 // case the screen resolution changed.
1071 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1072 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1073 gfx::Rect current_screen_bounds
= display
.work_area();
1074 SizeConstraints
constraints(params
.GetWindowMinimumSize(gfx::Insets()),
1075 params
.GetWindowMaximumSize(gfx::Insets()));
1076 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1077 cached_screen_bounds
,
1078 current_screen_bounds
,
1079 constraints
.GetMinimumSize(),
1080 ¶ms
.window_spec
.bounds
);
1081 params
.state
= cached_state
;
1083 // Since we are restoring a cached state, reset the content bounds spec to
1084 // ensure it is not used.
1085 params
.content_spec
.ResetBounds();
1093 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1094 const std::vector
<extensions::DraggableRegion
>& regions
) {
1095 SkRegion
* sk_region
= new SkRegion
;
1096 for (std::vector
<extensions::DraggableRegion
>::const_iterator iter
=
1098 iter
!= regions
.end();
1100 const extensions::DraggableRegion
& region
= *iter
;
1104 region
.bounds
.right(),
1105 region
.bounds
.bottom(),
1106 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);