1 // Copyright 2013 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/shell_window.h"
7 #include "apps/shell_window_geometry_cache.h"
8 #include "apps/shell_window_registry.h"
9 #include "apps/ui/native_app_window.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/values.h"
13 #include "chrome/browser/chrome_notification_types.h"
14 #include "chrome/browser/extensions/extension_process_manager.h"
15 #include "chrome/browser/extensions/extension_system.h"
16 #include "chrome/browser/extensions/suggest_permission_util.h"
17 #include "chrome/browser/lifetime/application_lifetime.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/common/extensions/extension.h"
20 #include "chrome/common/extensions/extension_constants.h"
21 #include "chrome/common/extensions/extension_messages.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/invalidate_type.h"
25 #include "content/public/browser/navigation_entry.h"
26 #include "content/public/browser/notification_details.h"
27 #include "content/public/browser/notification_service.h"
28 #include "content/public/browser/notification_source.h"
29 #include "content/public/browser/notification_types.h"
30 #include "content/public/browser/render_view_host.h"
31 #include "content/public/browser/resource_dispatcher_host.h"
32 #include "content/public/browser/web_contents.h"
33 #include "content/public/common/media_stream_request.h"
34 #include "extensions/browser/view_type_utils.h"
35 #include "skia/ext/image_operations.h"
36 #include "third_party/skia/include/core/SkRegion.h"
37 #include "ui/gfx/image/image_skia.h"
38 #include "ui/gfx/screen.h"
40 #if !defined(OS_MACOSX)
41 #include "apps/pref_names.h"
42 #include "base/prefs/pref_service.h"
45 using content::ConsoleMessageLevel
;
46 using content::WebContents
;
47 using extensions::APIPermission
;
48 using web_modal::WebContentsModalDialogHost
;
49 using web_modal::WebContentsModalDialogManager
;
52 const int kDefaultWidth
= 512;
53 const int kDefaultHeight
= 384;
59 ShellWindow::CreateParams::CreateParams()
60 : window_type(ShellWindow::WINDOW_TYPE_DEFAULT
),
61 frame(ShellWindow::FRAME_CHROME
),
62 transparent_background(false),
63 bounds(INT_MIN
, INT_MIN
, 0, 0),
64 creator_process_id(0),
65 state(ui::SHOW_STATE_DEFAULT
),
69 always_on_top(false) {}
71 ShellWindow::CreateParams::~CreateParams() {}
73 ShellWindow::Delegate::~Delegate() {}
75 ShellWindow::ShellWindow(Profile
* profile
,
77 const extensions::Extension
* extension
)
79 extension_(extension
),
80 extension_id_(extension
->id()),
81 window_type_(WINDOW_TYPE_DEFAULT
),
83 image_loader_ptr_factory_(this),
84 fullscreen_for_window_api_(false),
85 fullscreen_for_tab_(false),
86 is_content_visible_(false) {
89 void ShellWindow::Init(const GURL
& url
,
90 ShellWindowContents
* shell_window_contents
,
91 const CreateParams
& params
) {
92 // Initialize the render interface and web contents
93 shell_window_contents_
.reset(shell_window_contents
);
94 shell_window_contents_
->Initialize(profile(), url
);
95 WebContents
* web_contents
= shell_window_contents_
->GetWebContents();
96 delegate_
->InitWebContents(web_contents
);
97 WebContentsModalDialogManager::CreateForWebContents(web_contents
);
99 web_contents
->SetDelegate(this);
100 WebContentsModalDialogManager::FromWebContents(web_contents
)->
102 extensions::SetViewType(web_contents
, extensions::VIEW_TYPE_APP_SHELL
);
104 // Initialize the window
105 window_type_
= params
.window_type
;
107 gfx::Rect bounds
= params
.bounds
;
109 if (bounds
.width() == 0)
110 bounds
.set_width(kDefaultWidth
);
111 if (bounds
.height() == 0)
112 bounds
.set_height(kDefaultHeight
);
114 // If left and top are left undefined, the native shell window will center
115 // the window on the main screen in a platform-defined manner.
117 CreateParams new_params
= params
;
119 // Load cached state if it exists.
120 if (!params
.window_key
.empty()) {
121 window_key_
= params
.window_key
;
123 ShellWindowGeometryCache
* cache
= ShellWindowGeometryCache::Get(profile());
125 gfx::Rect cached_bounds
;
126 gfx::Rect cached_screen_bounds
;
127 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
128 if (cache
->GetGeometry(extension()->id(), params
.window_key
, &cached_bounds
,
129 &cached_screen_bounds
, &cached_state
)) {
130 // App window has cached screen bounds, make sure it fits on screen in
131 // case the screen resolution changed.
132 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
133 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
134 gfx::Rect current_screen_bounds
= display
.work_area();
135 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
136 cached_screen_bounds
,
137 current_screen_bounds
,
140 new_params
.state
= cached_state
;
144 gfx::Size
& minimum_size
= new_params
.minimum_size
;
145 gfx::Size
& maximum_size
= new_params
.maximum_size
;
147 // In the case that minimum size > maximum size, we consider the minimum
148 // size to be more important.
149 if (maximum_size
.width() && maximum_size
.width() < minimum_size
.width())
150 maximum_size
.set_width(minimum_size
.width());
151 if (maximum_size
.height() && maximum_size
.height() < minimum_size
.height())
152 maximum_size
.set_height(minimum_size
.height());
154 if (maximum_size
.width() && bounds
.width() > maximum_size
.width())
155 bounds
.set_width(maximum_size
.width());
156 if (bounds
.width() != INT_MIN
&& bounds
.width() < minimum_size
.width())
157 bounds
.set_width(minimum_size
.width());
159 if (maximum_size
.height() && bounds
.height() > maximum_size
.height())
160 bounds
.set_height(maximum_size
.height());
161 if (bounds
.height() != INT_MIN
&& bounds
.height() < minimum_size
.height())
162 bounds
.set_height(minimum_size
.height());
164 new_params
.bounds
= bounds
;
166 native_app_window_
.reset(delegate_
->CreateNativeAppWindow(this, new_params
));
168 if (!new_params
.hidden
) {
169 if (window_type_is_panel())
170 GetBaseWindow()->ShowInactive(); // Panels are not activated by default.
172 GetBaseWindow()->Show();
175 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
177 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
179 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
182 OnNativeWindowChanged();
184 // When the render view host is changed, the native window needs to know
185 // about it in case it has any setup to do to make the renderer appear
186 // properly. In particular, on Windows, the view's clickthrough region needs
188 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED
,
189 content::Source
<Profile
>(profile_
));
190 // Close when the browser process is exiting.
191 registrar_
.Add(this, chrome::NOTIFICATION_APP_TERMINATING
,
192 content::NotificationService::AllSources());
194 shell_window_contents_
->LoadContents(params
.creator_process_id
);
196 // Prevent the browser process from shutting down while this window is open.
197 chrome::StartKeepAlive();
199 UpdateExtensionAppIcon();
201 ShellWindowRegistry::Get(profile_
)->AddShellWindow(this);
204 ShellWindow::~ShellWindow() {
205 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
207 registrar_
.RemoveAll();
209 // Remove shutdown prevention.
210 chrome::EndKeepAlive();
213 void ShellWindow::RequestMediaAccessPermission(
214 content::WebContents
* web_contents
,
215 const content::MediaStreamRequest
& request
,
216 const content::MediaResponseCallback
& callback
) {
217 delegate_
->RequestMediaAccessPermission(web_contents
, request
, callback
,
221 WebContents
* ShellWindow::OpenURLFromTab(WebContents
* source
,
222 const content::OpenURLParams
& params
) {
223 // Don't allow the current tab to be navigated. It would be nice to map all
224 // anchor tags (even those without target="_blank") to new tabs, but right
225 // now we can't distinguish between those and <meta> refreshes or window.href
226 // navigations, which we don't want to allow.
227 // TOOD(mihaip): Can we check for user gestures instead?
228 WindowOpenDisposition disposition
= params
.disposition
;
229 if (disposition
== CURRENT_TAB
) {
230 AddMessageToDevToolsConsole(
231 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
233 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
234 params
.url
.spec().c_str()));
238 // These dispositions aren't really navigations.
239 if (disposition
== SUPPRESS_OPEN
|| disposition
== SAVE_TO_DISK
||
240 disposition
== IGNORE_ACTION
) {
244 WebContents
* contents
= delegate_
->OpenURLFromTab(profile_
, source
,
247 AddMessageToDevToolsConsole(
248 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
250 "Can't navigate to \"%s\"; apps do not support navigation.",
251 params
.url
.spec().c_str()));
257 void ShellWindow::AddNewContents(WebContents
* source
,
258 WebContents
* new_contents
,
259 WindowOpenDisposition disposition
,
260 const gfx::Rect
& initial_pos
,
263 DCHECK(Profile::FromBrowserContext(new_contents
->GetBrowserContext()) ==
265 delegate_
->AddNewContents(profile_
, new_contents
, disposition
,
266 initial_pos
, user_gesture
, was_blocked
);
269 void ShellWindow::HandleKeyboardEvent(
271 const content::NativeWebKeyboardEvent
& event
) {
272 native_app_window_
->HandleKeyboardEvent(event
);
275 void ShellWindow::RequestToLockMouse(WebContents
* web_contents
,
277 bool last_unlocked_by_target
) {
278 bool has_permission
= IsExtensionWithPermissionOrSuggestInConsole(
279 APIPermission::kPointerLock
,
281 web_contents
->GetRenderViewHost());
283 web_contents
->GotResponseToLockMouseRequest(has_permission
);
286 void ShellWindow::OnNativeClose() {
287 ShellWindowRegistry::Get(profile_
)->RemoveShellWindow(this);
288 if (shell_window_contents_
) {
289 WebContents
* web_contents
= shell_window_contents_
->GetWebContents();
290 WebContentsModalDialogManager::FromWebContents(web_contents
)->
292 shell_window_contents_
->NativeWindowClosed();
297 void ShellWindow::OnNativeWindowChanged() {
298 SaveWindowPosition();
299 if (shell_window_contents_
&& native_app_window_
)
300 shell_window_contents_
->NativeWindowChanged(native_app_window_
.get());
302 bool was_content_visible
= is_content_visible_
;
303 NativeAppWindow
* window
= GetBaseWindow();
305 is_content_visible_
= window
->IsVisible() && !window
->IsMinimized();
306 if (was_content_visible
&& !is_content_visible_
)
307 shell_window_contents_
->GetWebContents()->WasHidden();
308 else if (!was_content_visible
&& is_content_visible_
)
309 shell_window_contents_
->GetWebContents()->WasShown();
313 void ShellWindow::OnNativeWindowActivated() {
314 ShellWindowRegistry::Get(profile_
)->ShellWindowActivated(this);
317 scoped_ptr
<gfx::Image
> ShellWindow::GetAppListIcon() {
318 // TODO(skuhne): We might want to use LoadImages in UpdateExtensionAppIcon
319 // instead to let the extension give us pre-defined icons in the launcher
320 // and the launcher list sizes. Since there is no mock yet, doing this now
321 // seems a bit premature and we scale for the time being.
322 if (app_icon_
.IsEmpty())
323 return make_scoped_ptr(new gfx::Image());
325 SkBitmap bmp
= skia::ImageOperations::Resize(
326 *app_icon_
.ToSkBitmap(), skia::ImageOperations::RESIZE_BEST
,
327 extension_misc::EXTENSION_ICON_SMALLISH
,
328 extension_misc::EXTENSION_ICON_SMALLISH
);
329 return make_scoped_ptr(
330 new gfx::Image(gfx::ImageSkia::CreateFrom1xBitmap(bmp
)));
333 content::WebContents
* ShellWindow::web_contents() const {
334 return shell_window_contents_
->GetWebContents();
337 NativeAppWindow
* ShellWindow::GetBaseWindow() {
338 return native_app_window_
.get();
341 gfx::NativeWindow
ShellWindow::GetNativeWindow() {
342 return GetBaseWindow()->GetNativeWindow();
345 gfx::Rect
ShellWindow::GetClientBounds() const {
346 gfx::Rect bounds
= native_app_window_
->GetBounds();
347 bounds
.Inset(native_app_window_
->GetFrameInsets());
351 string16
ShellWindow::GetTitle() const {
352 // WebContents::GetTitle() will return the page's URL if there's no <title>
353 // specified. However, we'd prefer to show the name of the extension in that
354 // case, so we directly inspect the NavigationEntry's title.
356 if (!web_contents() ||
357 !web_contents()->GetController().GetActiveEntry() ||
358 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
359 title
= UTF8ToUTF16(extension()->name());
361 title
= web_contents()->GetTitle();
363 const char16 kBadChars
[] = { '\n', 0 };
364 RemoveChars(title
, kBadChars
, &title
);
368 void ShellWindow::SetAppIconUrl(const GURL
& url
) {
369 // Avoid using any previous app icons were are being downloaded.
370 image_loader_ptr_factory_
.InvalidateWeakPtrs();
372 // Reset |app_icon_image_| to abort pending image load (if any).
373 app_icon_image_
.reset();
376 web_contents()->DownloadImage(
378 true, // is a favicon
379 0, // no maximum size
380 base::Bind(&ShellWindow::DidDownloadFavicon
,
381 image_loader_ptr_factory_
.GetWeakPtr()));
384 void ShellWindow::UpdateInputRegion(scoped_ptr
<SkRegion
> region
) {
385 native_app_window_
->UpdateInputRegion(region
.Pass());
388 void ShellWindow::UpdateDraggableRegions(
389 const std::vector
<extensions::DraggableRegion
>& regions
) {
390 native_app_window_
->UpdateDraggableRegions(regions
);
393 void ShellWindow::UpdateAppIcon(const gfx::Image
& image
) {
397 native_app_window_
->UpdateWindowIcon();
398 ShellWindowRegistry::Get(profile_
)->ShellWindowIconChanged(this);
401 void ShellWindow::Fullscreen() {
402 #if !defined(OS_MACOSX)
403 // Do not enter fullscreen mode if disallowed by pref.
404 if (!profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed
))
407 fullscreen_for_window_api_
= true;
408 GetBaseWindow()->SetFullscreen(true);
411 void ShellWindow::Maximize() {
412 GetBaseWindow()->Maximize();
415 void ShellWindow::Minimize() {
416 GetBaseWindow()->Minimize();
419 void ShellWindow::Restore() {
420 fullscreen_for_window_api_
= false;
421 fullscreen_for_tab_
= false;
422 if (GetBaseWindow()->IsFullscreenOrPending()) {
423 GetBaseWindow()->SetFullscreen(false);
425 GetBaseWindow()->Restore();
429 //------------------------------------------------------------------------------
432 void ShellWindow::DidDownloadFavicon(
434 int http_status_code
,
435 const GURL
& image_url
,
436 const std::vector
<SkBitmap
>& bitmaps
,
437 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
438 if (image_url
!= app_icon_url_
|| bitmaps
.empty())
441 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
442 // whose height >= the preferred size.
443 int largest_index
= 0;
444 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
445 if (bitmaps
[i
].height() < delegate_
->PreferredIconSize())
449 const SkBitmap
& largest
= bitmaps
[largest_index
];
450 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
453 void ShellWindow::OnExtensionIconImageChanged(extensions::IconImage
* image
) {
454 DCHECK_EQ(app_icon_image_
.get(), image
);
456 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
459 void ShellWindow::UpdateExtensionAppIcon() {
460 // Avoid using any previous app icons were are being downloaded.
461 image_loader_ptr_factory_
.InvalidateWeakPtrs();
463 app_icon_image_
.reset(new extensions::IconImage(
466 extensions::IconsInfo::GetIcons(extension()),
467 delegate_
->PreferredIconSize(),
468 extensions::IconsInfo::GetDefaultAppIcon(),
471 // Triggers actual image loading with 1x resources. The 2x resource will
472 // be handled by IconImage class when requested.
473 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
476 void ShellWindow::CloseContents(WebContents
* contents
) {
477 native_app_window_
->Close();
480 bool ShellWindow::ShouldSuppressDialogs() {
484 content::ColorChooser
* ShellWindow::OpenColorChooser(WebContents
* web_contents
,
485 SkColor initial_color
) {
486 return delegate_
->ShowColorChooser(web_contents
, initial_color
);
489 void ShellWindow::RunFileChooser(WebContents
* tab
,
490 const content::FileChooserParams
& params
) {
491 if (window_type_is_panel()) {
492 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
493 // dialogs to be unhosted but still close with the owning web contents.
495 LOG(WARNING
) << "File dialog opened by panel.";
499 delegate_
->RunFileChooser(tab
, params
);
502 bool ShellWindow::IsPopupOrPanel(const WebContents
* source
) const {
506 void ShellWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
507 native_app_window_
->SetBounds(pos
);
510 void ShellWindow::NavigationStateChanged(
511 const content::WebContents
* source
, unsigned changed_flags
) {
512 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
513 native_app_window_
->UpdateWindowTitle();
514 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
515 native_app_window_
->UpdateWindowIcon();
518 void ShellWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
519 bool enter_fullscreen
) {
520 #if !defined(OS_MACOSX)
521 // Do not enter fullscreen mode if disallowed by pref.
522 // TODO(bartfab): Add a test once it becomes possible to simulate a user
523 // gesture. http://crbug.com/174178
524 if (enter_fullscreen
&&
525 !profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed
)) {
530 if (!IsExtensionWithPermissionOrSuggestInConsole(
531 APIPermission::kFullscreen
,
533 source
->GetRenderViewHost())) {
537 fullscreen_for_tab_
= enter_fullscreen
;
539 if (enter_fullscreen
) {
540 native_app_window_
->SetFullscreen(true);
541 } else if (!fullscreen_for_window_api_
) {
542 native_app_window_
->SetFullscreen(false);
546 bool ShellWindow::IsFullscreenForTabOrPending(
547 const content::WebContents
* source
) const {
548 return fullscreen_for_tab_
;
551 void ShellWindow::Observe(int type
,
552 const content::NotificationSource
& source
,
553 const content::NotificationDetails
& details
) {
555 case chrome::NOTIFICATION_EXTENSION_UNLOADED
: {
556 const extensions::Extension
* unloaded_extension
=
557 content::Details
<extensions::UnloadedExtensionInfo
>(
559 if (extension_
== unloaded_extension
)
560 native_app_window_
->Close();
563 case chrome::NOTIFICATION_APP_TERMINATING
:
564 native_app_window_
->Close();
567 NOTREACHED() << "Received unexpected notification";
571 void ShellWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
573 delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
576 bool ShellWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
577 return delegate_
->IsWebContentsVisible(web_contents
);
580 extensions::ActiveTabPermissionGranter
*
581 ShellWindow::GetActiveTabPermissionGranter() {
582 // Shell windows don't support the activeTab permission.
586 WebContentsModalDialogHost
* ShellWindow::GetWebContentsModalDialogHost() {
587 return native_app_window_
.get();
590 void ShellWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level
,
591 const std::string
& message
) {
592 content::RenderViewHost
* rvh
= web_contents()->GetRenderViewHost();
593 rvh
->Send(new ExtensionMsg_AddMessageToConsole(
594 rvh
->GetRoutingID(), level
, message
));
597 void ShellWindow::SaveWindowPosition() {
598 if (window_key_
.empty())
600 if (!native_app_window_
)
603 ShellWindowGeometryCache
* cache
= ShellWindowGeometryCache::Get(profile());
605 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
606 bounds
.Inset(native_app_window_
->GetFrameInsets());
607 gfx::Rect screen_bounds
=
608 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
609 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
610 cache
->SaveGeometry(extension()->id(),
617 void ShellWindow::AdjustBoundsToBeVisibleOnScreen(
618 const gfx::Rect
& cached_bounds
,
619 const gfx::Rect
& cached_screen_bounds
,
620 const gfx::Rect
& current_screen_bounds
,
621 const gfx::Size
& minimum_size
,
622 gfx::Rect
* bounds
) const {
623 *bounds
= cached_bounds
;
625 // Reposition and resize the bounds if the cached_screen_bounds is different
626 // from the current screen bounds and the current screen bounds doesn't
627 // completely contain the bounds.
628 if (cached_screen_bounds
!= current_screen_bounds
&&
629 !current_screen_bounds
.Contains(cached_bounds
)) {
631 std::max(minimum_size
.width(),
632 std::min(bounds
->width(), current_screen_bounds
.width())));
634 std::max(minimum_size
.height(),
635 std::min(bounds
->height(), current_screen_bounds
.height())));
637 std::max(current_screen_bounds
.x(),
638 std::min(bounds
->x(),
639 current_screen_bounds
.right() - bounds
->width())));
641 std::max(current_screen_bounds
.y(),
642 std::min(bounds
->y(),
643 current_screen_bounds
.bottom() - bounds
->height())));
648 SkRegion
* ShellWindow::RawDraggableRegionsToSkRegion(
649 const std::vector
<extensions::DraggableRegion
>& regions
) {
650 SkRegion
* sk_region
= new SkRegion
;
651 for (std::vector
<extensions::DraggableRegion
>::const_iterator iter
=
653 iter
!= regions
.end(); ++iter
) {
654 const extensions::DraggableRegion
& region
= *iter
;
658 region
.bounds
.right(),
659 region
.bounds
.bottom(),
660 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);