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_window_registry.h"
12 #include "apps/ui/apps_client.h"
13 #include "base/command_line.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/utf_string_conversions.h"
16 #include "base/values.h"
17 #include "components/web_modal/web_contents_modal_dialog_manager.h"
18 #include "content/public/browser/browser_context.h"
19 #include "content/public/browser/invalidate_type.h"
20 #include "content/public/browser/navigation_entry.h"
21 #include "content/public/browser/notification_details.h"
22 #include "content/public/browser/notification_service.h"
23 #include "content/public/browser/notification_source.h"
24 #include "content/public/browser/notification_types.h"
25 #include "content/public/browser/render_view_host.h"
26 #include "content/public/browser/resource_dispatcher_host.h"
27 #include "content/public/browser/web_contents.h"
28 #include "content/public/common/content_switches.h"
29 #include "content/public/common/media_stream_request.h"
30 #include "extensions/browser/app_window/app_delegate.h"
31 #include "extensions/browser/app_window/app_web_contents_helper.h"
32 #include "extensions/browser/app_window/app_window_geometry_cache.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 "third_party/skia/include/core/SkRegion.h"
48 #include "ui/gfx/screen.h"
50 #if !defined(OS_MACOSX)
51 #include "base/prefs/pref_service.h"
52 #include "extensions/browser/pref_names.h"
55 using content::BrowserContext
;
56 using content::ConsoleMessageLevel
;
57 using content::WebContents
;
58 using extensions::APIPermission
;
59 using extensions::NativeAppWindow
;
60 using web_modal::WebContentsModalDialogHost
;
61 using web_modal::WebContentsModalDialogManager
;
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
!= extensions::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 creator_process_id(0),
161 state(ui::SHOW_STATE_DEFAULT
),
165 always_on_top(false) {
168 AppWindow::CreateParams::~CreateParams() {}
170 gfx::Rect
AppWindow::CreateParams::GetInitialWindowBounds(
171 const gfx::Insets
& frame_insets
) const {
172 // Combine into a single window bounds.
173 gfx::Rect
combined_bounds(window_spec
.bounds
);
174 if (content_spec
.bounds
.x() != BoundsSpecification::kUnspecifiedPosition
)
175 combined_bounds
.set_x(content_spec
.bounds
.x() - frame_insets
.left());
176 if (content_spec
.bounds
.y() != BoundsSpecification::kUnspecifiedPosition
)
177 combined_bounds
.set_y(content_spec
.bounds
.y() - frame_insets
.top());
178 if (content_spec
.bounds
.width() > 0) {
179 combined_bounds
.set_width(
180 content_spec
.bounds
.width() + frame_insets
.width());
182 if (content_spec
.bounds
.height() > 0) {
183 combined_bounds
.set_height(
184 content_spec
.bounds
.height() + frame_insets
.height());
187 // Constrain the bounds.
188 extensions::SizeConstraints
constraints(
189 GetCombinedWindowConstraints(
190 window_spec
.minimum_size
, content_spec
.minimum_size
, frame_insets
),
191 GetCombinedWindowConstraints(
192 window_spec
.maximum_size
, content_spec
.maximum_size
, frame_insets
));
193 combined_bounds
.set_size(constraints
.ClampSize(combined_bounds
.size()));
195 return combined_bounds
;
198 gfx::Size
AppWindow::CreateParams::GetContentMinimumSize(
199 const gfx::Insets
& frame_insets
) const {
200 return GetCombinedContentConstraints(window_spec
.minimum_size
,
201 content_spec
.minimum_size
,
205 gfx::Size
AppWindow::CreateParams::GetContentMaximumSize(
206 const gfx::Insets
& frame_insets
) const {
207 return GetCombinedContentConstraints(window_spec
.maximum_size
,
208 content_spec
.maximum_size
,
212 gfx::Size
AppWindow::CreateParams::GetWindowMinimumSize(
213 const gfx::Insets
& frame_insets
) const {
214 return GetCombinedWindowConstraints(window_spec
.minimum_size
,
215 content_spec
.minimum_size
,
219 gfx::Size
AppWindow::CreateParams::GetWindowMaximumSize(
220 const gfx::Insets
& frame_insets
) const {
221 return GetCombinedWindowConstraints(window_spec
.maximum_size
,
222 content_spec
.maximum_size
,
228 AppWindow::AppWindow(BrowserContext
* context
,
229 extensions::AppDelegate
* app_delegate
,
230 const extensions::Extension
* extension
)
231 : browser_context_(context
),
232 extension_id_(extension
->id()),
233 window_type_(WINDOW_TYPE_DEFAULT
),
234 app_delegate_(app_delegate
),
235 image_loader_ptr_factory_(this),
236 fullscreen_types_(FULLSCREEN_TYPE_NONE
),
237 show_on_first_paint_(false),
238 first_paint_complete_(false),
239 has_been_shown_(false),
240 can_send_events_(false),
242 cached_always_on_top_(false),
243 requested_alpha_enabled_(false) {
244 extensions::ExtensionsBrowserClient
* client
=
245 extensions::ExtensionsBrowserClient::Get();
246 CHECK(!client
->IsGuestSession(context
) || context
->IsOffTheRecord())
247 << "Only off the record window may be opened in the guest mode.";
250 void AppWindow::Init(const GURL
& url
,
251 AppWindowContents
* app_window_contents
,
252 const CreateParams
& params
) {
253 // Initialize the render interface and web contents
254 app_window_contents_
.reset(app_window_contents
);
255 app_window_contents_
->Initialize(browser_context(), url
);
256 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
257 if (CommandLine::ForCurrentProcess()->HasSwitch(
258 extensions::switches::kEnableAppsShowOnFirstPaint
)) {
259 content::WebContentsObserver::Observe(web_contents
);
261 app_delegate_
->InitWebContents(web_contents
);
263 WebContentsModalDialogManager::CreateForWebContents(web_contents
);
265 web_contents
->SetDelegate(this);
266 WebContentsModalDialogManager::FromWebContents(web_contents
)
268 extensions::SetViewType(web_contents
, extensions::VIEW_TYPE_APP_WINDOW
);
270 // Initialize the window
271 CreateParams new_params
= LoadDefaults(params
);
272 window_type_
= new_params
.window_type
;
273 window_key_
= new_params
.window_key
;
275 // Windows cannot be always-on-top in fullscreen mode for security reasons.
276 cached_always_on_top_
= new_params
.always_on_top
;
277 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
278 new_params
.always_on_top
= false;
280 requested_alpha_enabled_
= new_params
.alpha_enabled
;
282 AppsClient
* apps_client
= AppsClient::Get();
283 native_app_window_
.reset(
284 apps_client
->CreateNativeAppWindow(this, new_params
));
286 helper_
.reset(new extensions::AppWebContentsHelper(
287 browser_context_
, extension_id_
, web_contents
, app_delegate_
.get()));
289 popup_manager_
.reset(
290 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
291 popup_manager_
->RegisterWith(web_contents
);
293 // Prevent the browser process from shutting down while this window exists.
294 apps_client
->IncrementKeepAliveCount();
295 UpdateExtensionAppIcon();
296 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
298 if (new_params
.hidden
) {
299 // Although the window starts hidden by default, calling Hide() here
300 // notifies observers of the window being hidden.
303 // Panels are not activated by default.
304 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
308 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
310 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
312 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
315 OnNativeWindowChanged();
317 // When the render view host is changed, the native window needs to know
318 // about it in case it has any setup to do to make the renderer appear
319 // properly. In particular, on Windows, the view's clickthrough region needs
321 extensions::ExtensionsBrowserClient
* client
=
322 extensions::ExtensionsBrowserClient::Get();
324 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
325 content::Source
<content::BrowserContext
>(
326 client
->GetOriginalContext(browser_context_
)));
327 // Update the app menu if an ephemeral app becomes installed.
330 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
331 content::Source
<content::BrowserContext
>(
332 client
->GetOriginalContext(browser_context_
)));
334 // Close when the browser process is exiting.
335 app_delegate_
->SetTerminatingCallback(
336 base::Bind(&NativeAppWindow::Close
,
337 base::Unretained(native_app_window_
.get())));
339 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
341 if (CommandLine::ForCurrentProcess()->HasSwitch(
342 extensions::switches::kEnableAppsShowOnFirstPaint
)) {
343 // We want to show the window only when the content has been painted. For
344 // that to happen, we need to define a size for the content, otherwise the
345 // layout will happen in a 0x0 area.
346 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
347 gfx::Rect initial_bounds
= new_params
.GetInitialWindowBounds(frame_insets
);
348 initial_bounds
.Inset(frame_insets
);
349 app_delegate_
->ResizeWebContents(web_contents
, initial_bounds
.size());
353 AppWindow::~AppWindow() {
354 // Unregister now to prevent getting notified if we're the last window open.
355 app_delegate_
->SetTerminatingCallback(base::Closure());
357 // Remove shutdown prevention.
358 AppsClient::Get()->DecrementKeepAliveCount();
361 void AppWindow::RequestMediaAccessPermission(
362 content::WebContents
* web_contents
,
363 const content::MediaStreamRequest
& request
,
364 const content::MediaResponseCallback
& callback
) {
365 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
366 helper_
->RequestMediaAccessPermission(request
, callback
);
369 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
370 const content::OpenURLParams
& params
) {
371 DCHECK_EQ(web_contents(), source
);
372 return helper_
->OpenURLFromTab(params
);
375 void AppWindow::AddNewContents(WebContents
* source
,
376 WebContents
* new_contents
,
377 WindowOpenDisposition disposition
,
378 const gfx::Rect
& initial_pos
,
381 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
382 app_delegate_
->AddNewContents(browser_context_
,
390 bool AppWindow::PreHandleKeyboardEvent(
391 content::WebContents
* source
,
392 const content::NativeWebKeyboardEvent
& event
,
393 bool* is_keyboard_shortcut
) {
394 const extensions::Extension
* extension
= GetExtension();
398 // Here, we can handle a key event before the content gets it. When we are
399 // fullscreen and it is not forced, we want to allow the user to leave
400 // when ESC is pressed.
401 // However, if the application has the "overrideEscFullscreen" permission, we
402 // should let it override that behavior.
403 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
404 // action is not prevented.
405 // Thus, we should handle the KeyEvent here only if the permission is not set.
406 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
407 !IsForcedFullscreen() &&
408 !extension
->permissions_data()->HasAPIPermission(
409 APIPermission::kOverrideEscFullscreen
)) {
417 void AppWindow::HandleKeyboardEvent(
419 const content::NativeWebKeyboardEvent
& event
) {
420 // If the window is currently fullscreen and not forced, ESC should leave
421 // fullscreen. If this code is being called for ESC, that means that the
422 // KeyEvent's default behavior was not prevented by the content.
423 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&& IsFullscreen() &&
424 !IsForcedFullscreen()) {
429 native_app_window_
->HandleKeyboardEvent(event
);
432 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
434 bool last_unlocked_by_target
) {
435 DCHECK_EQ(AppWindow::web_contents(), web_contents
);
436 helper_
->RequestToLockMouse();
439 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
440 const blink::WebGestureEvent
& event
) {
441 return extensions::AppWebContentsHelper::ShouldSuppressGestureEvent(event
);
444 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
445 first_paint_complete_
= true;
446 if (show_on_first_paint_
) {
447 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
448 delayed_show_type_
== SHOW_INACTIVE
);
449 Show(delayed_show_type_
);
453 void AppWindow::OnNativeClose() {
454 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
455 if (app_window_contents_
) {
456 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
457 WebContentsModalDialogManager::FromWebContents(web_contents
)
459 app_window_contents_
->NativeWindowClosed();
464 void AppWindow::OnNativeWindowChanged() {
465 SaveWindowPosition();
468 if (native_app_window_
&& cached_always_on_top_
&& !IsFullscreen() &&
469 !native_app_window_
->IsMaximized() &&
470 !native_app_window_
->IsMinimized()) {
471 UpdateNativeAlwaysOnTop();
475 if (app_window_contents_
&& native_app_window_
)
476 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
479 void AppWindow::OnNativeWindowActivated() {
480 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
483 content::WebContents
* AppWindow::web_contents() const {
484 return app_window_contents_
->GetWebContents();
487 const extensions::Extension
* AppWindow::GetExtension() const {
488 return extensions::ExtensionRegistry::Get(browser_context_
)
489 ->enabled_extensions()
490 .GetByID(extension_id_
);
493 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
495 gfx::NativeWindow
AppWindow::GetNativeWindow() {
496 return GetBaseWindow()->GetNativeWindow();
499 gfx::Rect
AppWindow::GetClientBounds() const {
500 gfx::Rect bounds
= native_app_window_
->GetBounds();
501 bounds
.Inset(native_app_window_
->GetFrameInsets());
505 base::string16
AppWindow::GetTitle() const {
506 const extensions::Extension
* extension
= GetExtension();
508 return base::string16();
510 // WebContents::GetTitle() will return the page's URL if there's no <title>
511 // specified. However, we'd prefer to show the name of the extension in that
512 // case, so we directly inspect the NavigationEntry's title.
513 base::string16 title
;
514 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
515 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
516 title
= base::UTF8ToUTF16(extension
->name());
518 title
= web_contents()->GetTitle();
520 base::RemoveChars(title
, base::ASCIIToUTF16("\n"), &title
);
524 void AppWindow::SetAppIconUrl(const GURL
& url
) {
525 // If the same url is being used for the badge, ignore it.
526 if (url
== badge_icon_url_
)
529 // Avoid using any previous icons that were being downloaded.
530 image_loader_ptr_factory_
.InvalidateWeakPtrs();
532 // Reset |app_icon_image_| to abort pending image load (if any).
533 app_icon_image_
.reset();
536 web_contents()->DownloadImage(
538 true, // is a favicon
539 0, // no maximum size
540 base::Bind(&AppWindow::DidDownloadFavicon
,
541 image_loader_ptr_factory_
.GetWeakPtr()));
544 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
545 // Avoid using any previous icons that were being downloaded.
546 image_loader_ptr_factory_
.InvalidateWeakPtrs();
548 // Reset |app_icon_image_| to abort pending image load (if any).
549 badge_icon_image_
.reset();
551 badge_icon_url_
= url
;
552 web_contents()->DownloadImage(
554 true, // is a favicon
555 0, // no maximum size
556 base::Bind(&AppWindow::DidDownloadFavicon
,
557 image_loader_ptr_factory_
.GetWeakPtr()));
560 void AppWindow::ClearBadge() {
561 badge_icon_image_
.reset();
562 badge_icon_url_
= GURL();
563 UpdateBadgeIcon(gfx::Image());
566 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
567 native_app_window_
->UpdateShape(region
.Pass());
570 void AppWindow::UpdateDraggableRegions(
571 const std::vector
<extensions::DraggableRegion
>& regions
) {
572 native_app_window_
->UpdateDraggableRegions(regions
);
575 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
579 native_app_window_
->UpdateWindowIcon();
580 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
583 void AppWindow::SetFullscreen(FullscreenType type
, bool enable
) {
584 DCHECK_NE(FULLSCREEN_TYPE_NONE
, type
);
587 #if !defined(OS_MACOSX)
588 // Do not enter fullscreen mode if disallowed by pref.
589 // TODO(bartfab): Add a test once it becomes possible to simulate a user
590 // gesture. http://crbug.com/174178
591 if (type
!= FULLSCREEN_TYPE_FORCED
) {
593 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
595 if (!prefs
->GetBoolean(extensions::pref_names::kAppFullscreenAllowed
))
599 fullscreen_types_
|= type
;
601 fullscreen_types_
&= ~type
;
603 SetNativeWindowFullscreen();
606 bool AppWindow::IsFullscreen() const {
607 return fullscreen_types_
!= FULLSCREEN_TYPE_NONE
;
610 bool AppWindow::IsForcedFullscreen() const {
611 return (fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) != 0;
614 bool AppWindow::IsHtmlApiFullscreen() const {
615 return (fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0;
618 void AppWindow::Fullscreen() {
619 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API
, true);
622 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
624 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
626 void AppWindow::Restore() {
627 if (IsFullscreen()) {
628 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
629 SetNativeWindowFullscreen();
631 GetBaseWindow()->Restore();
635 void AppWindow::OSFullscreen() {
636 SetFullscreen(FULLSCREEN_TYPE_OS
, true);
639 void AppWindow::ForcedFullscreen() {
640 SetFullscreen(FULLSCREEN_TYPE_FORCED
, true);
643 void AppWindow::SetContentSizeConstraints(const gfx::Size
& min_size
,
644 const gfx::Size
& max_size
) {
645 extensions::SizeConstraints
constraints(min_size
, max_size
);
646 native_app_window_
->SetContentSizeConstraints(constraints
.GetMinimumSize(),
647 constraints
.GetMaximumSize());
649 gfx::Rect bounds
= GetClientBounds();
650 gfx::Size constrained_size
= constraints
.ClampSize(bounds
.size());
651 if (bounds
.size() != constrained_size
) {
652 bounds
.set_size(constrained_size
);
653 bounds
.Inset(-native_app_window_
->GetFrameInsets());
654 native_app_window_
->SetBounds(bounds
);
656 OnNativeWindowChanged();
659 void AppWindow::Show(ShowType show_type
) {
662 if (CommandLine::ForCurrentProcess()->HasSwitch(
663 extensions::switches::kEnableAppsShowOnFirstPaint
)) {
664 show_on_first_paint_
= true;
666 if (!first_paint_complete_
) {
667 delayed_show_type_
= show_type
;
674 GetBaseWindow()->Show();
677 GetBaseWindow()->ShowInactive();
680 AppWindowRegistry::Get(browser_context_
)->AppWindowShown(this);
682 has_been_shown_
= true;
683 SendOnWindowShownIfShown();
686 void AppWindow::Hide() {
687 // This is there to prevent race conditions with Hide() being called before
688 // there was a non-empty paint. It should have no effect in a non-racy
689 // scenario where the application is hiding then showing a window: the second
690 // show will not be delayed.
692 show_on_first_paint_
= false;
693 GetBaseWindow()->Hide();
694 AppWindowRegistry::Get(browser_context_
)->AppWindowHidden(this);
697 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
698 if (cached_always_on_top_
== always_on_top
)
701 cached_always_on_top_
= always_on_top
;
703 // As a security measure, do not allow fullscreen windows or windows that
704 // overlap the taskbar to be on top. The property will be applied when the
705 // window exits fullscreen and moves away from the taskbar.
706 if (!IsFullscreen() && !IntersectsWithTaskbar())
707 native_app_window_
->SetAlwaysOnTop(always_on_top
);
709 OnNativeWindowChanged();
712 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
714 void AppWindow::WindowEventsReady() {
715 can_send_events_
= true;
716 SendOnWindowShownIfShown();
719 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
722 properties
->SetBoolean("fullscreen",
723 native_app_window_
->IsFullscreenOrPending());
724 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
725 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
726 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
727 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
728 properties
->SetBoolean(
730 requested_alpha_enabled_
&& native_app_window_
->CanHaveAlphaEnabled());
732 // These properties are undocumented and are to enable testing. Alpha is
734 // make the values easier to check.
735 SkColor transparent_white
= ~SK_ColorBLACK
;
736 properties
->SetInteger(
738 native_app_window_
->ActiveFrameColor() & transparent_white
);
739 properties
->SetInteger(
740 "inactiveFrameColor",
741 native_app_window_
->InactiveFrameColor() & transparent_white
);
743 gfx::Rect content_bounds
= GetClientBounds();
744 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
745 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
746 SetBoundsProperties(content_bounds
,
752 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
753 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
754 gfx::Size frame_min_size
= extensions::SizeConstraints::AddFrameToConstraints(
755 content_min_size
, frame_insets
);
756 gfx::Size frame_max_size
= extensions::SizeConstraints::AddFrameToConstraints(
757 content_max_size
, frame_insets
);
758 SetBoundsProperties(frame_bounds
,
765 //------------------------------------------------------------------------------
768 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
770 native_app_window_
->UpdateBadgeIcon();
773 void AppWindow::DidDownloadFavicon(
775 int http_status_code
,
776 const GURL
& image_url
,
777 const std::vector
<SkBitmap
>& bitmaps
,
778 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
779 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
784 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
785 // whose height >= the preferred size.
786 int largest_index
= 0;
787 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
788 if (bitmaps
[i
].height() < app_delegate_
->PreferredIconSize())
792 const SkBitmap
& largest
= bitmaps
[largest_index
];
793 if (image_url
== app_icon_url_
) {
794 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
798 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
801 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage
* image
) {
802 DCHECK_EQ(app_icon_image_
.get(), image
);
804 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
807 void AppWindow::UpdateExtensionAppIcon() {
808 // Avoid using any previous app icons were being downloaded.
809 image_loader_ptr_factory_
.InvalidateWeakPtrs();
811 const extensions::Extension
* extension
= GetExtension();
815 app_icon_image_
.reset(
816 new extensions::IconImage(browser_context(),
818 extensions::IconsInfo::GetIcons(extension
),
819 app_delegate_
->PreferredIconSize(),
820 app_delegate_
->GetAppDefaultIcon(),
823 // Triggers actual image loading with 1x resources. The 2x resource will
824 // be handled by IconImage class when requested.
825 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
828 void AppWindow::SetNativeWindowFullscreen() {
829 native_app_window_
->SetFullscreen(fullscreen_types_
);
831 if (cached_always_on_top_
)
832 UpdateNativeAlwaysOnTop();
835 bool AppWindow::IntersectsWithTaskbar() const {
837 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
838 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
839 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
841 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
842 it
!= displays
.end();
844 gfx::Rect taskbar_bounds
= it
->bounds();
845 taskbar_bounds
.Subtract(it
->work_area());
846 if (taskbar_bounds
.IsEmpty())
849 if (window_bounds
.Intersects(taskbar_bounds
))
857 void AppWindow::UpdateNativeAlwaysOnTop() {
858 DCHECK(cached_always_on_top_
);
859 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
860 bool fullscreen
= IsFullscreen();
861 bool intersects_taskbar
= IntersectsWithTaskbar();
863 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
864 // When entering fullscreen or overlapping the taskbar, ensure windows are
865 // not always-on-top.
866 native_app_window_
->SetAlwaysOnTop(false);
867 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
868 // When exiting fullscreen and moving away from the taskbar, reinstate
870 native_app_window_
->SetAlwaysOnTop(true);
874 void AppWindow::SendOnWindowShownIfShown() {
875 if (!can_send_events_
|| !has_been_shown_
)
878 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType
)) {
879 app_window_contents_
->DispatchWindowShownForTests();
883 void AppWindow::CloseContents(WebContents
* contents
) {
884 native_app_window_
->Close();
887 bool AppWindow::ShouldSuppressDialogs() { return true; }
889 content::ColorChooser
* AppWindow::OpenColorChooser(
890 WebContents
* web_contents
,
891 SkColor initial_color
,
892 const std::vector
<content::ColorSuggestion
>& suggestions
) {
893 return app_delegate_
->ShowColorChooser(web_contents
, initial_color
);
896 void AppWindow::RunFileChooser(WebContents
* tab
,
897 const content::FileChooserParams
& params
) {
898 if (window_type_is_panel()) {
899 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
900 // dialogs to be unhosted but still close with the owning web contents.
902 LOG(WARNING
) << "File dialog opened by panel.";
906 app_delegate_
->RunFileChooser(tab
, params
);
909 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
911 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
912 native_app_window_
->SetBounds(pos
);
915 void AppWindow::NavigationStateChanged(const content::WebContents
* source
,
916 content::InvalidateTypes changed_flags
) {
917 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
918 native_app_window_
->UpdateWindowTitle();
919 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
920 native_app_window_
->UpdateWindowIcon();
923 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
924 bool enter_fullscreen
) {
925 const extensions::Extension
* extension
= GetExtension();
929 if (!IsExtensionWithPermissionOrSuggestInConsole(
930 APIPermission::kFullscreen
, extension
, source
->GetRenderViewHost())) {
934 SetFullscreen(FULLSCREEN_TYPE_HTML_API
, enter_fullscreen
);
937 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
939 return IsHtmlApiFullscreen();
942 void AppWindow::Observe(int type
,
943 const content::NotificationSource
& source
,
944 const content::NotificationDetails
& details
) {
946 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
: {
947 const extensions::Extension
* unloaded_extension
=
948 content::Details
<extensions::UnloadedExtensionInfo
>(details
)
950 if (extension_id_
== unloaded_extension
->id())
951 native_app_window_
->Close();
954 case extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
: {
955 const extensions::Extension
* installed_extension
=
956 content::Details
<const extensions::InstalledExtensionInfo
>(details
)
958 DCHECK(installed_extension
);
959 if (installed_extension
->id() == extension_id())
960 native_app_window_
->UpdateShelfMenu();
964 NOTREACHED() << "Received unexpected notification";
968 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
970 app_delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
973 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
974 return app_delegate_
->IsWebContentsVisible(web_contents
);
977 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
978 return native_app_window_
.get();
981 void AppWindow::SaveWindowPosition() {
982 if (window_key_
.empty())
984 if (!native_app_window_
)
987 extensions::AppWindowGeometryCache
* cache
=
988 extensions::AppWindowGeometryCache::Get(browser_context());
990 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
991 gfx::Rect screen_bounds
=
992 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
993 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
995 extension_id(), window_key_
, bounds
, screen_bounds
, window_state
);
998 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
999 const gfx::Rect
& cached_bounds
,
1000 const gfx::Rect
& cached_screen_bounds
,
1001 const gfx::Rect
& current_screen_bounds
,
1002 const gfx::Size
& minimum_size
,
1003 gfx::Rect
* bounds
) const {
1004 *bounds
= cached_bounds
;
1006 // Reposition and resize the bounds if the cached_screen_bounds is different
1007 // from the current screen bounds and the current screen bounds doesn't
1008 // completely contain the bounds.
1009 if (cached_screen_bounds
!= current_screen_bounds
&&
1010 !current_screen_bounds
.Contains(cached_bounds
)) {
1012 std::max(minimum_size
.width(),
1013 std::min(bounds
->width(), current_screen_bounds
.width())));
1015 std::max(minimum_size
.height(),
1016 std::min(bounds
->height(), current_screen_bounds
.height())));
1018 std::max(current_screen_bounds
.x(),
1019 std::min(bounds
->x(),
1020 current_screen_bounds
.right() - bounds
->width())));
1022 std::max(current_screen_bounds
.y(),
1023 std::min(bounds
->y(),
1024 current_screen_bounds
.bottom() - bounds
->height())));
1028 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1030 // Ensure width and height are specified.
1031 if (params
.content_spec
.bounds
.width() == 0 &&
1032 params
.window_spec
.bounds
.width() == 0) {
1033 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1035 if (params
.content_spec
.bounds
.height() == 0 &&
1036 params
.window_spec
.bounds
.height() == 0) {
1037 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1040 // If left and top are left undefined, the native app window will center
1041 // the window on the main screen in a platform-defined manner.
1043 // Load cached state if it exists.
1044 if (!params
.window_key
.empty()) {
1045 extensions::AppWindowGeometryCache
* cache
=
1046 extensions::AppWindowGeometryCache::Get(browser_context());
1048 gfx::Rect cached_bounds
;
1049 gfx::Rect cached_screen_bounds
;
1050 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1051 if (cache
->GetGeometry(extension_id(),
1054 &cached_screen_bounds
,
1056 // App window has cached screen bounds, make sure it fits on screen in
1057 // case the screen resolution changed.
1058 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1059 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1060 gfx::Rect current_screen_bounds
= display
.work_area();
1061 extensions::SizeConstraints
constraints(
1062 params
.GetWindowMinimumSize(gfx::Insets()),
1063 params
.GetWindowMaximumSize(gfx::Insets()));
1064 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1065 cached_screen_bounds
,
1066 current_screen_bounds
,
1067 constraints
.GetMinimumSize(),
1068 ¶ms
.window_spec
.bounds
);
1069 params
.state
= cached_state
;
1071 // Since we are restoring a cached state, reset the content bounds spec to
1072 // ensure it is not used.
1073 params
.content_spec
.ResetBounds();
1081 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1082 const std::vector
<extensions::DraggableRegion
>& regions
) {
1083 SkRegion
* sk_region
= new SkRegion
;
1084 for (std::vector
<extensions::DraggableRegion
>::const_iterator iter
=
1086 iter
!= regions
.end();
1088 const extensions::DraggableRegion
& region
= *iter
;
1092 region
.bounds
.right(),
1093 region
.bounds
.bottom(),
1094 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);