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/native_app_window.h"
8 #include "apps/shell_window_geometry_cache.h"
9 #include "apps/shell_window_registry.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
),
70 ShellWindow::CreateParams::~CreateParams() {}
72 ShellWindow::Delegate::~Delegate() {}
74 ShellWindow::ShellWindow(Profile
* profile
,
76 const extensions::Extension
* extension
)
78 extension_(extension
),
79 extension_id_(extension
->id()),
80 window_type_(WINDOW_TYPE_DEFAULT
),
82 image_loader_ptr_factory_(this),
83 fullscreen_for_window_api_(false),
84 fullscreen_for_tab_(false) {
87 void ShellWindow::Init(const GURL
& url
,
88 ShellWindowContents
* shell_window_contents
,
89 const CreateParams
& params
) {
90 // Initialize the render interface and web contents
91 shell_window_contents_
.reset(shell_window_contents
);
92 shell_window_contents_
->Initialize(profile(), url
);
93 WebContents
* web_contents
= shell_window_contents_
->GetWebContents();
94 delegate_
->InitWebContents(web_contents
);
95 WebContentsModalDialogManager::CreateForWebContents(web_contents
);
97 web_contents
->SetDelegate(this);
98 WebContentsModalDialogManager::FromWebContents(web_contents
)->
100 extensions::SetViewType(web_contents
, extensions::VIEW_TYPE_APP_SHELL
);
102 // Initialize the window
103 window_type_
= params
.window_type
;
105 gfx::Rect bounds
= params
.bounds
;
107 if (bounds
.width() == 0)
108 bounds
.set_width(kDefaultWidth
);
109 if (bounds
.height() == 0)
110 bounds
.set_height(kDefaultHeight
);
112 // If left and top are left undefined, the native shell window will center
113 // the window on the main screen in a platform-defined manner.
115 CreateParams new_params
= params
;
117 // Load cached state if it exists.
118 if (!params
.window_key
.empty()) {
119 window_key_
= params
.window_key
;
121 ShellWindowGeometryCache
* cache
= ShellWindowGeometryCache::Get(profile());
123 gfx::Rect cached_bounds
;
124 gfx::Rect cached_screen_bounds
;
125 ui::WindowShowState cached_state
= ui::SHOW_STATE_DEFAULT
;
126 if (cache
->GetGeometry(extension()->id(), params
.window_key
, &cached_bounds
,
127 &cached_screen_bounds
, &cached_state
)) {
128 // App window has cached screen bounds, make sure it fits on screen in
129 // case the screen resolution changed.
130 gfx::Screen
* screen
= gfx::Screen::GetNativeScreen();
131 gfx::Display display
= screen
->GetDisplayMatching(cached_bounds
);
132 gfx::Rect current_screen_bounds
= display
.work_area();
133 AdjustBoundsToBeVisibleOnScreen(cached_bounds
,
134 cached_screen_bounds
,
135 current_screen_bounds
,
138 new_params
.state
= cached_state
;
142 gfx::Size
& minimum_size
= new_params
.minimum_size
;
143 gfx::Size
& maximum_size
= new_params
.maximum_size
;
145 // In the case that minimum size > maximum size, we consider the minimum
146 // size to be more important.
147 if (maximum_size
.width() && maximum_size
.width() < minimum_size
.width())
148 maximum_size
.set_width(minimum_size
.width());
149 if (maximum_size
.height() && maximum_size
.height() < minimum_size
.height())
150 maximum_size
.set_height(minimum_size
.height());
152 if (maximum_size
.width() && bounds
.width() > maximum_size
.width())
153 bounds
.set_width(maximum_size
.width());
154 if (bounds
.width() != INT_MIN
&& bounds
.width() < minimum_size
.width())
155 bounds
.set_width(minimum_size
.width());
157 if (maximum_size
.height() && bounds
.height() > maximum_size
.height())
158 bounds
.set_height(maximum_size
.height());
159 if (bounds
.height() != INT_MIN
&& bounds
.height() < minimum_size
.height())
160 bounds
.set_height(minimum_size
.height());
162 new_params
.bounds
= bounds
;
164 native_app_window_
.reset(delegate_
->CreateNativeAppWindow(this, new_params
));
166 if (!new_params
.hidden
) {
167 if (window_type_is_panel())
168 GetBaseWindow()->ShowInactive(); // Panels are not activated by default.
170 GetBaseWindow()->Show();
173 if (new_params
.state
== ui::SHOW_STATE_FULLSCREEN
)
175 else if (new_params
.state
== ui::SHOW_STATE_MAXIMIZED
)
177 else if (new_params
.state
== ui::SHOW_STATE_MINIMIZED
)
180 OnNativeWindowChanged();
182 // When the render view host is changed, the native window needs to know
183 // about it in case it has any setup to do to make the renderer appear
184 // properly. In particular, on Windows, the view's clickthrough region needs
186 registrar_
.Add(this, content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED
,
187 content::Source
<content::NavigationController
>(
188 &web_contents
->GetController()));
189 registrar_
.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED
,
190 content::Source
<Profile
>(profile_
));
191 // Close when the browser process is exiting.
192 registrar_
.Add(this, chrome::NOTIFICATION_APP_TERMINATING
,
193 content::NotificationService::AllSources());
195 shell_window_contents_
->LoadContents(params
.creator_process_id
);
197 // Prevent the browser process from shutting down while this window is open.
198 chrome::StartKeepAlive();
200 UpdateExtensionAppIcon();
202 ShellWindowRegistry::Get(profile_
)->AddShellWindow(this);
205 ShellWindow::~ShellWindow() {
206 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
208 registrar_
.RemoveAll();
210 // Remove shutdown prevention.
211 chrome::EndKeepAlive();
214 void ShellWindow::RequestMediaAccessPermission(
215 content::WebContents
* web_contents
,
216 const content::MediaStreamRequest
& request
,
217 const content::MediaResponseCallback
& callback
) {
218 delegate_
->RequestMediaAccessPermission(web_contents
, request
, callback
,
222 WebContents
* ShellWindow::OpenURLFromTab(WebContents
* source
,
223 const content::OpenURLParams
& params
) {
224 // Don't allow the current tab to be navigated. It would be nice to map all
225 // anchor tags (even those without target="_blank") to new tabs, but right
226 // now we can't distinguish between those and <meta> refreshes or window.href
227 // navigations, which we don't want to allow.
228 // TOOD(mihaip): Can we check for user gestures instead?
229 WindowOpenDisposition disposition
= params
.disposition
;
230 if (disposition
== CURRENT_TAB
) {
231 AddMessageToDevToolsConsole(
232 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
234 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
235 params
.url
.spec().c_str()));
239 // These dispositions aren't really navigations.
240 if (disposition
== SUPPRESS_OPEN
|| disposition
== SAVE_TO_DISK
||
241 disposition
== IGNORE_ACTION
) {
245 WebContents
* contents
= delegate_
->OpenURLFromTab(profile_
, source
,
248 AddMessageToDevToolsConsole(
249 content::CONSOLE_MESSAGE_LEVEL_ERROR
,
251 "Can't navigate to \"%s\"; apps do not support navigation.",
252 params
.url
.spec().c_str()));
258 void ShellWindow::AddNewContents(WebContents
* source
,
259 WebContents
* new_contents
,
260 WindowOpenDisposition disposition
,
261 const gfx::Rect
& initial_pos
,
264 DCHECK(Profile::FromBrowserContext(new_contents
->GetBrowserContext()) ==
266 delegate_
->AddNewContents(profile_
, new_contents
, disposition
,
267 initial_pos
, user_gesture
, was_blocked
);
270 void ShellWindow::HandleKeyboardEvent(
272 const content::NativeWebKeyboardEvent
& event
) {
273 native_app_window_
->HandleKeyboardEvent(event
);
276 void ShellWindow::RequestToLockMouse(WebContents
* web_contents
,
278 bool last_unlocked_by_target
) {
279 bool has_permission
= IsExtensionWithPermissionOrSuggestInConsole(
280 APIPermission::kPointerLock
,
282 web_contents
->GetRenderViewHost());
284 web_contents
->GotResponseToLockMouseRequest(has_permission
);
287 void ShellWindow::OnNativeClose() {
288 ShellWindowRegistry::Get(profile_
)->RemoveShellWindow(this);
289 if (shell_window_contents_
) {
290 WebContents
* web_contents
= shell_window_contents_
->GetWebContents();
291 WebContentsModalDialogManager::FromWebContents(web_contents
)->
293 shell_window_contents_
->NativeWindowClosed();
298 void ShellWindow::OnNativeWindowChanged() {
299 SaveWindowPosition();
300 if (shell_window_contents_
&& native_app_window_
)
301 shell_window_contents_
->NativeWindowChanged(native_app_window_
.get());
304 void ShellWindow::OnNativeWindowActivated() {
305 ShellWindowRegistry::Get(profile_
)->ShellWindowActivated(this);
308 scoped_ptr
<gfx::Image
> ShellWindow::GetAppListIcon() {
309 // TODO(skuhne): We might want to use LoadImages in UpdateExtensionAppIcon
310 // instead to let the extension give us pre-defined icons in the launcher
311 // and the launcher list sizes. Since there is no mock yet, doing this now
312 // seems a bit premature and we scale for the time being.
313 if (app_icon_
.IsEmpty())
314 return make_scoped_ptr(new gfx::Image());
316 SkBitmap bmp
= skia::ImageOperations::Resize(
317 *app_icon_
.ToSkBitmap(), skia::ImageOperations::RESIZE_BEST
,
318 extension_misc::EXTENSION_ICON_SMALLISH
,
319 extension_misc::EXTENSION_ICON_SMALLISH
);
320 return make_scoped_ptr(
321 new gfx::Image(gfx::ImageSkia::CreateFrom1xBitmap(bmp
)));
324 content::WebContents
* ShellWindow::web_contents() const {
325 return shell_window_contents_
->GetWebContents();
328 NativeAppWindow
* ShellWindow::GetBaseWindow() {
329 return native_app_window_
.get();
332 gfx::NativeWindow
ShellWindow::GetNativeWindow() {
333 return GetBaseWindow()->GetNativeWindow();
336 gfx::Rect
ShellWindow::GetClientBounds() const {
337 gfx::Rect bounds
= native_app_window_
->GetBounds();
338 bounds
.Inset(native_app_window_
->GetFrameInsets());
342 string16
ShellWindow::GetTitle() const {
343 // WebContents::GetTitle() will return the page's URL if there's no <title>
344 // specified. However, we'd prefer to show the name of the extension in that
345 // case, so we directly inspect the NavigationEntry's title.
347 if (!web_contents() ||
348 !web_contents()->GetController().GetActiveEntry() ||
349 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
350 title
= UTF8ToUTF16(extension()->name());
352 title
= web_contents()->GetTitle();
354 const char16 kBadChars
[] = { '\n', 0 };
355 RemoveChars(title
, kBadChars
, &title
);
359 void ShellWindow::SetAppIconUrl(const GURL
& url
) {
360 // Avoid using any previous app icons were are being downloaded.
361 image_loader_ptr_factory_
.InvalidateWeakPtrs();
363 // Reset |app_icon_image_| to abort pending image load (if any).
364 app_icon_image_
.reset();
367 web_contents()->DownloadImage(
369 true, // is a favicon
370 0, // no maximum size
371 base::Bind(&ShellWindow::DidDownloadFavicon
,
372 image_loader_ptr_factory_
.GetWeakPtr()));
375 void ShellWindow::UpdateInputRegion(scoped_ptr
<SkRegion
> region
) {
376 native_app_window_
->UpdateInputRegion(region
.Pass());
379 void ShellWindow::UpdateDraggableRegions(
380 const std::vector
<extensions::DraggableRegion
>& regions
) {
381 native_app_window_
->UpdateDraggableRegions(regions
);
384 void ShellWindow::UpdateAppIcon(const gfx::Image
& image
) {
388 native_app_window_
->UpdateWindowIcon();
389 ShellWindowRegistry::Get(profile_
)->ShellWindowIconChanged(this);
392 void ShellWindow::Fullscreen() {
393 #if !defined(OS_MACOSX)
394 // Do not enter fullscreen mode if disallowed by pref.
395 if (!profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed
))
398 fullscreen_for_window_api_
= true;
399 GetBaseWindow()->SetFullscreen(true);
402 void ShellWindow::Maximize() {
403 GetBaseWindow()->Maximize();
406 void ShellWindow::Minimize() {
407 GetBaseWindow()->Minimize();
410 void ShellWindow::Restore() {
411 fullscreen_for_window_api_
= false;
412 fullscreen_for_tab_
= false;
413 if (GetBaseWindow()->IsFullscreenOrPending()) {
414 GetBaseWindow()->SetFullscreen(false);
416 GetBaseWindow()->Restore();
420 //------------------------------------------------------------------------------
423 void ShellWindow::DidDownloadFavicon(
425 int http_status_code
,
426 const GURL
& image_url
,
427 const std::vector
<SkBitmap
>& bitmaps
,
428 const std::vector
<gfx::Size
>& original_bitmap_sizes
) {
429 if (image_url
!= app_icon_url_
|| bitmaps
.empty())
432 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
433 // whose height >= the preferred size.
434 int largest_index
= 0;
435 for (size_t i
= 1; i
< bitmaps
.size(); ++i
) {
436 if (bitmaps
[i
].height() < delegate_
->PreferredIconSize())
440 const SkBitmap
& largest
= bitmaps
[largest_index
];
441 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest
));
444 void ShellWindow::OnExtensionIconImageChanged(extensions::IconImage
* image
) {
445 DCHECK_EQ(app_icon_image_
.get(), image
);
447 UpdateAppIcon(gfx::Image(app_icon_image_
->image_skia()));
450 void ShellWindow::UpdateExtensionAppIcon() {
451 // Avoid using any previous app icons were are being downloaded.
452 image_loader_ptr_factory_
.InvalidateWeakPtrs();
454 app_icon_image_
.reset(new extensions::IconImage(
457 extensions::IconsInfo::GetIcons(extension()),
458 delegate_
->PreferredIconSize(),
459 extensions::IconsInfo::GetDefaultAppIcon(),
462 // Triggers actual image loading with 1x resources. The 2x resource will
463 // be handled by IconImage class when requested.
464 app_icon_image_
->image_skia().GetRepresentation(1.0f
);
467 void ShellWindow::CloseContents(WebContents
* contents
) {
468 native_app_window_
->Close();
471 bool ShellWindow::ShouldSuppressDialogs() {
475 content::ColorChooser
* ShellWindow::OpenColorChooser(WebContents
* web_contents
,
476 SkColor initial_color
) {
477 return delegate_
->ShowColorChooser(web_contents
, initial_color
);
480 void ShellWindow::RunFileChooser(WebContents
* tab
,
481 const content::FileChooserParams
& params
) {
482 if (window_type_is_panel()) {
483 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
484 // dialogs to be unhosted but still close with the owning web contents.
486 LOG(WARNING
) << "File dialog opened by panel.";
490 delegate_
->RunFileChooser(tab
, params
);
493 bool ShellWindow::IsPopupOrPanel(const WebContents
* source
) const {
497 void ShellWindow::MoveContents(WebContents
* source
, const gfx::Rect
& pos
) {
498 native_app_window_
->SetBounds(pos
);
501 void ShellWindow::NavigationStateChanged(
502 const content::WebContents
* source
, unsigned changed_flags
) {
503 if (changed_flags
& content::INVALIDATE_TYPE_TITLE
)
504 native_app_window_
->UpdateWindowTitle();
505 else if (changed_flags
& content::INVALIDATE_TYPE_TAB
)
506 native_app_window_
->UpdateWindowIcon();
509 void ShellWindow::ToggleFullscreenModeForTab(content::WebContents
* source
,
510 bool enter_fullscreen
) {
511 #if !defined(OS_MACOSX)
512 // Do not enter fullscreen mode if disallowed by pref.
513 // TODO(bartfab): Add a test once it becomes possible to simulate a user
514 // gesture. http://crbug.com/174178
515 if (enter_fullscreen
&&
516 !profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed
)) {
521 if (!IsExtensionWithPermissionOrSuggestInConsole(
522 APIPermission::kFullscreen
,
524 source
->GetRenderViewHost())) {
528 fullscreen_for_tab_
= enter_fullscreen
;
530 if (enter_fullscreen
) {
531 native_app_window_
->SetFullscreen(true);
532 } else if (!fullscreen_for_window_api_
) {
533 native_app_window_
->SetFullscreen(false);
537 bool ShellWindow::IsFullscreenForTabOrPending(
538 const content::WebContents
* source
) const {
539 return fullscreen_for_tab_
;
542 void ShellWindow::Observe(int type
,
543 const content::NotificationSource
& source
,
544 const content::NotificationDetails
& details
) {
546 case content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED
: {
547 // TODO(jianli): once http://crbug.com/123007 is fixed, we'll no longer
548 // need to make the native window (ShellWindowViews specially) update
549 // the clickthrough region for the new RVH.
550 native_app_window_
->RenderViewHostChanged();
553 case chrome::NOTIFICATION_EXTENSION_UNLOADED
: {
554 const extensions::Extension
* unloaded_extension
=
555 content::Details
<extensions::UnloadedExtensionInfo
>(
557 if (extension_
== unloaded_extension
)
558 native_app_window_
->Close();
561 case chrome::NOTIFICATION_APP_TERMINATING
:
562 native_app_window_
->Close();
565 NOTREACHED() << "Received unexpected notification";
569 void ShellWindow::SetWebContentsBlocked(content::WebContents
* web_contents
,
571 delegate_
->SetWebContentsBlocked(web_contents
, blocked
);
574 bool ShellWindow::IsWebContentsVisible(content::WebContents
* web_contents
) {
575 return delegate_
->IsWebContentsVisible(web_contents
);
578 extensions::ActiveTabPermissionGranter
*
579 ShellWindow::GetActiveTabPermissionGranter() {
580 // Shell windows don't support the activeTab permission.
584 WebContentsModalDialogHost
* ShellWindow::GetWebContentsModalDialogHost() {
585 return native_app_window_
.get();
588 void ShellWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level
,
589 const std::string
& message
) {
590 content::RenderViewHost
* rvh
= web_contents()->GetRenderViewHost();
591 rvh
->Send(new ExtensionMsg_AddMessageToConsole(
592 rvh
->GetRoutingID(), level
, message
));
595 void ShellWindow::SaveWindowPosition() {
596 if (window_key_
.empty())
598 if (!native_app_window_
)
601 ShellWindowGeometryCache
* cache
= ShellWindowGeometryCache::Get(profile());
603 gfx::Rect bounds
= native_app_window_
->GetRestoredBounds();
604 bounds
.Inset(native_app_window_
->GetFrameInsets());
605 gfx::Rect screen_bounds
=
606 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds
).work_area();
607 ui::WindowShowState window_state
= native_app_window_
->GetRestoredState();
608 cache
->SaveGeometry(extension()->id(),
615 void ShellWindow::AdjustBoundsToBeVisibleOnScreen(
616 const gfx::Rect
& cached_bounds
,
617 const gfx::Rect
& cached_screen_bounds
,
618 const gfx::Rect
& current_screen_bounds
,
619 const gfx::Size
& minimum_size
,
620 gfx::Rect
* bounds
) const {
621 *bounds
= cached_bounds
;
623 // Reposition and resize the bounds if the cached_screen_bounds is different
624 // from the current screen bounds and the current screen bounds doesn't
625 // completely contain the bounds.
626 if (cached_screen_bounds
!= current_screen_bounds
&&
627 !current_screen_bounds
.Contains(cached_bounds
)) {
629 std::max(minimum_size
.width(),
630 std::min(bounds
->width(), current_screen_bounds
.width())));
632 std::max(minimum_size
.height(),
633 std::min(bounds
->height(), current_screen_bounds
.height())));
635 std::max(current_screen_bounds
.x(),
636 std::min(bounds
->x(),
637 current_screen_bounds
.right() - bounds
->width())));
639 std::max(current_screen_bounds
.y(),
640 std::min(bounds
->y(),
641 current_screen_bounds
.bottom() - bounds
->height())));
646 SkRegion
* ShellWindow::RawDraggableRegionsToSkRegion(
647 const std::vector
<extensions::DraggableRegion
>& regions
) {
648 SkRegion
* sk_region
= new SkRegion
;
649 for (std::vector
<extensions::DraggableRegion
>::const_iterator iter
=
651 iter
!= regions
.end(); ++iter
) {
652 const extensions::DraggableRegion
& region
= *iter
;
656 region
.bounds
.right(),
657 region
.bounds
.bottom(),
658 region
.draggable
? SkRegion::kUnion_Op
: SkRegion::kDifference_Op
);