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"
9 #include "apps/app_window_geometry_cache.h"
10 #include "apps/app_window_registry.h"
11 #include "apps/apps_client.h"
12 #include "apps/size_constraints.h"
13 #include "apps/ui/native_app_window.h"
14 #include "apps/ui/web_contents_sizer.h"
15 #include "base/command_line.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/values.h"
19 #include "chrome/browser/chrome_notification_types.h"
20 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
21 #include "chrome/browser/extensions/suggest_permission_util.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "components/web_modal/web_contents_modal_dialog_manager.h"
24 #include "content/public/browser/browser_context.h"
25 #include "content/public/browser/invalidate_type.h"
26 #include "content/public/browser/navigation_entry.h"
27 #include "content/public/browser/notification_details.h"
28 #include "content/public/browser/notification_service.h"
29 #include "content/public/browser/notification_source.h"
30 #include "content/public/browser/notification_types.h"
31 #include "content/public/browser/render_view_host.h"
32 #include "content/public/browser/resource_dispatcher_host.h"
33 #include "content/public/browser/web_contents.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/media_stream_request.h"
36 #include "extensions/browser/extension_registry.h"
37 #include "extensions/browser/extension_system.h"
38 #include "extensions/browser/extensions_browser_client.h"
39 #include "extensions/browser/process_manager.h"
40 #include "extensions/browser/view_type_utils.h"
41 #include "extensions/common/extension.h"
42 #include "extensions/common/extension_messages.h"
43 #include "extensions/common/manifest_handlers/icons_handler.h"
44 #include "extensions/common/permissions/permissions_data.h"
45 #include "grit/theme_resources.h"
46 #include "third_party/skia/include/core/SkRegion.h"
47 #include "ui/base/resource/resource_bundle.h"
48 #include "ui/gfx/screen.h"
50 #if !defined(OS_MACOSX)
51 #include "apps/pref_names.h"
52 #include "base/prefs/pref_service.h"
55 using content::BrowserContext
;
56 using content::ConsoleMessageLevel
;
57 using content::WebContents
;
58 using extensions::APIPermission
;
59 using web_modal::WebContentsModalDialogHost
;
60 using web_modal::WebContentsModalDialogManager
;
66 const int kDefaultWidth
= 512;
67 const int kDefaultHeight
= 384;
69 bool IsFullscreen(int fullscreen_types
) {
70 return fullscreen_types
!= apps::AppWindow::FULLSCREEN_TYPE_NONE
;
73 void SetConstraintProperty(const std::string
& name
,
75 base::DictionaryValue
* bounds_properties
) {
76 if (value
!= SizeConstraints::kUnboundedSize
)
77 bounds_properties
->SetInteger(name
, value
);
79 bounds_properties
->Set(name
, base::Value::CreateNullValue());
82 void SetBoundsProperties(const gfx::Rect
& bounds
,
83 const gfx::Size
& min_size
,
84 const gfx::Size
& max_size
,
85 const std::string
& bounds_name
,
86 base::DictionaryValue
* window_properties
) {
87 scoped_ptr
<base::DictionaryValue
> bounds_properties(
88 new base::DictionaryValue());
90 bounds_properties
->SetInteger("left", bounds
.x());
91 bounds_properties
->SetInteger("top", bounds
.y());
92 bounds_properties
->SetInteger("width", bounds
.width());
93 bounds_properties
->SetInteger("height", bounds
.height());
95 SetConstraintProperty("minWidth", min_size
.width(), bounds_properties
.get());
96 SetConstraintProperty(
97 "minHeight", min_size
.height(), bounds_properties
.get());
98 SetConstraintProperty("maxWidth", max_size
.width(), bounds_properties
.get());
99 SetConstraintProperty(
100 "maxHeight", max_size
.height(), bounds_properties
.get());
102 window_properties
->Set(bounds_name
, bounds_properties
.release());
105 // Combines the constraints of the content and window, and returns constraints
107 gfx::Size
GetCombinedWindowConstraints(const gfx::Size
& window_constraints
,
108 const gfx::Size
& content_constraints
,
109 const gfx::Insets
& frame_insets
) {
110 gfx::Size
combined_constraints(window_constraints
);
111 if (content_constraints
.width() > 0) {
112 combined_constraints
.set_width(
113 content_constraints
.width() + frame_insets
.width());
115 if (content_constraints
.height() > 0) {
116 combined_constraints
.set_height(
117 content_constraints
.height() + frame_insets
.height());
119 return combined_constraints
;
122 // Combines the constraints of the content and window, and returns constraints
124 gfx::Size
GetCombinedContentConstraints(const gfx::Size
& window_constraints
,
125 const gfx::Size
& content_constraints
,
126 const gfx::Insets
& frame_insets
) {
127 gfx::Size
combined_constraints(content_constraints
);
128 if (window_constraints
.width() > 0) {
129 combined_constraints
.set_width(
130 std::max(0, window_constraints
.width() - frame_insets
.width()));
132 if (window_constraints
.height() > 0) {
133 combined_constraints
.set_height(
134 std::max(0, window_constraints
.height() - frame_insets
.height()));
136 return combined_constraints
;
141 // AppWindow::BoundsSpecification
143 const int AppWindow::BoundsSpecification::kUnspecifiedPosition
= INT_MIN
;
145 AppWindow::BoundsSpecification::BoundsSpecification()
146 : bounds(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0) {}
148 AppWindow::BoundsSpecification::~BoundsSpecification() {}
150 void AppWindow::BoundsSpecification::ResetBounds() {
151 bounds
.SetRect(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0);
154 // AppWindow::CreateParams
156 AppWindow::CreateParams::CreateParams()
157 : window_type(AppWindow::WINDOW_TYPE_DEFAULT
),
158 frame(AppWindow::FRAME_CHROME
),
159 has_frame_color(false),
160 transparent_background(false),
161 creator_process_id(0),
162 state(ui::SHOW_STATE_DEFAULT
),
166 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 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
,
226 // AppWindow::Delegate
228 AppWindow::Delegate::~Delegate() {}
232 AppWindow::AppWindow(BrowserContext
* context
,
234 const extensions::Extension
* extension
)
235 : browser_context_(context
),
236 extension_id_(extension
->id()),
237 window_type_(WINDOW_TYPE_DEFAULT
),
239 image_loader_ptr_factory_(this),
240 fullscreen_types_(FULLSCREEN_TYPE_NONE
),
241 show_on_first_paint_(false),
242 first_paint_complete_(false),
243 has_been_shown_(false),
244 can_send_events_(false),
246 cached_always_on_top_(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 delegate_
->InitWebContents(web_contents
);
265 WebContentsModalDialogManager::CreateForWebContents(web_contents
);
266 // TODO(jamescook): Delegate out this creation.
267 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
270 web_contents
->SetDelegate(this);
271 WebContentsModalDialogManager::FromWebContents(web_contents
)
273 extensions::SetViewType(web_contents
, extensions::VIEW_TYPE_APP_WINDOW
);
275 // Initialize the window
276 CreateParams new_params
= LoadDefaults(params
);
277 window_type_
= new_params
.window_type
;
278 window_key_
= new_params
.window_key
;
280 // Windows cannot be always-on-top in fullscreen mode for security reasons.
281 cached_always_on_top_
= new_params
.always_on_top
;
282 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
283 new_params
.always_on_top
= false;
285 native_app_window_
.reset(delegate_
->CreateNativeAppWindow(this, new_params
));
287 // Prevent the browser process from shutting down while this window exists.
288 AppsClient::Get()->IncrementKeepAliveCount();
289 UpdateExtensionAppIcon();
290 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
292 if (new_params
.hidden
) {
293 // Although the window starts hidden by default, calling Hide() here
294 // notifies observers of the window being hidden.
297 // Panels are not activated by default.
298 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
302 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
304 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
306 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
309 OnNativeWindowChanged();
311 // When the render view host is changed, the native window needs to know
312 // about it in case it has any setup to do to make the renderer appear
313 // properly. In particular, on Windows, the view's clickthrough region needs
315 extensions::ExtensionsBrowserClient
* client
=
316 extensions::ExtensionsBrowserClient::Get();
318 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
319 content::Source
<content::BrowserContext
>(
320 client
->GetOriginalContext(browser_context_
)));
321 // Close when the browser process is exiting.
323 chrome::NOTIFICATION_APP_TERMINATING
,
324 content::NotificationService::AllSources());
325 // Update the app menu if an ephemeral app becomes installed.
327 chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED
,
328 content::Source
<content::BrowserContext
>(
329 client
->GetOriginalContext(browser_context_
)));
331 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
333 if (CommandLine::ForCurrentProcess()->HasSwitch(
334 switches::kEnableAppsShowOnFirstPaint
)) {
335 // We want to show the window only when the content has been painted. For
336 // that to happen, we need to define a size for the content, otherwise the
337 // layout will happen in a 0x0 area.
338 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
339 gfx::Rect initial_bounds
= new_params
.GetInitialWindowBounds(frame_insets
);
340 initial_bounds
.Inset(frame_insets
);
341 apps::ResizeWebContents(web_contents
, initial_bounds
.size());
345 AppWindow::~AppWindow() {
346 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
348 registrar_
.RemoveAll();
350 // Remove shutdown prevention.
351 AppsClient::Get()->DecrementKeepAliveCount();
354 void AppWindow::RequestMediaAccessPermission(
355 content::WebContents
* web_contents
,
356 const content::MediaStreamRequest
& request
,
357 const content::MediaResponseCallback
& callback
) {
358 const extensions::Extension
* extension
= GetExtension();
362 delegate_
->RequestMediaAccessPermission(
363 web_contents
, request
, callback
, extension
);
366 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
367 const content::OpenURLParams
& params
) {
368 // Don't allow the current tab to be navigated. It would be nice to map all
369 // anchor tags (even those without target="_blank") to new tabs, but right
370 // now we can't distinguish between those and <meta> refreshes or window.href
371 // navigations, which we don't want to allow.
372 // TOOD(mihaip): Can we check for user gestures instead?
373 WindowOpenDisposition disposition
= params
.disposition
;
374 if (disposition
== CURRENT_TAB
) {
375 AddMessageToDevToolsConsole(
376 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
378 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
379 params
.url
.spec().c_str()));
383 // These dispositions aren't really navigations.
384 if (disposition
== SUPPRESS_OPEN
|| disposition
== SAVE_TO_DISK
||
385 disposition
== IGNORE_ACTION
) {
389 WebContents
* contents
=
390 delegate_
->OpenURLFromTab(browser_context_
, source
, params
);
392 AddMessageToDevToolsConsole(
393 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
395 "Can't navigate to \"%s\"; apps do not support navigation.",
396 params
.url
.spec().c_str()));
402 void AppWindow::AddNewContents(WebContents
* source
,
403 WebContents
* new_contents
,
404 WindowOpenDisposition disposition
,
405 const gfx::Rect
& initial_pos
,
408 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
409 delegate_
->AddNewContents(browser_context_
,
417 bool AppWindow::PreHandleKeyboardEvent(
418 content::WebContents
* source
,
419 const content::NativeWebKeyboardEvent
& event
,
420 bool* is_keyboard_shortcut
) {
421 const extensions::Extension
* extension
= GetExtension();
425 // Here, we can handle a key event before the content gets it. When we are
426 // fullscreen and it is not forced, we want to allow the user to leave
427 // when ESC is pressed.
428 // However, if the application has the "overrideEscFullscreen" permission, we
429 // should let it override that behavior.
430 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
431 // action is not prevented.
432 // Thus, we should handle the KeyEvent here only if the permission is not set.
433 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&&
434 (fullscreen_types_
!= FULLSCREEN_TYPE_NONE
) &&
435 ((fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) == 0) &&
436 !extension
->permissions_data()->HasAPIPermission(
437 APIPermission::kOverrideEscFullscreen
)) {
445 void AppWindow::HandleKeyboardEvent(
447 const content::NativeWebKeyboardEvent
& event
) {
448 // If the window is currently fullscreen and not forced, ESC should leave
449 // fullscreen. If this code is being called for ESC, that means that the
450 // KeyEvent's default behavior was not prevented by the content.
451 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&&
452 (fullscreen_types_
!= FULLSCREEN_TYPE_NONE
) &&
453 ((fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) == 0)) {
458 native_app_window_
->HandleKeyboardEvent(event
);
461 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
463 bool last_unlocked_by_target
) {
464 const extensions::Extension
* extension
= GetExtension();
468 bool has_permission
= IsExtensionWithPermissionOrSuggestInConsole(
469 APIPermission::kPointerLock
,
471 web_contents
->GetRenderViewHost());
473 web_contents
->GotResponseToLockMouseRequest(has_permission
);
476 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
477 const blink::WebGestureEvent
& event
) {
478 // Disable pinch zooming in app windows.
479 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
480 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
481 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
484 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
485 first_paint_complete_
= true;
486 if (show_on_first_paint_
) {
487 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
488 delayed_show_type_
== SHOW_INACTIVE
);
489 Show(delayed_show_type_
);
493 void AppWindow::OnNativeClose() {
494 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
495 if (app_window_contents_
) {
496 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
497 WebContentsModalDialogManager::FromWebContents(web_contents
)
499 app_window_contents_
->NativeWindowClosed();
504 void AppWindow::OnNativeWindowChanged() {
505 SaveWindowPosition();
508 if (native_app_window_
&& cached_always_on_top_
&&
509 !IsFullscreen(fullscreen_types_
) && !native_app_window_
->IsMaximized() &&
510 !native_app_window_
->IsMinimized()) {
511 UpdateNativeAlwaysOnTop();
515 if (app_window_contents_
&& native_app_window_
)
516 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
519 void AppWindow::OnNativeWindowActivated() {
520 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
523 content::WebContents
* AppWindow::web_contents() const {
524 return app_window_contents_
->GetWebContents();
527 const extensions::Extension
* AppWindow::GetExtension() const {
528 return extensions::ExtensionRegistry::Get(browser_context_
)
529 ->enabled_extensions()
530 .GetByID(extension_id_
);
533 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
535 gfx::NativeWindow
AppWindow::GetNativeWindow() {
536 return GetBaseWindow()->GetNativeWindow();
539 gfx::Rect
AppWindow::GetClientBounds() const {
540 gfx::Rect bounds
= native_app_window_
->GetBounds();
541 bounds
.Inset(native_app_window_
->GetFrameInsets());
545 base::string16
AppWindow::GetTitle() const {
546 const extensions::Extension
* extension
= GetExtension();
548 return base::string16();
550 // WebContents::GetTitle() will return the page's URL if there's no <title>
551 // specified. However, we'd prefer to show the name of the extension in that
552 // case, so we directly inspect the NavigationEntry's title.
553 base::string16 title
;
554 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
555 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
556 title
= base::UTF8ToUTF16(extension
->name());
558 title
= web_contents()->GetTitle();
560 base::RemoveChars(title
, base::ASCIIToUTF16("\n"), &title
);
564 void AppWindow::SetAppIconUrl(const GURL
& url
) {
565 // If the same url is being used for the badge, ignore it.
566 if (url
== badge_icon_url_
)
569 // Avoid using any previous icons that were being downloaded.
570 image_loader_ptr_factory_
.InvalidateWeakPtrs();
572 // Reset |app_icon_image_| to abort pending image load (if any).
573 app_icon_image_
.reset();
576 web_contents()->DownloadImage(
578 true, // is a favicon
579 0, // no maximum size
580 base::Bind(&AppWindow::DidDownloadFavicon
,
581 image_loader_ptr_factory_
.GetWeakPtr()));
584 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
585 // Avoid using any previous icons that were being downloaded.
586 image_loader_ptr_factory_
.InvalidateWeakPtrs();
588 // Reset |app_icon_image_| to abort pending image load (if any).
589 badge_icon_image_
.reset();
591 badge_icon_url_
= url
;
592 web_contents()->DownloadImage(
594 true, // is a favicon
595 0, // no maximum size
596 base::Bind(&AppWindow::DidDownloadFavicon
,
597 image_loader_ptr_factory_
.GetWeakPtr()));
600 void AppWindow::ClearBadge() {
601 badge_icon_image_
.reset();
602 badge_icon_url_
= GURL();
603 UpdateBadgeIcon(gfx::Image());
606 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
607 native_app_window_
->UpdateShape(region
.Pass());
610 void AppWindow::UpdateDraggableRegions(
611 const std::vector
<extensions::DraggableRegion
>& regions
) {
612 native_app_window_
->UpdateDraggableRegions(regions
);
615 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
619 native_app_window_
->UpdateWindowIcon();
620 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
623 void AppWindow::Fullscreen() {
624 #if !defined(OS_MACOSX)
625 // Do not enter fullscreen mode if disallowed by pref.
627 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
629 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
632 fullscreen_types_
|= FULLSCREEN_TYPE_WINDOW_API
;
633 SetNativeWindowFullscreen();
636 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
638 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
640 void AppWindow::Restore() {
641 if (IsFullscreen(fullscreen_types_
)) {
642 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
643 SetNativeWindowFullscreen();
645 GetBaseWindow()->Restore();
649 void AppWindow::OSFullscreen() {
650 #if !defined(OS_MACOSX)
651 // Do not enter fullscreen mode if disallowed by pref.
653 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
655 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
658 fullscreen_types_
|= FULLSCREEN_TYPE_OS
;
659 SetNativeWindowFullscreen();
662 void AppWindow::ForcedFullscreen() {
663 fullscreen_types_
|= FULLSCREEN_TYPE_FORCED
;
664 SetNativeWindowFullscreen();
667 void AppWindow::SetContentSizeConstraints(const gfx::Size
& min_size
,
668 const gfx::Size
& max_size
) {
669 SizeConstraints
constraints(min_size
, max_size
);
670 native_app_window_
->SetContentSizeConstraints(constraints
.GetMinimumSize(),
671 constraints
.GetMaximumSize());
673 gfx::Rect bounds
= GetClientBounds();
674 gfx::Size constrained_size
= constraints
.ClampSize(bounds
.size());
675 if (bounds
.size() != constrained_size
) {
676 bounds
.set_size(constrained_size
);
677 bounds
.Inset(-native_app_window_
->GetFrameInsets());
678 native_app_window_
->SetBounds(bounds
);
680 OnNativeWindowChanged();
683 void AppWindow::Show(ShowType show_type
) {
686 if (CommandLine::ForCurrentProcess()->HasSwitch(
687 switches::kEnableAppsShowOnFirstPaint
)) {
688 show_on_first_paint_
= true;
690 if (!first_paint_complete_
) {
691 delayed_show_type_
= show_type
;
698 GetBaseWindow()->Show();
701 GetBaseWindow()->ShowInactive();
704 AppWindowRegistry::Get(browser_context_
)->AppWindowShown(this);
706 has_been_shown_
= true;
707 SendOnWindowShownIfShown();
710 void AppWindow::Hide() {
711 // This is there to prevent race conditions with Hide() being called before
712 // there was a non-empty paint. It should have no effect in a non-racy
713 // scenario where the application is hiding then showing a window: the second
714 // show will not be delayed.
716 show_on_first_paint_
= false;
717 GetBaseWindow()->Hide();
718 AppWindowRegistry::Get(browser_context_
)->AppWindowHidden(this);
721 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
722 if (cached_always_on_top_
== always_on_top
)
725 cached_always_on_top_
= always_on_top
;
727 // As a security measure, do not allow fullscreen windows or windows that
728 // overlap the taskbar to be on top. The property will be applied when the
729 // window exits fullscreen and moves away from the taskbar.
730 if (!IsFullscreen(fullscreen_types_
) && !IntersectsWithTaskbar())
731 native_app_window_
->SetAlwaysOnTop(always_on_top
);
733 OnNativeWindowChanged();
736 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
738 void AppWindow::WindowEventsReady() {
739 can_send_events_
= true;
740 SendOnWindowShownIfShown();
743 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
746 properties
->SetBoolean("fullscreen",
747 native_app_window_
->IsFullscreenOrPending());
748 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
749 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
750 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
751 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
753 // These properties are undocumented and are to enable testing. Alpha is
755 // make the values easier to check.
756 SkColor transparent_white
= ~SK_ColorBLACK
;
757 properties
->SetInteger(
759 native_app_window_
->ActiveFrameColor() & transparent_white
);
760 properties
->SetInteger(
761 "inactiveFrameColor",
762 native_app_window_
->InactiveFrameColor() & transparent_white
);
764 gfx::Rect content_bounds
= GetClientBounds();
765 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
766 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
767 SetBoundsProperties(content_bounds
,
773 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
774 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
775 gfx::Size frame_min_size
=
776 SizeConstraints::AddFrameToConstraints(content_min_size
, frame_insets
);
777 gfx::Size frame_max_size
=
778 SizeConstraints::AddFrameToConstraints(content_max_size
, frame_insets
);
779 SetBoundsProperties(frame_bounds
,
786 //------------------------------------------------------------------------------
789 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
791 native_app_window_
->UpdateBadgeIcon();
794 void AppWindow::DidDownloadFavicon(
796 int http_status_code
,
797 const GURL
& image_url
,
798 const std::vector
<SkBitmap
>& bitmaps
,
799 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
800 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
805 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
806 // whose height >= the preferred size.
807 int largest_index
= 0;
808 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
809 if (bitmaps
[i
].height() < delegate_
->PreferredIconSize())
813 const SkBitmap
& largest
= bitmaps
[largest_index
];
814 if (image_url
== app_icon_url_
) {
815 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
819 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
822 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage
* image
) {
823 DCHECK_EQ(app_icon_image_
.get(), image
);
825 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
828 void AppWindow::UpdateExtensionAppIcon() {
829 // Avoid using any previous app icons were being downloaded.
830 image_loader_ptr_factory_
.InvalidateWeakPtrs();
832 const gfx::ImageSkia
& default_icon
=
833 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
834 IDR_APP_DEFAULT_ICON
);
836 const extensions::Extension
* extension
= GetExtension();
840 app_icon_image_
.reset(
841 new extensions::IconImage(browser_context(),
843 extensions::IconsInfo::GetIcons(extension
),
844 delegate_
->PreferredIconSize(),
848 // Triggers actual image loading with 1x resources. The 2x resource will
849 // be handled by IconImage class when requested.
850 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
853 void AppWindow::SetNativeWindowFullscreen() {
854 native_app_window_
->SetFullscreen(fullscreen_types_
);
856 if (cached_always_on_top_
)
857 UpdateNativeAlwaysOnTop();
860 bool AppWindow::IntersectsWithTaskbar() const {
862 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
863 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
864 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
866 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
867 it
!= displays
.end();
869 gfx::Rect taskbar_bounds
= it
->bounds();
870 taskbar_bounds
.Subtract(it
->work_area());
871 if (taskbar_bounds
.IsEmpty())
874 if (window_bounds
.Intersects(taskbar_bounds
))
882 void AppWindow::UpdateNativeAlwaysOnTop() {
883 DCHECK(cached_always_on_top_
);
884 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
885 bool fullscreen
= IsFullscreen(fullscreen_types_
);
886 bool intersects_taskbar
= IntersectsWithTaskbar();
888 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
889 // When entering fullscreen or overlapping the taskbar, ensure windows are
890 // not always-on-top.
891 native_app_window_
->SetAlwaysOnTop(false);
892 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
893 // When exiting fullscreen and moving away from the taskbar, reinstate
895 native_app_window_
->SetAlwaysOnTop(true);
899 void AppWindow::SendOnWindowShownIfShown() {
900 if (!can_send_events_
|| !has_been_shown_
)
903 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType
)) {
904 app_window_contents_
->DispatchWindowShownForTests();
908 void AppWindow::CloseContents(WebContents
* contents
) {
909 native_app_window_
->Close();
912 bool AppWindow::ShouldSuppressDialogs() { return true; }
914 content::ColorChooser
* AppWindow::OpenColorChooser(
915 WebContents
* web_contents
,
916 SkColor initial_color
,
917 const std::vector
<content::ColorSuggestion
>& suggestionss
) {
918 return delegate_
->ShowColorChooser(web_contents
, initial_color
);
921 void AppWindow::RunFileChooser(WebContents
* tab
,
922 const content::FileChooserParams
& params
) {
923 if (window_type_is_panel()) {
924 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
925 // dialogs to be unhosted but still close with the owning web contents.
927 LOG(WARNING
) << "File dialog opened by panel.";
931 delegate_
->RunFileChooser(tab
, params
);
934 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
936 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
937 native_app_window_
->SetBounds(pos
);
940 void AppWindow::NavigationStateChanged(const content::WebContents
* source
,
941 unsigned changed_flags
) {
942 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
943 native_app_window_
->UpdateWindowTitle();
944 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
945 native_app_window_
->UpdateWindowIcon();
948 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
949 bool enter_fullscreen
) {
950 #if !defined(OS_MACOSX)
951 // Do not enter fullscreen mode if disallowed by pref.
952 // TODO(bartfab): Add a test once it becomes possible to simulate a user
953 // gesture. http://crbug.com/174178
955 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
957 if (enter_fullscreen
&& !prefs
->GetBoolean(prefs::kAppFullscreenAllowed
)) {
962 const extensions::Extension
* extension
= GetExtension();
966 if (!IsExtensionWithPermissionOrSuggestInConsole(
967 APIPermission::kFullscreen
, extension
, source
->GetRenderViewHost())) {
971 if (enter_fullscreen
)
972 fullscreen_types_
|= FULLSCREEN_TYPE_HTML_API
;
974 fullscreen_types_
&= ~FULLSCREEN_TYPE_HTML_API
;
975 SetNativeWindowFullscreen();
978 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
980 return ((fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0);
983 void AppWindow::Observe(int type
,
984 const content::NotificationSource
& source
,
985 const content::NotificationDetails
& details
) {
987 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
: {
988 const extensions::Extension
* unloaded_extension
=
989 content::Details
<extensions::UnloadedExtensionInfo
>(details
)
991 if (extension_id_
== unloaded_extension
->id())
992 native_app_window_
->Close();
995 case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED
: {
996 const extensions::Extension
* installed_extension
=
997 content::Details
<const extensions::InstalledExtensionInfo
>(details
)
999 DCHECK(installed_extension
);
1000 if (installed_extension
->id() == extension_id())
1001 native_app_window_
->UpdateShelfMenu();
1004 case chrome::NOTIFICATION_APP_TERMINATING
:
1005 native_app_window_
->Close();
1008 NOTREACHED() << "Received unexpected notification";
1012 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
1014 delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
1017 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
1018 return delegate_
->IsWebContentsVisible(web_contents
);
1021 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
1022 return native_app_window_
.get();
1025 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level
,
1026 const std::string
& message
) {
1027 content::RenderViewHost
* rvh
= web_contents()->GetRenderViewHost();
1028 rvh
->Send(new ExtensionMsg_AddMessageToConsole(
1029 rvh
->GetRoutingID(), level
, message
));
1032 void AppWindow::SaveWindowPosition() {
1033 if (window_key_
.empty())
1035 if (!native_app_window_
)
1038 AppWindowGeometryCache
* cache
=
1039 AppWindowGeometryCache::Get(browser_context());
1041 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
1042 gfx::Rect screen_bounds
=
1043 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
1044 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
1045 cache
->SaveGeometry(
1046 extension_id(), window_key_
, bounds
, screen_bounds
, window_state
);
1049 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1050 const gfx::Rect
& cached_bounds
,
1051 const gfx::Rect
& cached_screen_bounds
,
1052 const gfx::Rect
& current_screen_bounds
,
1053 const gfx::Size
& minimum_size
,
1054 gfx::Rect
* bounds
) const {
1055 *bounds
= cached_bounds
;
1057 // Reposition and resize the bounds if the cached_screen_bounds is different
1058 // from the current screen bounds and the current screen bounds doesn't
1059 // completely contain the bounds.
1060 if (cached_screen_bounds
!= current_screen_bounds
&&
1061 !current_screen_bounds
.Contains(cached_bounds
)) {
1063 std::max(minimum_size
.width(),
1064 std::min(bounds
->width(), current_screen_bounds
.width())));
1066 std::max(minimum_size
.height(),
1067 std::min(bounds
->height(), current_screen_bounds
.height())));
1069 std::max(current_screen_bounds
.x(),
1070 std::min(bounds
->x(),
1071 current_screen_bounds
.right() - bounds
->width())));
1073 std::max(current_screen_bounds
.y(),
1074 std::min(bounds
->y(),
1075 current_screen_bounds
.bottom() - bounds
->height())));
1079 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1081 // Ensure width and height are specified.
1082 if (params
.content_spec
.bounds
.width() == 0 &&
1083 params
.window_spec
.bounds
.width() == 0) {
1084 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1086 if (params
.content_spec
.bounds
.height() == 0 &&
1087 params
.window_spec
.bounds
.height() == 0) {
1088 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1091 // If left and top are left undefined, the native app window will center
1092 // the window on the main screen in a platform-defined manner.
1094 // Load cached state if it exists.
1095 if (!params
.window_key
.empty()) {
1096 AppWindowGeometryCache
* cache
=
1097 AppWindowGeometryCache::Get(browser_context());
1099 gfx::Rect cached_bounds
;
1100 gfx::Rect cached_screen_bounds
;
1101 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1102 if (cache
->GetGeometry(extension_id(),
1105 &cached_screen_bounds
,
1107 // App window has cached screen bounds, make sure it fits on screen in
1108 // case the screen resolution changed.
1109 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1110 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1111 gfx::Rect current_screen_bounds
= display
.work_area();
1112 SizeConstraints
constraints(params
.GetWindowMinimumSize(gfx::Insets()),
1113 params
.GetWindowMaximumSize(gfx::Insets()));
1114 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1115 cached_screen_bounds
,
1116 current_screen_bounds
,
1117 constraints
.GetMinimumSize(),
1118 ¶ms
.window_spec
.bounds
);
1119 params
.state
= cached_state
;
1121 // Since we are restoring a cached state, reset the content bounds spec to
1122 // ensure it is not used.
1123 params
.content_spec
.ResetBounds();
1131 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1132 const std::vector
<extensions::DraggableRegion
>& regions
) {
1133 SkRegion
* sk_region
= new SkRegion
;
1134 for (std::vector
<extensions::DraggableRegion
>::const_iterator iter
=
1136 iter
!= regions
.end();
1138 const extensions::DraggableRegion
& region
= *iter
;
1142 region
.bounds
.right(),
1143 region
.bounds
.bottom(),
1144 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);