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 "base/command_line.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "chrome/browser/chrome_notification_types.h"
19 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
20 #include "chrome/browser/extensions/suggest_permission_util.h"
21 #include "chrome/common/chrome_switches.h"
22 #include "chrome/common/extensions/manifest_handlers/icons_handler.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 "third_party/skia/include/core/SkRegion.h"
43 #include "ui/gfx/screen.h"
45 #if !defined(OS_MACOSX)
46 #include "apps/pref_names.h"
47 #include "base/prefs/pref_service.h"
50 using content::BrowserContext
;
51 using content::ConsoleMessageLevel
;
52 using content::WebContents
;
53 using extensions::APIPermission
;
54 using web_modal::WebContentsModalDialogHost
;
55 using web_modal::WebContentsModalDialogManager
;
61 const int kDefaultWidth
= 512;
62 const int kDefaultHeight
= 384;
64 bool IsFullscreen(int fullscreen_types
) {
65 return fullscreen_types
!= apps::AppWindow::FULLSCREEN_TYPE_NONE
;
68 void SetConstraintProperty(const std::string
& name
,
70 base::DictionaryValue
* bounds_properties
) {
71 if (value
!= SizeConstraints::kUnboundedSize
)
72 bounds_properties
->SetInteger(name
, value
);
74 bounds_properties
->Set(name
, base::Value::CreateNullValue());
77 void SetBoundsProperties(const gfx::Rect
& bounds
,
78 const gfx::Size
& min_size
,
79 const gfx::Size
& max_size
,
80 const std::string
& bounds_name
,
81 base::DictionaryValue
* window_properties
) {
82 scoped_ptr
<base::DictionaryValue
> bounds_properties(
83 new base::DictionaryValue());
85 bounds_properties
->SetInteger("left", bounds
.x());
86 bounds_properties
->SetInteger("top", bounds
.y());
87 bounds_properties
->SetInteger("width", bounds
.width());
88 bounds_properties
->SetInteger("height", bounds
.height());
90 SetConstraintProperty("minWidth", min_size
.width(), bounds_properties
.get());
91 SetConstraintProperty(
92 "minHeight", min_size
.height(), bounds_properties
.get());
93 SetConstraintProperty("maxWidth", max_size
.width(), bounds_properties
.get());
94 SetConstraintProperty(
95 "maxHeight", max_size
.height(), bounds_properties
.get());
97 window_properties
->Set(bounds_name
, bounds_properties
.release());
100 // Combines the constraints of the content and window, and returns constraints
102 gfx::Size
GetCombinedWindowConstraints(const gfx::Size
& window_constraints
,
103 const gfx::Size
& content_constraints
,
104 const gfx::Insets
& frame_insets
) {
105 gfx::Size
combined_constraints(window_constraints
);
106 if (content_constraints
.width() > 0) {
107 combined_constraints
.set_width(
108 content_constraints
.width() + frame_insets
.width());
110 if (content_constraints
.height() > 0) {
111 combined_constraints
.set_height(
112 content_constraints
.height() + frame_insets
.height());
114 return combined_constraints
;
117 // Combines the constraints of the content and window, and returns constraints
119 gfx::Size
GetCombinedContentConstraints(const gfx::Size
& window_constraints
,
120 const gfx::Size
& content_constraints
,
121 const gfx::Insets
& frame_insets
) {
122 gfx::Size
combined_constraints(content_constraints
);
123 if (window_constraints
.width() > 0) {
124 combined_constraints
.set_width(
125 std::max(0, window_constraints
.width() - frame_insets
.width()));
127 if (window_constraints
.height() > 0) {
128 combined_constraints
.set_height(
129 std::max(0, window_constraints
.height() - frame_insets
.height()));
131 return combined_constraints
;
136 // AppWindow::BoundsSpecification
138 const int AppWindow::BoundsSpecification::kUnspecifiedPosition
= INT_MIN
;
140 AppWindow::BoundsSpecification::BoundsSpecification()
141 : bounds(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0) {}
143 AppWindow::BoundsSpecification::~BoundsSpecification() {}
145 void AppWindow::BoundsSpecification::ResetBounds() {
146 bounds
.SetRect(kUnspecifiedPosition
, kUnspecifiedPosition
, 0, 0);
149 // AppWindow::CreateParams
151 AppWindow::CreateParams::CreateParams()
152 : window_type(AppWindow::WINDOW_TYPE_DEFAULT
),
153 frame(AppWindow::FRAME_CHROME
),
154 has_frame_color(false),
155 transparent_background(false),
156 creator_process_id(0),
157 state(ui::SHOW_STATE_DEFAULT
),
161 always_on_top(false) {}
163 AppWindow::CreateParams::~CreateParams() {}
165 gfx::Rect
AppWindow::CreateParams::GetInitialWindowBounds(
166 const gfx::Insets
& frame_insets
) const {
167 // Combine into a single window bounds.
168 gfx::Rect
combined_bounds(window_spec
.bounds
);
169 if (content_spec
.bounds
.x() != BoundsSpecification::kUnspecifiedPosition
)
170 combined_bounds
.set_x(content_spec
.bounds
.x() - frame_insets
.left());
171 if (content_spec
.bounds
.y() != BoundsSpecification::kUnspecifiedPosition
)
172 combined_bounds
.set_y(content_spec
.bounds
.y() - frame_insets
.top());
173 if (content_spec
.bounds
.width() > 0) {
174 combined_bounds
.set_width(
175 content_spec
.bounds
.width() + frame_insets
.width());
177 if (content_spec
.bounds
.height() > 0) {
178 combined_bounds
.set_height(
179 content_spec
.bounds
.height() + frame_insets
.height());
182 // Constrain the bounds.
183 SizeConstraints
constraints(
184 GetCombinedWindowConstraints(
185 window_spec
.minimum_size
, content_spec
.minimum_size
, frame_insets
),
186 GetCombinedWindowConstraints(
187 window_spec
.maximum_size
, content_spec
.maximum_size
, frame_insets
));
188 combined_bounds
.set_size(constraints
.ClampSize(combined_bounds
.size()));
190 return combined_bounds
;
193 gfx::Size
AppWindow::CreateParams::GetContentMinimumSize(
194 const gfx::Insets
& frame_insets
) const {
195 return GetCombinedContentConstraints(window_spec
.minimum_size
,
196 content_spec
.minimum_size
,
200 gfx::Size
AppWindow::CreateParams::GetContentMaximumSize(
201 const gfx::Insets
& frame_insets
) const {
202 return GetCombinedContentConstraints(window_spec
.maximum_size
,
203 content_spec
.maximum_size
,
207 gfx::Size
AppWindow::CreateParams::GetWindowMinimumSize(
208 const gfx::Insets
& frame_insets
) const {
209 return GetCombinedWindowConstraints(window_spec
.minimum_size
,
210 content_spec
.minimum_size
,
214 gfx::Size
AppWindow::CreateParams::GetWindowMaximumSize(
215 const gfx::Insets
& frame_insets
) const {
216 return GetCombinedWindowConstraints(window_spec
.maximum_size
,
217 content_spec
.maximum_size
,
221 // AppWindow::Delegate
223 AppWindow::Delegate::~Delegate() {}
227 AppWindow::AppWindow(BrowserContext
* context
,
229 const extensions::Extension
* extension
)
230 : browser_context_(context
),
231 extension_(extension
),
232 extension_id_(extension
->id()),
233 window_type_(WINDOW_TYPE_DEFAULT
),
235 image_loader_ptr_factory_(this),
236 fullscreen_types_(FULLSCREEN_TYPE_NONE
),
237 show_on_first_paint_(false),
238 first_paint_complete_(false),
239 cached_always_on_top_(false) {
240 extensions::ExtensionsBrowserClient
* client
=
241 extensions::ExtensionsBrowserClient::Get();
242 CHECK(!client
->IsGuestSession(context
) || context
->IsOffTheRecord())
243 << "Only off the record window may be opened in the guest mode.";
246 void AppWindow::Init(const GURL
& url
,
247 AppWindowContents
* app_window_contents
,
248 const CreateParams
& params
) {
249 // Initialize the render interface and web contents
250 app_window_contents_
.reset(app_window_contents
);
251 app_window_contents_
->Initialize(browser_context(), url
);
252 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
253 if (CommandLine::ForCurrentProcess()->HasSwitch(
254 switches::kEnableAppsShowOnFirstPaint
)) {
255 content::WebContentsObserver::Observe(web_contents
);
257 delegate_
->InitWebContents(web_contents
);
258 WebContentsModalDialogManager::CreateForWebContents(web_contents
);
259 // TODO(jamescook): Delegate out this creation.
260 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
263 web_contents
->SetDelegate(this);
264 WebContentsModalDialogManager::FromWebContents(web_contents
)
266 extensions::SetViewType(web_contents
, extensions::VIEW_TYPE_APP_WINDOW
);
268 // Initialize the window
269 CreateParams new_params
= LoadDefaults(params
);
270 window_type_
= new_params
.window_type
;
271 window_key_
= new_params
.window_key
;
273 // Windows cannot be always-on-top in fullscreen mode for security reasons.
274 cached_always_on_top_
= new_params
.always_on_top
;
275 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
276 new_params
.always_on_top
= false;
278 native_app_window_
.reset(delegate_
->CreateNativeAppWindow(this, new_params
));
280 if (!new_params
.hidden
) {
281 // Panels are not activated by default.
282 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
286 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
288 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
290 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
293 OnNativeWindowChanged();
295 // When the render view host is changed, the native window needs to know
296 // about it in case it has any setup to do to make the renderer appear
297 // properly. In particular, on Windows, the view's clickthrough region needs
299 extensions::ExtensionsBrowserClient
* client
=
300 extensions::ExtensionsBrowserClient::Get();
302 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
303 content::Source
<content::BrowserContext
>(
304 client
->GetOriginalContext(browser_context_
)));
305 // Close when the browser process is exiting.
307 chrome::NOTIFICATION_APP_TERMINATING
,
308 content::NotificationService::AllSources());
309 // Update the app menu if an ephemeral app becomes installed.
311 chrome::NOTIFICATION_EXTENSION_INSTALLED
,
312 content::Source
<content::BrowserContext
>(
313 client
->GetOriginalContext(browser_context_
)));
315 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
317 if (CommandLine::ForCurrentProcess()->HasSwitch(
318 switches::kEnableAppsShowOnFirstPaint
)) {
319 // We want to show the window only when the content has been painted. For
320 // that to happen, we need to define a size for the content, otherwise the
321 // layout will happen in a 0x0 area.
322 // Note: WebContents::GetView() is guaranteed to be non-null.
323 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
324 gfx::Rect initial_bounds
= new_params
.GetInitialWindowBounds(frame_insets
);
325 initial_bounds
.Inset(frame_insets
);
326 web_contents
->GetView()->SizeContents(initial_bounds
.size());
329 // Prevent the browser process from shutting down while this window is open.
330 AppsClient::Get()->IncrementKeepAliveCount();
332 UpdateExtensionAppIcon();
334 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
337 AppWindow::~AppWindow() {
338 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
340 registrar_
.RemoveAll();
342 // Remove shutdown prevention.
343 AppsClient::Get()->DecrementKeepAliveCount();
346 void AppWindow::RequestMediaAccessPermission(
347 content::WebContents
* web_contents
,
348 const content::MediaStreamRequest
& request
,
349 const content::MediaResponseCallback
& callback
) {
350 delegate_
->RequestMediaAccessPermission(
351 web_contents
, request
, callback
, extension());
354 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
355 const content::OpenURLParams
& params
) {
356 // Don't allow the current tab to be navigated. It would be nice to map all
357 // anchor tags (even those without target="_blank") to new tabs, but right
358 // now we can't distinguish between those and <meta> refreshes or window.href
359 // navigations, which we don't want to allow.
360 // TOOD(mihaip): Can we check for user gestures instead?
361 WindowOpenDisposition disposition
= params
.disposition
;
362 if (disposition
== CURRENT_TAB
) {
363 AddMessageToDevToolsConsole(
364 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
366 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
367 params
.url
.spec().c_str()));
371 // These dispositions aren't really navigations.
372 if (disposition
== SUPPRESS_OPEN
|| disposition
== SAVE_TO_DISK
||
373 disposition
== IGNORE_ACTION
) {
377 WebContents
* contents
=
378 delegate_
->OpenURLFromTab(browser_context_
, source
, params
);
380 AddMessageToDevToolsConsole(
381 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
383 "Can't navigate to \"%s\"; apps do not support navigation.",
384 params
.url
.spec().c_str()));
390 void AppWindow::AddNewContents(WebContents
* source
,
391 WebContents
* new_contents
,
392 WindowOpenDisposition disposition
,
393 const gfx::Rect
& initial_pos
,
396 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
397 delegate_
->AddNewContents(browser_context_
,
405 bool AppWindow::PreHandleKeyboardEvent(
406 content::WebContents
* source
,
407 const content::NativeWebKeyboardEvent
& event
,
408 bool* is_keyboard_shortcut
) {
409 // Here, we can handle a key event before the content gets it. When we are
410 // fullscreen and it is not forced, we want to allow the user to leave
411 // when ESC is pressed.
412 // However, if the application has the "overrideEscFullscreen" permission, we
413 // should let it override that behavior.
414 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
415 // action is not prevented.
416 // Thus, we should handle the KeyEvent here only if the permission is not set.
417 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&&
418 (fullscreen_types_
!= FULLSCREEN_TYPE_NONE
) &&
419 ((fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) == 0) &&
420 !extension_
->HasAPIPermission(APIPermission::kOverrideEscFullscreen
)) {
428 void AppWindow::HandleKeyboardEvent(
430 const content::NativeWebKeyboardEvent
& event
) {
431 // If the window is currently fullscreen and not forced, ESC should leave
432 // fullscreen. If this code is being called for ESC, that means that the
433 // KeyEvent's default behavior was not prevented by the content.
434 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&&
435 (fullscreen_types_
!= FULLSCREEN_TYPE_NONE
) &&
436 ((fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) == 0)) {
441 native_app_window_
->HandleKeyboardEvent(event
);
444 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
446 bool last_unlocked_by_target
) {
447 bool has_permission
= IsExtensionWithPermissionOrSuggestInConsole(
448 APIPermission::kPointerLock
,
450 web_contents
->GetRenderViewHost());
452 web_contents
->GotResponseToLockMouseRequest(has_permission
);
455 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
456 const blink::WebGestureEvent
& event
) {
457 // Disable pinch zooming in app windows.
458 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
459 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
460 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
463 void AppWindow::DidFirstVisuallyNonEmptyPaint(int32 page_id
) {
464 first_paint_complete_
= true;
465 if (show_on_first_paint_
) {
466 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
467 delayed_show_type_
== SHOW_INACTIVE
);
468 Show(delayed_show_type_
);
472 void AppWindow::OnNativeClose() {
473 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
474 if (app_window_contents_
) {
475 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
476 WebContentsModalDialogManager::FromWebContents(web_contents
)
478 app_window_contents_
->NativeWindowClosed();
483 void AppWindow::OnNativeWindowChanged() {
484 SaveWindowPosition();
487 if (native_app_window_
&& cached_always_on_top_
&&
488 !IsFullscreen(fullscreen_types_
) && !native_app_window_
->IsMaximized() &&
489 !native_app_window_
->IsMinimized()) {
490 UpdateNativeAlwaysOnTop();
494 if (app_window_contents_
&& native_app_window_
)
495 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
498 void AppWindow::OnNativeWindowActivated() {
499 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
502 content::WebContents
* AppWindow::web_contents() const {
503 return app_window_contents_
->GetWebContents();
506 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
508 gfx::NativeWindow
AppWindow::GetNativeWindow() {
509 return GetBaseWindow()->GetNativeWindow();
512 gfx::Rect
AppWindow::GetClientBounds() const {
513 gfx::Rect bounds
= native_app_window_
->GetBounds();
514 bounds
.Inset(native_app_window_
->GetFrameInsets());
518 base::string16
AppWindow::GetTitle() const {
519 // WebContents::GetTitle() will return the page's URL if there's no <title>
520 // specified. However, we'd prefer to show the name of the extension in that
521 // case, so we directly inspect the NavigationEntry's title.
522 base::string16 title
;
523 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
524 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
525 title
= base::UTF8ToUTF16(extension()->name());
527 title
= web_contents()->GetTitle();
529 const base::char16 kBadChars
[] = {'\n', 0};
530 base::RemoveChars(title
, kBadChars
, &title
);
534 void AppWindow::SetAppIconUrl(const GURL
& url
) {
535 // If the same url is being used for the badge, ignore it.
536 if (url
== badge_icon_url_
)
539 // Avoid using any previous icons that were being downloaded.
540 image_loader_ptr_factory_
.InvalidateWeakPtrs();
542 // Reset |app_icon_image_| to abort pending image load (if any).
543 app_icon_image_
.reset();
546 web_contents()->DownloadImage(
548 true, // is a favicon
549 0, // no maximum size
550 base::Bind(&AppWindow::DidDownloadFavicon
,
551 image_loader_ptr_factory_
.GetWeakPtr()));
554 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
555 // Avoid using any previous icons that were being downloaded.
556 image_loader_ptr_factory_
.InvalidateWeakPtrs();
558 // Reset |app_icon_image_| to abort pending image load (if any).
559 badge_icon_image_
.reset();
561 badge_icon_url_
= url
;
562 web_contents()->DownloadImage(
564 true, // is a favicon
565 0, // no maximum size
566 base::Bind(&AppWindow::DidDownloadFavicon
,
567 image_loader_ptr_factory_
.GetWeakPtr()));
570 void AppWindow::ClearBadge() {
571 badge_icon_image_
.reset();
572 badge_icon_url_
= GURL();
573 UpdateBadgeIcon(gfx::Image());
576 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
577 native_app_window_
->UpdateShape(region
.Pass());
580 void AppWindow::UpdateDraggableRegions(
581 const std::vector
<extensions::DraggableRegion
>& regions
) {
582 native_app_window_
->UpdateDraggableRegions(regions
);
585 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
589 native_app_window_
->UpdateWindowIcon();
590 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
593 void AppWindow::Fullscreen() {
594 #if !defined(OS_MACOSX)
595 // Do not enter fullscreen mode if disallowed by pref.
597 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
599 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
602 fullscreen_types_
|= FULLSCREEN_TYPE_WINDOW_API
;
603 SetNativeWindowFullscreen();
606 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
608 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
610 void AppWindow::Restore() {
611 if (IsFullscreen(fullscreen_types_
)) {
612 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
613 SetNativeWindowFullscreen();
615 GetBaseWindow()->Restore();
619 void AppWindow::OSFullscreen() {
620 #if !defined(OS_MACOSX)
621 // Do not enter fullscreen mode if disallowed by pref.
623 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
625 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
628 fullscreen_types_
|= FULLSCREEN_TYPE_OS
;
629 SetNativeWindowFullscreen();
632 void AppWindow::ForcedFullscreen() {
633 fullscreen_types_
|= FULLSCREEN_TYPE_FORCED
;
634 SetNativeWindowFullscreen();
637 void AppWindow::SetContentSizeConstraints(const gfx::Size
& min_size
,
638 const gfx::Size
& max_size
) {
639 SizeConstraints
constraints(min_size
, max_size
);
640 native_app_window_
->SetContentSizeConstraints(constraints
.GetMinimumSize(),
641 constraints
.GetMaximumSize());
643 gfx::Rect bounds
= GetClientBounds();
644 gfx::Size constrained_size
= constraints
.ClampSize(bounds
.size());
645 if (bounds
.size() != constrained_size
) {
646 bounds
.set_size(constrained_size
);
647 bounds
.Inset(-native_app_window_
->GetFrameInsets());
648 native_app_window_
->SetBounds(bounds
);
650 OnNativeWindowChanged();
653 void AppWindow::Show(ShowType show_type
) {
654 if (CommandLine::ForCurrentProcess()->HasSwitch(
655 switches::kEnableAppsShowOnFirstPaint
)) {
656 show_on_first_paint_
= true;
658 if (!first_paint_complete_
) {
659 delayed_show_type_
= show_type
;
666 GetBaseWindow()->Show();
669 GetBaseWindow()->ShowInactive();
674 void AppWindow::Hide() {
675 // This is there to prevent race conditions with Hide() being called before
676 // there was a non-empty paint. It should have no effect in a non-racy
677 // scenario where the application is hiding then showing a window: the second
678 // show will not be delayed.
679 show_on_first_paint_
= false;
680 GetBaseWindow()->Hide();
683 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
684 if (cached_always_on_top_
== always_on_top
)
687 cached_always_on_top_
= always_on_top
;
689 // As a security measure, do not allow fullscreen windows or windows that
690 // overlap the taskbar to be on top. The property will be applied when the
691 // window exits fullscreen and moves away from the taskbar.
692 if (!IsFullscreen(fullscreen_types_
) && !IntersectsWithTaskbar())
693 native_app_window_
->SetAlwaysOnTop(always_on_top
);
695 OnNativeWindowChanged();
698 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
700 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
703 properties
->SetBoolean("fullscreen",
704 native_app_window_
->IsFullscreenOrPending());
705 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
706 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
707 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
708 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
709 properties
->SetInteger("frameColor", native_app_window_
->FrameColor());
711 gfx::Rect content_bounds
= GetClientBounds();
712 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
713 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
714 SetBoundsProperties(content_bounds
,
720 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
721 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
722 gfx::Size frame_min_size
=
723 SizeConstraints::AddFrameToConstraints(content_min_size
, frame_insets
);
724 gfx::Size frame_max_size
=
725 SizeConstraints::AddFrameToConstraints(content_max_size
, frame_insets
);
726 SetBoundsProperties(frame_bounds
,
733 //------------------------------------------------------------------------------
736 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
738 native_app_window_
->UpdateBadgeIcon();
741 void AppWindow::DidDownloadFavicon(
743 int http_status_code
,
744 const GURL
& image_url
,
745 const std::vector
<SkBitmap
>& bitmaps
,
746 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
747 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
752 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
753 // whose height >= the preferred size.
754 int largest_index
= 0;
755 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
756 if (bitmaps
[i
].height() < delegate_
->PreferredIconSize())
760 const SkBitmap
& largest
= bitmaps
[largest_index
];
761 if (image_url
== app_icon_url_
) {
762 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
766 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
769 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage
* image
) {
770 DCHECK_EQ(app_icon_image_
.get(), image
);
772 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
775 void AppWindow::UpdateExtensionAppIcon() {
776 // Avoid using any previous app icons were being downloaded.
777 image_loader_ptr_factory_
.InvalidateWeakPtrs();
779 app_icon_image_
.reset(
780 new extensions::IconImage(browser_context(),
782 extensions::IconsInfo::GetIcons(extension()),
783 delegate_
->PreferredIconSize(),
784 extensions::IconsInfo::GetDefaultAppIcon(),
787 // Triggers actual image loading with 1x resources. The 2x resource will
788 // be handled by IconImage class when requested.
789 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
792 void AppWindow::SetNativeWindowFullscreen() {
793 native_app_window_
->SetFullscreen(fullscreen_types_
);
795 if (cached_always_on_top_
)
796 UpdateNativeAlwaysOnTop();
799 bool AppWindow::IntersectsWithTaskbar() const {
801 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
802 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
803 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
805 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
806 it
!= displays
.end();
808 gfx::Rect taskbar_bounds
= it
->bounds();
809 taskbar_bounds
.Subtract(it
->work_area());
810 if (taskbar_bounds
.IsEmpty())
813 if (window_bounds
.Intersects(taskbar_bounds
))
821 void AppWindow::UpdateNativeAlwaysOnTop() {
822 DCHECK(cached_always_on_top_
);
823 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
824 bool fullscreen
= IsFullscreen(fullscreen_types_
);
825 bool intersects_taskbar
= IntersectsWithTaskbar();
827 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
828 // When entering fullscreen or overlapping the taskbar, ensure windows are
829 // not always-on-top.
830 native_app_window_
->SetAlwaysOnTop(false);
831 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
832 // When exiting fullscreen and moving away from the taskbar, reinstate
834 native_app_window_
->SetAlwaysOnTop(true);
838 void AppWindow::CloseContents(WebContents
* contents
) {
839 native_app_window_
->Close();
842 bool AppWindow::ShouldSuppressDialogs() { return true; }
844 content::ColorChooser
* AppWindow::OpenColorChooser(
845 WebContents
* web_contents
,
846 SkColor initial_color
,
847 const std::vector
<content::ColorSuggestion
>& suggestionss
) {
848 return delegate_
->ShowColorChooser(web_contents
, initial_color
);
851 void AppWindow::RunFileChooser(WebContents
* tab
,
852 const content::FileChooserParams
& params
) {
853 if (window_type_is_panel()) {
854 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
855 // dialogs to be unhosted but still close with the owning web contents.
857 LOG(WARNING
) << "File dialog opened by panel.";
861 delegate_
->RunFileChooser(tab
, params
);
864 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
866 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
867 native_app_window_
->SetBounds(pos
);
870 void AppWindow::NavigationStateChanged(const content::WebContents
* source
,
871 unsigned changed_flags
) {
872 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
873 native_app_window_
->UpdateWindowTitle();
874 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
875 native_app_window_
->UpdateWindowIcon();
878 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
879 bool enter_fullscreen
) {
880 #if !defined(OS_MACOSX)
881 // Do not enter fullscreen mode if disallowed by pref.
882 // TODO(bartfab): Add a test once it becomes possible to simulate a user
883 // gesture. http://crbug.com/174178
885 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
887 if (enter_fullscreen
&& !prefs
->GetBoolean(prefs::kAppFullscreenAllowed
)) {
892 if (!IsExtensionWithPermissionOrSuggestInConsole(
893 APIPermission::kFullscreen
,
895 source
->GetRenderViewHost())) {
899 if (enter_fullscreen
)
900 fullscreen_types_
|= FULLSCREEN_TYPE_HTML_API
;
902 fullscreen_types_
&= ~FULLSCREEN_TYPE_HTML_API
;
903 SetNativeWindowFullscreen();
906 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
908 return ((fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0);
911 void AppWindow::Observe(int type
,
912 const content::NotificationSource
& source
,
913 const content::NotificationDetails
& details
) {
915 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
: {
916 const extensions::Extension
* unloaded_extension
=
917 content::Details
<extensions::UnloadedExtensionInfo
>(details
)
919 if (extension_
== unloaded_extension
)
920 native_app_window_
->Close();
923 case chrome::NOTIFICATION_EXTENSION_INSTALLED
: {
924 const extensions::Extension
* installed_extension
=
925 content::Details
<const extensions::InstalledExtensionInfo
>(details
)
927 DCHECK(installed_extension
);
928 if (installed_extension
->id() == extension_
->id())
929 native_app_window_
->UpdateShelfMenu();
932 case chrome::NOTIFICATION_APP_TERMINATING
:
933 native_app_window_
->Close();
936 NOTREACHED() << "Received unexpected notification";
940 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
942 delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
945 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
946 return delegate_
->IsWebContentsVisible(web_contents
);
949 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
950 return native_app_window_
.get();
953 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level
,
954 const std::string
& message
) {
955 content::RenderViewHost
* rvh
= web_contents()->GetRenderViewHost();
956 rvh
->Send(new ExtensionMsg_AddMessageToConsole(
957 rvh
->GetRoutingID(), level
, message
));
960 void AppWindow::SaveWindowPosition() {
961 if (window_key_
.empty())
963 if (!native_app_window_
)
966 AppWindowGeometryCache
* cache
=
967 AppWindowGeometryCache::Get(browser_context());
969 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
970 gfx::Rect screen_bounds
=
971 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
972 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
974 extension()->id(), window_key_
, bounds
, screen_bounds
, window_state
);
977 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
978 const gfx::Rect
& cached_bounds
,
979 const gfx::Rect
& cached_screen_bounds
,
980 const gfx::Rect
& current_screen_bounds
,
981 const gfx::Size
& minimum_size
,
982 gfx::Rect
* bounds
) const {
983 *bounds
= cached_bounds
;
985 // Reposition and resize the bounds if the cached_screen_bounds is different
986 // from the current screen bounds and the current screen bounds doesn't
987 // completely contain the bounds.
988 if (cached_screen_bounds
!= current_screen_bounds
&&
989 !current_screen_bounds
.Contains(cached_bounds
)) {
991 std::max(minimum_size
.width(),
992 std::min(bounds
->width(), current_screen_bounds
.width())));
994 std::max(minimum_size
.height(),
995 std::min(bounds
->height(), current_screen_bounds
.height())));
997 std::max(current_screen_bounds
.x(),
998 std::min(bounds
->x(),
999 current_screen_bounds
.right() - bounds
->width())));
1001 std::max(current_screen_bounds
.y(),
1002 std::min(bounds
->y(),
1003 current_screen_bounds
.bottom() - bounds
->height())));
1007 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1009 // Ensure width and height are specified.
1010 if (params
.content_spec
.bounds
.width() == 0 &&
1011 params
.window_spec
.bounds
.width() == 0) {
1012 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1014 if (params
.content_spec
.bounds
.height() == 0 &&
1015 params
.window_spec
.bounds
.height() == 0) {
1016 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1019 // If left and top are left undefined, the native app window will center
1020 // the window on the main screen in a platform-defined manner.
1022 // Load cached state if it exists.
1023 if (!params
.window_key
.empty()) {
1024 AppWindowGeometryCache
* cache
=
1025 AppWindowGeometryCache::Get(browser_context());
1027 gfx::Rect cached_bounds
;
1028 gfx::Rect cached_screen_bounds
;
1029 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1030 if (cache
->GetGeometry(extension()->id(),
1033 &cached_screen_bounds
,
1036 // App window has cached screen bounds, make sure it fits on screen in
1037 // case the screen resolution changed.
1038 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1039 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1040 gfx::Rect current_screen_bounds
= display
.work_area();
1041 SizeConstraints
constraints(params
.GetWindowMinimumSize(gfx::Insets()),
1042 params
.GetWindowMaximumSize(gfx::Insets()));
1043 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1044 cached_screen_bounds
,
1045 current_screen_bounds
,
1046 constraints
.GetMinimumSize(),
1047 ¶ms
.window_spec
.bounds
);
1048 params
.state
= cached_state
;
1050 // Since we are restoring a cached state, reset the content bounds spec to
1051 // ensure it is not used.
1052 params
.content_spec
.ResetBounds();
1060 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1061 const std::vector
<extensions::DraggableRegion
>& regions
) {
1062 SkRegion
* sk_region
= new SkRegion
;
1063 for (std::vector
<extensions::DraggableRegion
>::const_iterator iter
=
1065 iter
!= regions
.end();
1067 const extensions::DraggableRegion
& region
= *iter
;
1071 region
.bounds
.right(),
1072 region
.bounds
.bottom(),
1073 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);