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/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 extensions::ExtensionWebContentsObserver::CreateForWebContents(web_contents
);
261 web_contents
->SetDelegate(this);
262 WebContentsModalDialogManager::FromWebContents(web_contents
)
264 extensions::SetViewType(web_contents
, extensions::VIEW_TYPE_APP_WINDOW
);
266 // Initialize the window
267 CreateParams new_params
= LoadDefaults(params
);
268 window_type_
= new_params
.window_type
;
269 window_key_
= new_params
.window_key
;
271 // Windows cannot be always-on-top in fullscreen mode for security reasons.
272 cached_always_on_top_
= new_params
.always_on_top
;
273 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
274 new_params
.always_on_top
= false;
276 native_app_window_
.reset(delegate_
->CreateNativeAppWindow(this, new_params
));
278 if (!new_params
.hidden
) {
279 // Panels are not activated by default.
280 Show(window_type_is_panel() || !new_params
.focused
? SHOW_INACTIVE
284 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
286 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
288 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
291 OnNativeWindowChanged();
293 // When the render view host is changed, the native window needs to know
294 // about it in case it has any setup to do to make the renderer appear
295 // properly. In particular, on Windows, the view's clickthrough region needs
297 extensions::ExtensionsBrowserClient
* client
=
298 extensions::ExtensionsBrowserClient::Get();
300 chrome::NOTIFICATION_EXTENSION_UNLOADED
,
301 content::Source
<content::BrowserContext
>(
302 client
->GetOriginalContext(browser_context_
)));
303 // Close when the browser process is exiting.
305 chrome::NOTIFICATION_APP_TERMINATING
,
306 content::NotificationService::AllSources());
307 // Update the app menu if an ephemeral app becomes installed.
309 chrome::NOTIFICATION_EXTENSION_INSTALLED
,
310 content::Source
<content::BrowserContext
>(
311 client
->GetOriginalContext(browser_context_
)));
313 app_window_contents_
->LoadContents(new_params
.creator_process_id
);
315 if (CommandLine::ForCurrentProcess()->HasSwitch(
316 switches::kEnableAppsShowOnFirstPaint
)) {
317 // We want to show the window only when the content has been painted. For
318 // that to happen, we need to define a size for the content, otherwise the
319 // layout will happen in a 0x0 area.
320 // Note: WebContents::GetView() is guaranteed to be non-null.
321 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
322 gfx::Rect initial_bounds
= new_params
.GetInitialWindowBounds(frame_insets
);
323 initial_bounds
.Inset(frame_insets
);
324 web_contents
->GetView()->SizeContents(initial_bounds
.size());
327 // Prevent the browser process from shutting down while this window is open.
328 AppsClient::Get()->IncrementKeepAliveCount();
330 UpdateExtensionAppIcon();
332 AppWindowRegistry::Get(browser_context_
)->AddAppWindow(this);
335 AppWindow::~AppWindow() {
336 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
338 registrar_
.RemoveAll();
340 // Remove shutdown prevention.
341 AppsClient::Get()->DecrementKeepAliveCount();
344 void AppWindow::RequestMediaAccessPermission(
345 content::WebContents
* web_contents
,
346 const content::MediaStreamRequest
& request
,
347 const content::MediaResponseCallback
& callback
) {
348 delegate_
->RequestMediaAccessPermission(
349 web_contents
, request
, callback
, extension());
352 WebContents
* AppWindow::OpenURLFromTab(WebContents
* source
,
353 const content::OpenURLParams
& params
) {
354 // Don't allow the current tab to be navigated. It would be nice to map all
355 // anchor tags (even those without target="_blank") to new tabs, but right
356 // now we can't distinguish between those and <meta> refreshes or window.href
357 // navigations, which we don't want to allow.
358 // TOOD(mihaip): Can we check for user gestures instead?
359 WindowOpenDisposition disposition
= params
.disposition
;
360 if (disposition
== CURRENT_TAB
) {
361 AddMessageToDevToolsConsole(
362 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
364 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
365 params
.url
.spec().c_str()));
369 // These dispositions aren't really navigations.
370 if (disposition
== SUPPRESS_OPEN
|| disposition
== SAVE_TO_DISK
||
371 disposition
== IGNORE_ACTION
) {
375 WebContents
* contents
=
376 delegate_
->OpenURLFromTab(browser_context_
, source
, params
);
378 AddMessageToDevToolsConsole(
379 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
381 "Can't navigate to \"%s\"; apps do not support navigation.",
382 params
.url
.spec().c_str()));
388 void AppWindow::AddNewContents(WebContents
* source
,
389 WebContents
* new_contents
,
390 WindowOpenDisposition disposition
,
391 const gfx::Rect
& initial_pos
,
394 DCHECK(new_contents
->GetBrowserContext() == browser_context_
);
395 delegate_
->AddNewContents(browser_context_
,
403 bool AppWindow::PreHandleKeyboardEvent(
404 content::WebContents
* source
,
405 const content::NativeWebKeyboardEvent
& event
,
406 bool* is_keyboard_shortcut
) {
407 // Here, we can handle a key event before the content gets it. When we are
408 // fullscreen and it is not forced, we want to allow the user to leave
409 // when ESC is pressed.
410 // However, if the application has the "overrideEscFullscreen" permission, we
411 // should let it override that behavior.
412 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
413 // action is not prevented.
414 // Thus, we should handle the KeyEvent here only if the permission is not set.
415 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&&
416 (fullscreen_types_
!= FULLSCREEN_TYPE_NONE
) &&
417 ((fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) == 0) &&
418 !extension_
->HasAPIPermission(APIPermission::kOverrideEscFullscreen
)) {
426 void AppWindow::HandleKeyboardEvent(
428 const content::NativeWebKeyboardEvent
& event
) {
429 // If the window is currently fullscreen and not forced, ESC should leave
430 // fullscreen. If this code is being called for ESC, that means that the
431 // KeyEvent's default behavior was not prevented by the content.
432 if (event
.windowsKeyCode
== ui::VKEY_ESCAPE
&&
433 (fullscreen_types_
!= FULLSCREEN_TYPE_NONE
) &&
434 ((fullscreen_types_
& FULLSCREEN_TYPE_FORCED
) == 0)) {
439 native_app_window_
->HandleKeyboardEvent(event
);
442 void AppWindow::RequestToLockMouse(WebContents
* web_contents
,
444 bool last_unlocked_by_target
) {
445 bool has_permission
= IsExtensionWithPermissionOrSuggestInConsole(
446 APIPermission::kPointerLock
,
448 web_contents
->GetRenderViewHost());
450 web_contents
->GotResponseToLockMouseRequest(has_permission
);
453 bool AppWindow::PreHandleGestureEvent(WebContents
* source
,
454 const blink::WebGestureEvent
& event
) {
455 // Disable pinch zooming in app windows.
456 return event
.type
== blink::WebGestureEvent::GesturePinchBegin
||
457 event
.type
== blink::WebGestureEvent::GesturePinchUpdate
||
458 event
.type
== blink::WebGestureEvent::GesturePinchEnd
;
461 void AppWindow::DidFirstVisuallyNonEmptyPaint(int32 page_id
) {
462 first_paint_complete_
= true;
463 if (show_on_first_paint_
) {
464 DCHECK(delayed_show_type_
== SHOW_ACTIVE
||
465 delayed_show_type_
== SHOW_INACTIVE
);
466 Show(delayed_show_type_
);
470 void AppWindow::OnNativeClose() {
471 AppWindowRegistry::Get(browser_context_
)->RemoveAppWindow(this);
472 if (app_window_contents_
) {
473 WebContents
* web_contents
= app_window_contents_
->GetWebContents();
474 WebContentsModalDialogManager::FromWebContents(web_contents
)
476 app_window_contents_
->NativeWindowClosed();
481 void AppWindow::OnNativeWindowChanged() {
482 SaveWindowPosition();
485 if (native_app_window_
&& cached_always_on_top_
&&
486 !IsFullscreen(fullscreen_types_
) && !native_app_window_
->IsMaximized() &&
487 !native_app_window_
->IsMinimized()) {
488 UpdateNativeAlwaysOnTop();
492 if (app_window_contents_
&& native_app_window_
)
493 app_window_contents_
->NativeWindowChanged(native_app_window_
.get());
496 void AppWindow::OnNativeWindowActivated() {
497 AppWindowRegistry::Get(browser_context_
)->AppWindowActivated(this);
500 content::WebContents
* AppWindow::web_contents() const {
501 return app_window_contents_
->GetWebContents();
504 NativeAppWindow
* AppWindow::GetBaseWindow() { return native_app_window_
.get(); }
506 gfx::NativeWindow
AppWindow::GetNativeWindow() {
507 return GetBaseWindow()->GetNativeWindow();
510 gfx::Rect
AppWindow::GetClientBounds() const {
511 gfx::Rect bounds
= native_app_window_
->GetBounds();
512 bounds
.Inset(native_app_window_
->GetFrameInsets());
516 base::string16
AppWindow::GetTitle() const {
517 // WebContents::GetTitle() will return the page's URL if there's no <title>
518 // specified. However, we'd prefer to show the name of the extension in that
519 // case, so we directly inspect the NavigationEntry's title.
520 base::string16 title
;
521 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
522 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
523 title
= base::UTF8ToUTF16(extension()->name());
525 title
= web_contents()->GetTitle();
527 const base::char16 kBadChars
[] = {'\n', 0};
528 base::RemoveChars(title
, kBadChars
, &title
);
532 void AppWindow::SetAppIconUrl(const GURL
& url
) {
533 // If the same url is being used for the badge, ignore it.
534 if (url
== badge_icon_url_
)
537 // Avoid using any previous icons that were being downloaded.
538 image_loader_ptr_factory_
.InvalidateWeakPtrs();
540 // Reset |app_icon_image_| to abort pending image load (if any).
541 app_icon_image_
.reset();
544 web_contents()->DownloadImage(
546 true, // is a favicon
547 0, // no maximum size
548 base::Bind(&AppWindow::DidDownloadFavicon
,
549 image_loader_ptr_factory_
.GetWeakPtr()));
552 void AppWindow::SetBadgeIconUrl(const GURL
& url
) {
553 // Avoid using any previous icons that were being downloaded.
554 image_loader_ptr_factory_
.InvalidateWeakPtrs();
556 // Reset |app_icon_image_| to abort pending image load (if any).
557 badge_icon_image_
.reset();
559 badge_icon_url_
= url
;
560 web_contents()->DownloadImage(
562 true, // is a favicon
563 0, // no maximum size
564 base::Bind(&AppWindow::DidDownloadFavicon
,
565 image_loader_ptr_factory_
.GetWeakPtr()));
568 void AppWindow::ClearBadge() {
569 badge_icon_image_
.reset();
570 badge_icon_url_
= GURL();
571 UpdateBadgeIcon(gfx::Image());
574 void AppWindow::UpdateShape(scoped_ptr
<SkRegion
> region
) {
575 native_app_window_
->UpdateShape(region
.Pass());
578 void AppWindow::UpdateDraggableRegions(
579 const std::vector
<extensions::DraggableRegion
>& regions
) {
580 native_app_window_
->UpdateDraggableRegions(regions
);
583 void AppWindow::UpdateAppIcon(const gfx::Image
& image
) {
587 native_app_window_
->UpdateWindowIcon();
588 AppWindowRegistry::Get(browser_context_
)->AppWindowIconChanged(this);
591 void AppWindow::Fullscreen() {
592 #if !defined(OS_MACOSX)
593 // Do not enter fullscreen mode if disallowed by pref.
595 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
597 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
600 fullscreen_types_
|= FULLSCREEN_TYPE_WINDOW_API
;
601 SetNativeWindowFullscreen();
604 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
606 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
608 void AppWindow::Restore() {
609 if (IsFullscreen(fullscreen_types_
)) {
610 fullscreen_types_
= FULLSCREEN_TYPE_NONE
;
611 SetNativeWindowFullscreen();
613 GetBaseWindow()->Restore();
617 void AppWindow::OSFullscreen() {
618 #if !defined(OS_MACOSX)
619 // Do not enter fullscreen mode if disallowed by pref.
621 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
623 if (!prefs
->GetBoolean(prefs::kAppFullscreenAllowed
))
626 fullscreen_types_
|= FULLSCREEN_TYPE_OS
;
627 SetNativeWindowFullscreen();
630 void AppWindow::ForcedFullscreen() {
631 fullscreen_types_
|= FULLSCREEN_TYPE_FORCED
;
632 SetNativeWindowFullscreen();
635 void AppWindow::SetContentMinimumSize(const gfx::Size
& min_size
) {
636 native_app_window_
->SetContentMinimumSize(min_size
);
637 OnSizeConstraintsChanged();
640 void AppWindow::SetContentMaximumSize(const gfx::Size
& max_size
) {
641 native_app_window_
->SetContentMaximumSize(max_size
);
642 OnSizeConstraintsChanged();
645 void AppWindow::Show(ShowType show_type
) {
646 if (CommandLine::ForCurrentProcess()->HasSwitch(
647 switches::kEnableAppsShowOnFirstPaint
)) {
648 show_on_first_paint_
= true;
650 if (!first_paint_complete_
) {
651 delayed_show_type_
= show_type
;
658 GetBaseWindow()->Show();
661 GetBaseWindow()->ShowInactive();
666 void AppWindow::Hide() {
667 // This is there to prevent race conditions with Hide() being called before
668 // there was a non-empty paint. It should have no effect in a non-racy
669 // scenario where the application is hiding then showing a window: the second
670 // show will not be delayed.
671 show_on_first_paint_
= false;
672 GetBaseWindow()->Hide();
675 void AppWindow::SetAlwaysOnTop(bool always_on_top
) {
676 if (cached_always_on_top_
== always_on_top
)
679 cached_always_on_top_
= always_on_top
;
681 // As a security measure, do not allow fullscreen windows or windows that
682 // overlap the taskbar to be on top. The property will be applied when the
683 // window exits fullscreen and moves away from the taskbar.
684 if (!IsFullscreen(fullscreen_types_
) && !IntersectsWithTaskbar())
685 native_app_window_
->SetAlwaysOnTop(always_on_top
);
687 OnNativeWindowChanged();
690 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_
; }
692 void AppWindow::GetSerializedState(base::DictionaryValue
* properties
) const {
695 properties
->SetBoolean("fullscreen",
696 native_app_window_
->IsFullscreenOrPending());
697 properties
->SetBoolean("minimized", native_app_window_
->IsMinimized());
698 properties
->SetBoolean("maximized", native_app_window_
->IsMaximized());
699 properties
->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
700 properties
->SetBoolean("hasFrameColor", native_app_window_
->HasFrameColor());
701 properties
->SetInteger("frameColor", native_app_window_
->FrameColor());
703 gfx::Rect content_bounds
= GetClientBounds();
704 gfx::Size content_min_size
= native_app_window_
->GetContentMinimumSize();
705 gfx::Size content_max_size
= native_app_window_
->GetContentMaximumSize();
706 SetBoundsProperties(content_bounds
,
712 gfx::Insets frame_insets
= native_app_window_
->GetFrameInsets();
713 gfx::Rect frame_bounds
= native_app_window_
->GetBounds();
714 gfx::Size frame_min_size
=
715 SizeConstraints::AddFrameToConstraints(content_min_size
, frame_insets
);
716 gfx::Size frame_max_size
=
717 SizeConstraints::AddFrameToConstraints(content_max_size
, frame_insets
);
718 SetBoundsProperties(frame_bounds
,
725 //------------------------------------------------------------------------------
728 void AppWindow::UpdateBadgeIcon(const gfx::Image
& image
) {
730 native_app_window_
->UpdateBadgeIcon();
733 void AppWindow::DidDownloadFavicon(
735 int http_status_code
,
736 const GURL
& image_url
,
737 const std::vector
<SkBitmap
>& bitmaps
,
738 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
739 if ((image_url
!= app_icon_url_
&& image_url
!= badge_icon_url_
) ||
744 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
745 // whose height >= the preferred size.
746 int largest_index
= 0;
747 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
748 if (bitmaps
[i
].height() < delegate_
->PreferredIconSize())
752 const SkBitmap
& largest
= bitmaps
[largest_index
];
753 if (image_url
== app_icon_url_
) {
754 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
758 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest
));
761 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage
* image
) {
762 DCHECK_EQ(app_icon_image_
.get(), image
);
764 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
767 void AppWindow::UpdateExtensionAppIcon() {
768 // Avoid using any previous app icons were being downloaded.
769 image_loader_ptr_factory_
.InvalidateWeakPtrs();
771 app_icon_image_
.reset(
772 new extensions::IconImage(browser_context(),
774 extensions::IconsInfo::GetIcons(extension()),
775 delegate_
->PreferredIconSize(),
776 extensions::IconsInfo::GetDefaultAppIcon(),
779 // Triggers actual image loading with 1x resources. The 2x resource will
780 // be handled by IconImage class when requested.
781 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
784 void AppWindow::OnSizeConstraintsChanged() {
785 SizeConstraints
size_constraints(native_app_window_
->GetContentMinimumSize(),
786 native_app_window_
->GetContentMaximumSize());
787 gfx::Rect bounds
= GetClientBounds();
788 gfx::Size constrained_size
= size_constraints
.ClampSize(bounds
.size());
789 if (bounds
.size() != constrained_size
) {
790 bounds
.set_size(constrained_size
);
791 bounds
.Inset(-native_app_window_
->GetFrameInsets());
792 native_app_window_
->SetBounds(bounds
);
794 OnNativeWindowChanged();
797 void AppWindow::SetNativeWindowFullscreen() {
798 native_app_window_
->SetFullscreen(fullscreen_types_
);
800 if (cached_always_on_top_
)
801 UpdateNativeAlwaysOnTop();
804 bool AppWindow::IntersectsWithTaskbar() const {
806 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
807 gfx::Rect window_bounds
= native_app_window_
->GetRestoredBounds();
808 std::vector
<gfx::Display
> displays
= screen
->GetAllDisplays();
810 for (std::vector
<gfx::Display
>::const_iterator it
= displays
.begin();
811 it
!= displays
.end();
813 gfx::Rect taskbar_bounds
= it
->bounds();
814 taskbar_bounds
.Subtract(it
->work_area());
815 if (taskbar_bounds
.IsEmpty())
818 if (window_bounds
.Intersects(taskbar_bounds
))
826 void AppWindow::UpdateNativeAlwaysOnTop() {
827 DCHECK(cached_always_on_top_
);
828 bool is_on_top
= native_app_window_
->IsAlwaysOnTop();
829 bool fullscreen
= IsFullscreen(fullscreen_types_
);
830 bool intersects_taskbar
= IntersectsWithTaskbar();
832 if (is_on_top
&& (fullscreen
|| intersects_taskbar
)) {
833 // When entering fullscreen or overlapping the taskbar, ensure windows are
834 // not always-on-top.
835 native_app_window_
->SetAlwaysOnTop(false);
836 } else if (!is_on_top
&& !fullscreen
&& !intersects_taskbar
) {
837 // When exiting fullscreen and moving away from the taskbar, reinstate
839 native_app_window_
->SetAlwaysOnTop(true);
843 void AppWindow::CloseContents(WebContents
* contents
) {
844 native_app_window_
->Close();
847 bool AppWindow::ShouldSuppressDialogs() { return true; }
849 content::ColorChooser
* AppWindow::OpenColorChooser(
850 WebContents
* web_contents
,
851 SkColor initial_color
,
852 const std::vector
<content::ColorSuggestion
>& suggestionss
) {
853 return delegate_
->ShowColorChooser(web_contents
, initial_color
);
856 void AppWindow::RunFileChooser(WebContents
* tab
,
857 const content::FileChooserParams
& params
) {
858 if (window_type_is_panel()) {
859 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
860 // dialogs to be unhosted but still close with the owning web contents.
862 LOG(WARNING
) << "File dialog opened by panel.";
866 delegate_
->RunFileChooser(tab
, params
);
869 bool AppWindow::IsPopupOrPanel(const WebContents
* source
) const { return true; }
871 void AppWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
872 native_app_window_
->SetBounds(pos
);
875 void AppWindow::NavigationStateChanged(const content::WebContents
* source
,
876 unsigned changed_flags
) {
877 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
878 native_app_window_
->UpdateWindowTitle();
879 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
880 native_app_window_
->UpdateWindowIcon();
883 void AppWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
884 bool enter_fullscreen
) {
885 #if !defined(OS_MACOSX)
886 // Do not enter fullscreen mode if disallowed by pref.
887 // TODO(bartfab): Add a test once it becomes possible to simulate a user
888 // gesture. http://crbug.com/174178
890 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
892 if (enter_fullscreen
&& !prefs
->GetBoolean(prefs::kAppFullscreenAllowed
)) {
897 if (!IsExtensionWithPermissionOrSuggestInConsole(
898 APIPermission::kFullscreen
,
900 source
->GetRenderViewHost())) {
904 if (enter_fullscreen
)
905 fullscreen_types_
|= FULLSCREEN_TYPE_HTML_API
;
907 fullscreen_types_
&= ~FULLSCREEN_TYPE_HTML_API
;
908 SetNativeWindowFullscreen();
911 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents
* source
)
913 return ((fullscreen_types_
& FULLSCREEN_TYPE_HTML_API
) != 0);
916 void AppWindow::Observe(int type
,
917 const content::NotificationSource
& source
,
918 const content::NotificationDetails
& details
) {
920 case chrome::NOTIFICATION_EXTENSION_UNLOADED
: {
921 const extensions::Extension
* unloaded_extension
=
922 content::Details
<extensions::UnloadedExtensionInfo
>(details
)
924 if (extension_
== unloaded_extension
)
925 native_app_window_
->Close();
928 case chrome::NOTIFICATION_EXTENSION_INSTALLED
: {
929 const extensions::Extension
* installed_extension
=
930 content::Details
<const extensions::InstalledExtensionInfo
>(details
)
932 DCHECK(installed_extension
);
933 if (installed_extension
->id() == extension_
->id())
934 native_app_window_
->UpdateShelfMenu();
937 case chrome::NOTIFICATION_APP_TERMINATING
:
938 native_app_window_
->Close();
941 NOTREACHED() << "Received unexpected notification";
945 void AppWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
947 delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
950 bool AppWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
951 return delegate_
->IsWebContentsVisible(web_contents
);
954 WebContentsModalDialogHost
* AppWindow::GetWebContentsModalDialogHost() {
955 return native_app_window_
.get();
958 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level
,
959 const std::string
& message
) {
960 content::RenderViewHost
* rvh
= web_contents()->GetRenderViewHost();
961 rvh
->Send(new ExtensionMsg_AddMessageToConsole(
962 rvh
->GetRoutingID(), level
, message
));
965 void AppWindow::SaveWindowPosition() {
966 if (window_key_
.empty())
968 if (!native_app_window_
)
971 AppWindowGeometryCache
* cache
=
972 AppWindowGeometryCache::Get(browser_context());
974 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
975 gfx::Rect screen_bounds
=
976 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
977 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
979 extension()->id(), window_key_
, bounds
, screen_bounds
, window_state
);
982 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
983 const gfx::Rect
& cached_bounds
,
984 const gfx::Rect
& cached_screen_bounds
,
985 const gfx::Rect
& current_screen_bounds
,
986 const gfx::Size
& minimum_size
,
987 gfx::Rect
* bounds
) const {
988 *bounds
= cached_bounds
;
990 // Reposition and resize the bounds if the cached_screen_bounds is different
991 // from the current screen bounds and the current screen bounds doesn't
992 // completely contain the bounds.
993 if (cached_screen_bounds
!= current_screen_bounds
&&
994 !current_screen_bounds
.Contains(cached_bounds
)) {
996 std::max(minimum_size
.width(),
997 std::min(bounds
->width(), current_screen_bounds
.width())));
999 std::max(minimum_size
.height(),
1000 std::min(bounds
->height(), current_screen_bounds
.height())));
1002 std::max(current_screen_bounds
.x(),
1003 std::min(bounds
->x(),
1004 current_screen_bounds
.right() - bounds
->width())));
1006 std::max(current_screen_bounds
.y(),
1007 std::min(bounds
->y(),
1008 current_screen_bounds
.bottom() - bounds
->height())));
1012 AppWindow::CreateParams
AppWindow::LoadDefaults(CreateParams params
)
1014 // Ensure width and height are specified.
1015 if (params
.content_spec
.bounds
.width() == 0 &&
1016 params
.window_spec
.bounds
.width() == 0) {
1017 params
.content_spec
.bounds
.set_width(kDefaultWidth
);
1019 if (params
.content_spec
.bounds
.height() == 0 &&
1020 params
.window_spec
.bounds
.height() == 0) {
1021 params
.content_spec
.bounds
.set_height(kDefaultHeight
);
1024 // If left and top are left undefined, the native app window will center
1025 // the window on the main screen in a platform-defined manner.
1027 // Load cached state if it exists.
1028 if (!params
.window_key
.empty()) {
1029 AppWindowGeometryCache
* cache
=
1030 AppWindowGeometryCache::Get(browser_context());
1032 gfx::Rect cached_bounds
;
1033 gfx::Rect cached_screen_bounds
;
1034 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
1035 if (cache
->GetGeometry(extension()->id(),
1038 &cached_screen_bounds
,
1041 // App window has cached screen bounds, make sure it fits on screen in
1042 // case the screen resolution changed.
1043 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
1044 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
1045 gfx::Rect current_screen_bounds
= display
.work_area();
1046 SizeConstraints
constraints(params
.GetWindowMinimumSize(gfx::Insets()),
1047 params
.GetWindowMaximumSize(gfx::Insets()));
1048 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
1049 cached_screen_bounds
,
1050 current_screen_bounds
,
1051 constraints
.GetMinimumSize(),
1052 ¶ms
.window_spec
.bounds
);
1053 params
.state
= cached_state
;
1055 // Since we are restoring a cached state, reset the content bounds spec to
1056 // ensure it is not used.
1057 params
.content_spec
.ResetBounds();
1065 SkRegion
* AppWindow::RawDraggableRegionsToSkRegion(
1066 const std::vector
<extensions::DraggableRegion
>& regions
) {
1067 SkRegion
* sk_region
= new SkRegion
;
1068 for (std::vector
<extensions::DraggableRegion
>::const_iterator iter
=
1070 iter
!= regions
.end();
1072 const extensions::DraggableRegion
& region
= *iter
;
1076 region
.bounds
.right(),
1077 region
.bounds
.bottom(),
1078 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);