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/browser/web_contents_view.h"
35 #include "content/public/common/media_stream_request.h"
36 #include "extensions/browser/extension_system.h"
37 #include "extensions/browser/extensions_browser_client.h"
38 #include "extensions/browser/process_manager.h"
39 #include "extensions/browser/view_type_utils.h"
40 #include "extensions/common/extension.h"
41 #include "extensions/common/extension_messages.h"
42 #include "extensions/common/manifest_handlers/icons_handler.h"
43 #include "third_party/skia/include/core/SkRegion.h"
44 #include "ui/gfx/screen.h"
46 #if !defined(OS_MACOSX)
47 #include "apps/pref_names.h"
48 #include "base/prefs/pref_service.h"
51 using content::BrowserContext
;
52 using content::ConsoleMessageLevel
;
53 using content::WebContents
;
54 using extensions::APIPermission
;
55 using web_modal::WebContentsModalDialogHost
;
56 using web_modal::WebContentsModalDialogManager
;
62 const int kDefaultWidth
= 512;
63 const int kDefaultHeight
= 384;
65 bool IsFullscreen(int fullscreen_types
) {
66 return fullscreen_types
!= apps::AppWindow::FULLSCREEN_TYPE_NONE
;
69 void SetConstraintProperty(const std::string
& name
,
71 base::DictionaryValue
* bounds_properties
) {
72 if (value
!= SizeConstraints::kUnboundedSize
)
73 bounds_properties
->SetInteger(name
, value
);
75 bounds_properties
->Set(name
, base::Value::CreateNullValue());
78 void SetBoundsProperties(const gfx::Rect
& bounds
,
79 const gfx::Size
& min_size
,
80 const gfx::Size
& max_size
,
81 const std::string
& bounds_name
,
82 base::DictionaryValue
* window_properties
) {
83 scoped_ptr
<base::DictionaryValue
> bounds_properties(
84 new base::DictionaryValue());
86 bounds_properties
->SetInteger("left", bounds
.x());
87 bounds_properties
->SetInteger("top", bounds
.y());
88 bounds_properties
->SetInteger("width", bounds
.width());
89 bounds_properties
->SetInteger("height", bounds
.height());
91 SetConstraintProperty("minWidth", min_size
.width(), bounds_properties
.get());
92 SetConstraintProperty(
93 "minHeight", min_size
.height(), bounds_properties
.get());
94 SetConstraintProperty("maxWidth", max_size
.width(), bounds_properties
.get());
95 SetConstraintProperty(
96 "maxHeight", max_size
.height(), bounds_properties
.get());
98 window_properties
->Set(bounds_name
, bounds_properties
.release());
101 // Combines the constraints of the content and window, and returns constraints
103 gfx::Size
GetCombinedWindowConstraints(const gfx::Size
& window_constraints
,
104 const gfx::Size
& content_constraints
,
105 const gfx::Insets
& frame_insets
) {
106 gfx::Size
combined_constraints(window_constraints
);
107 if (content_constraints
.width() > 0) {
108 combined_constraints
.set_width(
109 content_constraints
.width() + frame_insets
.width());
111 if (content_constraints
.height() > 0) {
112 combined_constraints
.set_height(
113 content_constraints
.height() + frame_insets
.height());
115 return combined_constraints
;
118 // Combines the constraints of the content and window, and returns constraints
120 gfx::Size
GetCombinedContentConstraints(const gfx::Size
& window_constraints
,
121 const gfx::Size
& content_constraints
,
122 const gfx::Insets
& frame_insets
) {
123 gfx::Size
combined_constraints(content_constraints
);
124 if (window_constraints
.width() > 0) {
125 combined_constraints
.set_width(
126 std::max(0, window_constraints
.width() - frame_insets
.width()));
128 if (window_constraints
.height() > 0) {
129 combined_constraints
.set_height(
130 std::max(0, window_constraints
.height() - frame_insets
.height()));
132 return combined_constraints
;
137 // AppWindow::BoundsSpecification
139 const int AppWindow::BoundsSpecification::kUnspecifiedPosition
= INT_MIN
;
141 AppWindow::BoundsSpecification::BoundsSpecification()
142 : bounds(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0) {}
144 AppWindow::BoundsSpecification::~BoundsSpecification() {}
146 void AppWindow::BoundsSpecification::ResetBounds() {
147 bounds
.SetRect(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0);
150 // AppWindow::CreateParams
152 AppWindow::CreateParams::CreateParams()
153 : window_type(AppWindow::WINDOW_TYPE_DEFAULT
),
154 frame(AppWindow::FRAME_CHROME
),
155 has_frame_color(false),
156 transparent_background(false),
157 creator_process_id(0),
158 state(ui::SHOW_STATE_DEFAULT
),
162 always_on_top(false) {}
164 AppWindow::CreateParams::~CreateParams() {}
166 gfx::Rect
AppWindow::CreateParams::GetInitialWindowBounds(
167 const gfx::Insets
& frame_insets
) const {
168 // Combine into a single window bounds.
169 gfx::Rect
combined_bounds(window_spec
.bounds
);
170 if (content_spec
.bounds
.x() != BoundsSpecification::kUnspecifiedPosition
)
171 combined_bounds
.set_x(content_spec
.bounds
.x() - frame_insets
.left());
172 if (content_spec
.bounds
.y() != BoundsSpecification::kUnspecifiedPosition
)
173 combined_bounds
.set_y(content_spec
.bounds
.y() - frame_insets
.top());
174 if (content_spec
.bounds
.width() > 0) {
175 combined_bounds
.set_width(
176 content_spec
.bounds
.width() + frame_insets
.width());
178 if (content_spec
.bounds
.height() > 0) {
179 combined_bounds
.set_height(
180 content_spec
.bounds
.height() + frame_insets
.height());
183 // Constrain the bounds.
184 SizeConstraints
constraints(
185 GetCombinedWindowConstraints(
186 window_spec
.minimum_size
, content_spec
.minimum_size
, frame_insets
),
187 GetCombinedWindowConstraints(
188 window_spec
.maximum_size
, content_spec
.maximum_size
, frame_insets
));
189 combined_bounds
.set_size(constraints
.ClampSize(combined_bounds
.size()));
191 return combined_bounds
;
194 gfx::Size
AppWindow::CreateParams::GetContentMinimumSize(
195 const gfx::Insets
& frame_insets
) const {
196 return GetCombinedContentConstraints(window_spec
.minimum_size
,
197 content_spec
.minimum_size
,
201 gfx::Size
AppWindow::CreateParams::GetContentMaximumSize(
202 const gfx::Insets
& frame_insets
) const {
203 return GetCombinedContentConstraints(window_spec
.maximum_size
,
204 content_spec
.maximum_size
,
208 gfx::Size
AppWindow::CreateParams::GetWindowMinimumSize(
209 const gfx::Insets
& frame_insets
) const {
210 return GetCombinedWindowConstraints(window_spec
.minimum_size
,
211 content_spec
.minimum_size
,
215 gfx::Size
AppWindow::CreateParams::GetWindowMaximumSize(
216 const gfx::Insets
& frame_insets
) const {
217 return GetCombinedWindowConstraints(window_spec
.maximum_size
,
218 content_spec
.maximum_size
,
222 // AppWindow::Delegate
224 AppWindow::Delegate::~Delegate() {}
228 AppWindow::AppWindow(BrowserContext
* context
,
230 const extensions::Extension
* extension
)
231 : browser_context_(context
),
232 extension_(extension
),
233 extension_id_(extension
->id()),
234 window_type_(WINDOW_TYPE_DEFAULT
),
236 image_loader_ptr_factory_(this),
237 fullscreen_types_(FULLSCREEN_TYPE_NONE
),
238 show_on_first_paint_(false),
239 first_paint_complete_(false),
240 cached_always_on_top_(false) {
241 extensions::ExtensionsBrowserClient
* client
=
242 extensions::ExtensionsBrowserClient::Get();
243 CHECK(!client
->IsGuestSession(context
) || context
->IsOffTheRecord())
244 << "Only off the record window may be opened in the guest mode.";
247 void AppWindow::Init(const GURL
& url
,
248 AppWindowContents
* app_window_contents
,
249 const CreateParams
& params
) {
250 // Initialize the render interface and web contents
251 app_window_contents_
.reset(app_window_contents
);
252 app_window_contents_
->Initialize(browser_context(), url
);
253 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
254 if (CommandLine::ForCurrentProcess()->HasSwitch(
255 switches::kEnableAppsShowOnFirstPaint
)) {
256 content::WebContentsObserver::Observe(web_contents
);
258 delegate_
->InitWebContents(web_contents
);
259 WebContentsModalDialogManager::CreateForWebContents(web_contents
);
260 // TODO(jamescook): Delegate out this creation.
261 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
264 web_contents
->SetDelegate(this);
265 WebContentsModalDialogManager::FromWebContents(web_contents
)
267 extensions::SetViewType(web_contents
, extensions::VIEW_TYPE_APP_WINDOW
);
269 // Initialize the window
270 CreateParams new_params
= LoadDefaults(params
);
271 window_type_
= new_params
.window_type
;
272 window_key_
= new_params
.window_key
;
274 // Windows cannot be always-on-top in fullscreen mode for security reasons.
275 cached_always_on_top_
= new_params
.always_on_top
;
276 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
277 new_params
.always_on_top
= false;
279 native_app_window_
.reset(delegate_
->CreateNativeAppWindow(this, new_params
));
281 if (!new_params
.hidden
) {
282 // Panels are not activated by default.
283 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
287 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
289 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
291 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
294 OnNativeWindowChanged();
296 // When the render view host is changed, the native window needs to know
297 // about it in case it has any setup to do to make the renderer appear
298 // properly. In particular, on Windows, the view's clickthrough region needs
300 extensions::ExtensionsBrowserClient
* client
=
301 extensions::ExtensionsBrowserClient::Get();
303 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
304 content::Source
<content::BrowserContext
>(
305 client
->GetOriginalContext(browser_context_
)));
306 // Close when the browser process is exiting.
308 chrome::NOTIFICATION_APP_TERMINATING
,
309 content::NotificationService::AllSources());
310 // Update the app menu if an ephemeral app becomes installed.
312 chrome::NOTIFICATION_EXTENSION_INSTALLED
,
313 content::Source
<content::BrowserContext
>(
314 client
->GetOriginalContext(browser_context_
)));
316 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
318 if (CommandLine::ForCurrentProcess()->HasSwitch(
319 switches::kEnableAppsShowOnFirstPaint
)) {
320 // We want to show the window only when the content has been painted. For
321 // that to happen, we need to define a size for the content, otherwise the
322 // layout will happen in a 0x0 area.
323 // Note: WebContents::GetView() is guaranteed to be non-null.
324 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
325 gfx::Rect initial_bounds
= new_params
.GetInitialWindowBounds(frame_insets
);
326 initial_bounds
.Inset(frame_insets
);
327 apps::ResizeWebContents(web_contents
, initial_bounds
.size());
330 // Prevent the browser process from shutting down while this window is open.
331 AppsClient::Get()->IncrementKeepAliveCount();
333 UpdateExtensionAppIcon();
335 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
338 AppWindow::~AppWindow() {
339 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
341 registrar_
.RemoveAll();
343 // Remove shutdown prevention.
344 AppsClient::Get()->DecrementKeepAliveCount();
347 void AppWindow::RequestMediaAccessPermission(
348 content::WebContents
* web_contents
,
349 const content::MediaStreamRequest
& request
,
350 const content::MediaResponseCallback
& callback
) {
351 delegate_
->RequestMediaAccessPermission(
352 web_contents
, request
, callback
, extension());
355 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
356 const content::OpenURLParams
& params
) {
357 // Don't allow the current tab to be navigated. It would be nice to map all
358 // anchor tags (even those without target="_blank") to new tabs, but right
359 // now we can't distinguish between those and <meta> refreshes or window.href
360 // navigations, which we don't want to allow.
361 // TOOD(mihaip): Can we check for user gestures instead?
362 WindowOpenDisposition disposition
= params
.disposition
;
363 if (disposition
== CURRENT_TAB
) {
364 AddMessageToDevToolsConsole(
365 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
367 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
368 params
.url
.spec().c_str()));
372 // These dispositions aren't really navigations.
373 if (disposition
== SUPPRESS_OPEN
|| disposition
== SAVE_TO_DISK
||
374 disposition
== IGNORE_ACTION
) {
378 WebContents
* contents
=
379 delegate_
->OpenURLFromTab(browser_context_
, source
, params
);
381 AddMessageToDevToolsConsole(
382 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
384 "Can't navigate to \"%s\"; apps do not support navigation.",
385 params
.url
.spec().c_str()));
391 void AppWindow::AddNewContents(WebContents
* source
,
392 WebContents
* new_contents
,
393 WindowOpenDisposition disposition
,
394 const gfx::Rect
& initial_pos
,
397 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
398 delegate_
->AddNewContents(browser_context_
,
406 bool AppWindow::PreHandleKeyboardEvent(
407 content::WebContents
* source
,
408 const content::NativeWebKeyboardEvent
& event
,
409 bool* is_keyboard_shortcut
) {
410 // Here, we can handle a key event before the content gets it. When we are
411 // fullscreen and it is not forced, we want to allow the user to leave
412 // when ESC is pressed.
413 // However, if the application has the "overrideEscFullscreen" permission, we
414 // should let it override that behavior.
415 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
416 // action is not prevented.
417 // Thus, we should handle the KeyEvent here only if the permission is not set.
418 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&&
419 (fullscreen_types_
!= FULLSCREEN_TYPE_NONE
) &&
420 ((fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) == 0) &&
421 !extension_
->HasAPIPermission(APIPermission::kOverrideEscFullscreen
)) {
429 void AppWindow::HandleKeyboardEvent(
431 const content::NativeWebKeyboardEvent
& event
) {
432 // If the window is currently fullscreen and not forced, ESC should leave
433 // fullscreen. If this code is being called for ESC, that means that the
434 // KeyEvent's default behavior was not prevented by the content.
435 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&&
436 (fullscreen_types_
!= FULLSCREEN_TYPE_NONE
) &&
437 ((fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) == 0)) {
442 native_app_window_
->HandleKeyboardEvent(event
);
445 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
447 bool last_unlocked_by_target
) {
448 bool has_permission
= IsExtensionWithPermissionOrSuggestInConsole(
449 APIPermission::kPointerLock
,
451 web_contents
->GetRenderViewHost());
453 web_contents
->GotResponseToLockMouseRequest(has_permission
);
456 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
457 const blink::WebGestureEvent
& event
) {
458 // Disable pinch zooming in app windows.
459 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
460 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
461 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
464 void AppWindow::DidFirstVisuallyNonEmptyPaint(int32 page_id
) {
465 first_paint_complete_
= true;
466 if (show_on_first_paint_
) {
467 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
468 delayed_show_type_
== SHOW_INACTIVE
);
469 Show(delayed_show_type_
);
473 void AppWindow::OnNativeClose() {
474 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
475 if (app_window_contents_
) {
476 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
477 WebContentsModalDialogManager::FromWebContents(web_contents
)
479 app_window_contents_
->NativeWindowClosed();
484 void AppWindow::OnNativeWindowChanged() {
485 SaveWindowPosition();
488 if (native_app_window_
&& cached_always_on_top_
&&
489 !IsFullscreen(fullscreen_types_
) && !native_app_window_
->IsMaximized() &&
490 !native_app_window_
->IsMinimized()) {
491 UpdateNativeAlwaysOnTop();
495 if (app_window_contents_
&& native_app_window_
)
496 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
499 void AppWindow::OnNativeWindowActivated() {
500 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
503 content::WebContents
* AppWindow::web_contents() const {
504 return app_window_contents_
->GetWebContents();
507 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
509 gfx::NativeWindow
AppWindow::GetNativeWindow() {
510 return GetBaseWindow()->GetNativeWindow();
513 gfx::Rect
AppWindow::GetClientBounds() const {
514 gfx::Rect bounds
= native_app_window_
->GetBounds();
515 bounds
.Inset(native_app_window_
->GetFrameInsets());
519 base::string16
AppWindow::GetTitle() const {
520 // WebContents::GetTitle() will return the page's URL if there's no <title>
521 // specified. However, we'd prefer to show the name of the extension in that
522 // case, so we directly inspect the NavigationEntry's title.
523 base::string16 title
;
524 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
525 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
526 title
= base::UTF8ToUTF16(extension()->name());
528 title
= web_contents()->GetTitle();
530 const base::char16 kBadChars
[] = {'\n', 0};
531 base::RemoveChars(title
, kBadChars
, &title
);
535 void AppWindow::SetAppIconUrl(const GURL
& url
) {
536 // If the same url is being used for the badge, ignore it.
537 if (url
== badge_icon_url_
)
540 // Avoid using any previous icons that were being downloaded.
541 image_loader_ptr_factory_
.InvalidateWeakPtrs();
543 // Reset |app_icon_image_| to abort pending image load (if any).
544 app_icon_image_
.reset();
547 web_contents()->DownloadImage(
549 true, // is a favicon
550 0, // no maximum size
551 base::Bind(&AppWindow::DidDownloadFavicon
,
552 image_loader_ptr_factory_
.GetWeakPtr()));
555 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
556 // Avoid using any previous icons that were being downloaded.
557 image_loader_ptr_factory_
.InvalidateWeakPtrs();
559 // Reset |app_icon_image_| to abort pending image load (if any).
560 badge_icon_image_
.reset();
562 badge_icon_url_
= url
;
563 web_contents()->DownloadImage(
565 true, // is a favicon
566 0, // no maximum size
567 base::Bind(&AppWindow::DidDownloadFavicon
,
568 image_loader_ptr_factory_
.GetWeakPtr()));
571 void AppWindow::ClearBadge() {
572 badge_icon_image_
.reset();
573 badge_icon_url_
= GURL();
574 UpdateBadgeIcon(gfx::Image());
577 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
578 native_app_window_
->UpdateShape(region
.Pass());
581 void AppWindow::UpdateDraggableRegions(
582 const std::vector
<extensions::DraggableRegion
>& regions
) {
583 native_app_window_
->UpdateDraggableRegions(regions
);
586 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
590 native_app_window_
->UpdateWindowIcon();
591 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
594 void AppWindow::Fullscreen() {
595 #if !defined(OS_MACOSX)
596 // Do not enter fullscreen mode if disallowed by pref.
598 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
600 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
603 fullscreen_types_
|= FULLSCREEN_TYPE_WINDOW_API
;
604 SetNativeWindowFullscreen();
607 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
609 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
611 void AppWindow::Restore() {
612 if (IsFullscreen(fullscreen_types_
)) {
613 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
614 SetNativeWindowFullscreen();
616 GetBaseWindow()->Restore();
620 void AppWindow::OSFullscreen() {
621 #if !defined(OS_MACOSX)
622 // Do not enter fullscreen mode if disallowed by pref.
624 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
626 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
629 fullscreen_types_
|= FULLSCREEN_TYPE_OS
;
630 SetNativeWindowFullscreen();
633 void AppWindow::ForcedFullscreen() {
634 fullscreen_types_
|= FULLSCREEN_TYPE_FORCED
;
635 SetNativeWindowFullscreen();
638 void AppWindow::SetContentSizeConstraints(const gfx::Size
& min_size
,
639 const gfx::Size
& max_size
) {
640 SizeConstraints
constraints(min_size
, max_size
);
641 native_app_window_
->SetContentSizeConstraints(constraints
.GetMinimumSize(),
642 constraints
.GetMaximumSize());
644 gfx::Rect bounds
= GetClientBounds();
645 gfx::Size constrained_size
= constraints
.ClampSize(bounds
.size());
646 if (bounds
.size() != constrained_size
) {
647 bounds
.set_size(constrained_size
);
648 bounds
.Inset(-native_app_window_
->GetFrameInsets());
649 native_app_window_
->SetBounds(bounds
);
651 OnNativeWindowChanged();
654 void AppWindow::Show(ShowType show_type
) {
655 if (CommandLine::ForCurrentProcess()->HasSwitch(
656 switches::kEnableAppsShowOnFirstPaint
)) {
657 show_on_first_paint_
= true;
659 if (!first_paint_complete_
) {
660 delayed_show_type_
= show_type
;
667 GetBaseWindow()->Show();
670 GetBaseWindow()->ShowInactive();
675 void AppWindow::Hide() {
676 // This is there to prevent race conditions with Hide() being called before
677 // there was a non-empty paint. It should have no effect in a non-racy
678 // scenario where the application is hiding then showing a window: the second
679 // show will not be delayed.
680 show_on_first_paint_
= false;
681 GetBaseWindow()->Hide();
684 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
685 if (cached_always_on_top_
== always_on_top
)
688 cached_always_on_top_
= always_on_top
;
690 // As a security measure, do not allow fullscreen windows or windows that
691 // overlap the taskbar to be on top. The property will be applied when the
692 // window exits fullscreen and moves away from the taskbar.
693 if (!IsFullscreen(fullscreen_types_
) && !IntersectsWithTaskbar())
694 native_app_window_
->SetAlwaysOnTop(always_on_top
);
696 OnNativeWindowChanged();
699 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
701 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
704 properties
->SetBoolean("fullscreen",
705 native_app_window_
->IsFullscreenOrPending());
706 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
707 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
708 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
709 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
710 properties
->SetInteger("frameColor", native_app_window_
->FrameColor());
712 gfx::Rect content_bounds
= GetClientBounds();
713 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
714 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
715 SetBoundsProperties(content_bounds
,
721 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
722 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
723 gfx::Size frame_min_size
=
724 SizeConstraints::AddFrameToConstraints(content_min_size
, frame_insets
);
725 gfx::Size frame_max_size
=
726 SizeConstraints::AddFrameToConstraints(content_max_size
, frame_insets
);
727 SetBoundsProperties(frame_bounds
,
734 //------------------------------------------------------------------------------
737 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
739 native_app_window_
->UpdateBadgeIcon();
742 void AppWindow::DidDownloadFavicon(
744 int http_status_code
,
745 const GURL
& image_url
,
746 const std::vector
<SkBitmap
>& bitmaps
,
747 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
748 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
753 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
754 // whose height >= the preferred size.
755 int largest_index
= 0;
756 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
757 if (bitmaps
[i
].height() < delegate_
->PreferredIconSize())
761 const SkBitmap
& largest
= bitmaps
[largest_index
];
762 if (image_url
== app_icon_url_
) {
763 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
767 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
770 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage
* image
) {
771 DCHECK_EQ(app_icon_image_
.get(), image
);
773 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
776 void AppWindow::UpdateExtensionAppIcon() {
777 // Avoid using any previous app icons were being downloaded.
778 image_loader_ptr_factory_
.InvalidateWeakPtrs();
780 app_icon_image_
.reset(
781 new extensions::IconImage(browser_context(),
783 extensions::IconsInfo::GetIcons(extension()),
784 delegate_
->PreferredIconSize(),
785 extensions::IconsInfo::GetDefaultAppIcon(),
788 // Triggers actual image loading with 1x resources. The 2x resource will
789 // be handled by IconImage class when requested.
790 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
793 void AppWindow::SetNativeWindowFullscreen() {
794 native_app_window_
->SetFullscreen(fullscreen_types_
);
796 if (cached_always_on_top_
)
797 UpdateNativeAlwaysOnTop();
800 bool AppWindow::IntersectsWithTaskbar() const {
802 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
803 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
804 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
806 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
807 it
!= displays
.end();
809 gfx::Rect taskbar_bounds
= it
->bounds();
810 taskbar_bounds
.Subtract(it
->work_area());
811 if (taskbar_bounds
.IsEmpty())
814 if (window_bounds
.Intersects(taskbar_bounds
))
822 void AppWindow::UpdateNativeAlwaysOnTop() {
823 DCHECK(cached_always_on_top_
);
824 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
825 bool fullscreen
= IsFullscreen(fullscreen_types_
);
826 bool intersects_taskbar
= IntersectsWithTaskbar();
828 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
829 // When entering fullscreen or overlapping the taskbar, ensure windows are
830 // not always-on-top.
831 native_app_window_
->SetAlwaysOnTop(false);
832 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
833 // When exiting fullscreen and moving away from the taskbar, reinstate
835 native_app_window_
->SetAlwaysOnTop(true);
839 void AppWindow::CloseContents(WebContents
* contents
) {
840 native_app_window_
->Close();
843 bool AppWindow::ShouldSuppressDialogs() { return true; }
845 content::ColorChooser
* AppWindow::OpenColorChooser(
846 WebContents
* web_contents
,
847 SkColor initial_color
,
848 const std::vector
<content::ColorSuggestion
>& suggestionss
) {
849 return delegate_
->ShowColorChooser(web_contents
, initial_color
);
852 void AppWindow::RunFileChooser(WebContents
* tab
,
853 const content::FileChooserParams
& params
) {
854 if (window_type_is_panel()) {
855 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
856 // dialogs to be unhosted but still close with the owning web contents.
858 LOG(WARNING
) << "File dialog opened by panel.";
862 delegate_
->RunFileChooser(tab
, params
);
865 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
867 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
868 native_app_window_
->SetBounds(pos
);
871 void AppWindow::NavigationStateChanged(const content::WebContents
* source
,
872 unsigned changed_flags
) {
873 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
874 native_app_window_
->UpdateWindowTitle();
875 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
876 native_app_window_
->UpdateWindowIcon();
879 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
880 bool enter_fullscreen
) {
881 #if !defined(OS_MACOSX)
882 // Do not enter fullscreen mode if disallowed by pref.
883 // TODO(bartfab): Add a test once it becomes possible to simulate a user
884 // gesture. http://crbug.com/174178
886 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
888 if (enter_fullscreen
&& !prefs
->GetBoolean(prefs::kAppFullscreenAllowed
)) {
893 if (!IsExtensionWithPermissionOrSuggestInConsole(
894 APIPermission::kFullscreen
,
896 source
->GetRenderViewHost())) {
900 if (enter_fullscreen
)
901 fullscreen_types_
|= FULLSCREEN_TYPE_HTML_API
;
903 fullscreen_types_
&= ~FULLSCREEN_TYPE_HTML_API
;
904 SetNativeWindowFullscreen();
907 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
909 return ((fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0);
912 void AppWindow::Observe(int type
,
913 const content::NotificationSource
& source
,
914 const content::NotificationDetails
& details
) {
916 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
: {
917 const extensions::Extension
* unloaded_extension
=
918 content::Details
<extensions::UnloadedExtensionInfo
>(details
)
920 if (extension_
== unloaded_extension
)
921 native_app_window_
->Close();
924 case chrome::NOTIFICATION_EXTENSION_INSTALLED
: {
925 const extensions::Extension
* installed_extension
=
926 content::Details
<const extensions::InstalledExtensionInfo
>(details
)
928 DCHECK(installed_extension
);
929 if (installed_extension
->id() == extension_
->id())
930 native_app_window_
->UpdateShelfMenu();
933 case chrome::NOTIFICATION_APP_TERMINATING
:
934 native_app_window_
->Close();
937 NOTREACHED() << "Received unexpected notification";
941 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
943 delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
946 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
947 return delegate_
->IsWebContentsVisible(web_contents
);
950 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
951 return native_app_window_
.get();
954 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level
,
955 const std::string
& message
) {
956 content::RenderViewHost
* rvh
= web_contents()->GetRenderViewHost();
957 rvh
->Send(new ExtensionMsg_AddMessageToConsole(
958 rvh
->GetRoutingID(), level
, message
));
961 void AppWindow::SaveWindowPosition() {
962 if (window_key_
.empty())
964 if (!native_app_window_
)
967 AppWindowGeometryCache
* cache
=
968 AppWindowGeometryCache::Get(browser_context());
970 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
971 gfx::Rect screen_bounds
=
972 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
973 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
975 extension()->id(), window_key_
, bounds
, screen_bounds
, window_state
);
978 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
979 const gfx::Rect
& cached_bounds
,
980 const gfx::Rect
& cached_screen_bounds
,
981 const gfx::Rect
& current_screen_bounds
,
982 const gfx::Size
& minimum_size
,
983 gfx::Rect
* bounds
) const {
984 *bounds
= cached_bounds
;
986 // Reposition and resize the bounds if the cached_screen_bounds is different
987 // from the current screen bounds and the current screen bounds doesn't
988 // completely contain the bounds.
989 if (cached_screen_bounds
!= current_screen_bounds
&&
990 !current_screen_bounds
.Contains(cached_bounds
)) {
992 std::max(minimum_size
.width(),
993 std::min(bounds
->width(), current_screen_bounds
.width())));
995 std::max(minimum_size
.height(),
996 std::min(bounds
->height(), current_screen_bounds
.height())));
998 std::max(current_screen_bounds
.x(),
999 std::min(bounds
->x(),
1000 current_screen_bounds
.right() - bounds
->width())));
1002 std::max(current_screen_bounds
.y(),
1003 std::min(bounds
->y(),
1004 current_screen_bounds
.bottom() - bounds
->height())));
1008 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1010 // Ensure width and height are specified.
1011 if (params
.content_spec
.bounds
.width() == 0 &&
1012 params
.window_spec
.bounds
.width() == 0) {
1013 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1015 if (params
.content_spec
.bounds
.height() == 0 &&
1016 params
.window_spec
.bounds
.height() == 0) {
1017 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1020 // If left and top are left undefined, the native app window will center
1021 // the window on the main screen in a platform-defined manner.
1023 // Load cached state if it exists.
1024 if (!params
.window_key
.empty()) {
1025 AppWindowGeometryCache
* cache
=
1026 AppWindowGeometryCache::Get(browser_context());
1028 gfx::Rect cached_bounds
;
1029 gfx::Rect cached_screen_bounds
;
1030 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1031 if (cache
->GetGeometry(extension()->id(),
1034 &cached_screen_bounds
,
1037 // App window has cached screen bounds, make sure it fits on screen in
1038 // case the screen resolution changed.
1039 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1040 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1041 gfx::Rect current_screen_bounds
= display
.work_area();
1042 SizeConstraints
constraints(params
.GetWindowMinimumSize(gfx::Insets()),
1043 params
.GetWindowMaximumSize(gfx::Insets()));
1044 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1045 cached_screen_bounds
,
1046 current_screen_bounds
,
1047 constraints
.GetMinimumSize(),
1048 ¶ms
.window_spec
.bounds
);
1049 params
.state
= cached_state
;
1051 // Since we are restoring a cached state, reset the content bounds spec to
1052 // ensure it is not used.
1053 params
.content_spec
.ResetBounds();
1061 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1062 const std::vector
<extensions::DraggableRegion
>& regions
) {
1063 SkRegion
* sk_region
= new SkRegion
;
1064 for (std::vector
<extensions::DraggableRegion
>::const_iterator iter
=
1066 iter
!= regions
.end();
1068 const extensions::DraggableRegion
& region
= *iter
;
1072 region
.bounds
.right(),
1073 region
.bounds
.bottom(),
1074 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);