file_manager: Remove fileBrowserPrivate.viewFiles()
[chromium-blink-merge.git] / apps / shell_window.cc
blob96c6abd7ed63de73d0dbfbbf9d87699b44e5e976
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"
43 #endif
45 using content::ConsoleMessageLevel;
46 using content::WebContents;
47 using extensions::APIPermission;
48 using web_modal::WebContentsModalDialogHost;
49 using web_modal::WebContentsModalDialogManager;
51 namespace {
52 const int kDefaultWidth = 512;
53 const int kDefaultHeight = 384;
55 } // namespace
57 namespace apps {
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),
66 hidden(false),
67 resizable(true),
68 focused(true) {}
70 ShellWindow::CreateParams::~CreateParams() {}
72 ShellWindow::Delegate::~Delegate() {}
74 ShellWindow::ShellWindow(Profile* profile,
75 Delegate* delegate,
76 const extensions::Extension* extension)
77 : profile_(profile),
78 extension_(extension),
79 extension_id_(extension->id()),
80 window_type_(WINDOW_TYPE_DEFAULT),
81 delegate_(delegate),
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)->
99 SetDelegate(this);
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,
136 params.minimum_size,
137 &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.
169 else
170 GetBaseWindow()->Show();
173 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
174 Fullscreen();
175 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
176 Maximize();
177 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
178 Minimize();
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
185 // to be set.
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
207 // last window open.
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,
219 extension());
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,
233 base::StringPrintf(
234 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
235 params.url.spec().c_str()));
236 return NULL;
239 // These dispositions aren't really navigations.
240 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
241 disposition == IGNORE_ACTION) {
242 return NULL;
245 WebContents* contents = delegate_->OpenURLFromTab(profile_, source,
246 params);
247 if (!contents) {
248 AddMessageToDevToolsConsole(
249 content::CONSOLE_MESSAGE_LEVEL_ERROR,
250 base::StringPrintf(
251 "Can't navigate to \"%s\"; apps do not support navigation.",
252 params.url.spec().c_str()));
255 return contents;
258 void ShellWindow::AddNewContents(WebContents* source,
259 WebContents* new_contents,
260 WindowOpenDisposition disposition,
261 const gfx::Rect& initial_pos,
262 bool user_gesture,
263 bool* was_blocked) {
264 DCHECK(Profile::FromBrowserContext(new_contents->GetBrowserContext()) ==
265 profile_);
266 delegate_->AddNewContents(profile_, new_contents, disposition,
267 initial_pos, user_gesture, was_blocked);
270 void ShellWindow::HandleKeyboardEvent(
271 WebContents* source,
272 const content::NativeWebKeyboardEvent& event) {
273 native_app_window_->HandleKeyboardEvent(event);
276 void ShellWindow::RequestToLockMouse(WebContents* web_contents,
277 bool user_gesture,
278 bool last_unlocked_by_target) {
279 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
280 APIPermission::kPointerLock,
281 extension_,
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 shell_window_contents_->NativeWindowClosed();
291 delete this;
294 void ShellWindow::OnNativeWindowChanged() {
295 SaveWindowPosition();
296 if (shell_window_contents_ && native_app_window_)
297 shell_window_contents_->NativeWindowChanged(native_app_window_.get());
300 void ShellWindow::OnNativeWindowActivated() {
301 ShellWindowRegistry::Get(profile_)->ShellWindowActivated(this);
304 scoped_ptr<gfx::Image> ShellWindow::GetAppListIcon() {
305 // TODO(skuhne): We might want to use LoadImages in UpdateExtensionAppIcon
306 // instead to let the extension give us pre-defined icons in the launcher
307 // and the launcher list sizes. Since there is no mock yet, doing this now
308 // seems a bit premature and we scale for the time being.
309 if (app_icon_.IsEmpty())
310 return make_scoped_ptr(new gfx::Image());
312 SkBitmap bmp = skia::ImageOperations::Resize(
313 *app_icon_.ToSkBitmap(), skia::ImageOperations::RESIZE_BEST,
314 extension_misc::EXTENSION_ICON_SMALLISH,
315 extension_misc::EXTENSION_ICON_SMALLISH);
316 return make_scoped_ptr(
317 new gfx::Image(gfx::ImageSkia::CreateFrom1xBitmap(bmp)));
320 content::WebContents* ShellWindow::web_contents() const {
321 return shell_window_contents_->GetWebContents();
324 NativeAppWindow* ShellWindow::GetBaseWindow() {
325 return native_app_window_.get();
328 gfx::NativeWindow ShellWindow::GetNativeWindow() {
329 return GetBaseWindow()->GetNativeWindow();
332 gfx::Rect ShellWindow::GetClientBounds() const {
333 gfx::Rect bounds = native_app_window_->GetBounds();
334 bounds.Inset(native_app_window_->GetFrameInsets());
335 return bounds;
338 string16 ShellWindow::GetTitle() const {
339 // WebContents::GetTitle() will return the page's URL if there's no <title>
340 // specified. However, we'd prefer to show the name of the extension in that
341 // case, so we directly inspect the NavigationEntry's title.
342 string16 title;
343 if (!web_contents() ||
344 !web_contents()->GetController().GetActiveEntry() ||
345 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
346 title = UTF8ToUTF16(extension()->name());
347 } else {
348 title = web_contents()->GetTitle();
350 const char16 kBadChars[] = { '\n', 0 };
351 RemoveChars(title, kBadChars, &title);
352 return title;
355 void ShellWindow::SetAppIconUrl(const GURL& url) {
356 // Avoid using any previous app icons were are being downloaded.
357 image_loader_ptr_factory_.InvalidateWeakPtrs();
359 // Reset |app_icon_image_| to abort pending image load (if any).
360 app_icon_image_.reset();
362 app_icon_url_ = url;
363 web_contents()->DownloadImage(
364 url,
365 true, // is a favicon
366 delegate_->PreferredIconSize(),
367 0, // no maximum size
368 base::Bind(&ShellWindow::DidDownloadFavicon,
369 image_loader_ptr_factory_.GetWeakPtr()));
372 void ShellWindow::UpdateInputRegion(scoped_ptr<SkRegion> region) {
373 native_app_window_->UpdateInputRegion(region.Pass());
376 void ShellWindow::UpdateDraggableRegions(
377 const std::vector<extensions::DraggableRegion>& regions) {
378 native_app_window_->UpdateDraggableRegions(regions);
381 void ShellWindow::UpdateAppIcon(const gfx::Image& image) {
382 if (image.IsEmpty())
383 return;
384 app_icon_ = image;
385 native_app_window_->UpdateWindowIcon();
386 ShellWindowRegistry::Get(profile_)->ShellWindowIconChanged(this);
389 void ShellWindow::Fullscreen() {
390 fullscreen_for_window_api_ = true;
391 GetBaseWindow()->SetFullscreen(true);
394 void ShellWindow::Maximize() {
395 GetBaseWindow()->Maximize();
398 void ShellWindow::Minimize() {
399 GetBaseWindow()->Minimize();
402 void ShellWindow::Restore() {
403 fullscreen_for_window_api_ = false;
404 fullscreen_for_tab_ = false;
405 if (GetBaseWindow()->IsFullscreenOrPending()) {
406 GetBaseWindow()->SetFullscreen(false);
407 } else {
408 GetBaseWindow()->Restore();
412 //------------------------------------------------------------------------------
413 // Private methods
415 void ShellWindow::DidDownloadFavicon(int id,
416 int http_status_code,
417 const GURL& image_url,
418 int requested_size,
419 const std::vector<SkBitmap>& bitmaps) {
420 if (image_url != app_icon_url_ || bitmaps.empty())
421 return;
423 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
424 // whose height >= the preferred size.
425 int largest_index = 0;
426 for (size_t i = 1; i < bitmaps.size(); ++i) {
427 if (bitmaps[i].height() < delegate_->PreferredIconSize())
428 break;
429 largest_index = i;
431 const SkBitmap& largest = bitmaps[largest_index];
432 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
435 void ShellWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
436 DCHECK_EQ(app_icon_image_.get(), image);
438 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
441 void ShellWindow::UpdateExtensionAppIcon() {
442 // Avoid using any previous app icons were are being downloaded.
443 image_loader_ptr_factory_.InvalidateWeakPtrs();
445 app_icon_image_.reset(new extensions::IconImage(
446 profile(),
447 extension(),
448 extensions::IconsInfo::GetIcons(extension()),
449 delegate_->PreferredIconSize(),
450 extensions::IconsInfo::GetDefaultAppIcon(),
451 this));
453 // Triggers actual image loading with 1x resources. The 2x resource will
454 // be handled by IconImage class when requested.
455 app_icon_image_->image_skia().GetRepresentation(ui::SCALE_FACTOR_100P);
458 void ShellWindow::CloseContents(WebContents* contents) {
459 native_app_window_->Close();
462 bool ShellWindow::ShouldSuppressDialogs() {
463 return true;
466 content::ColorChooser* ShellWindow::OpenColorChooser(WebContents* web_contents,
467 SkColor initial_color) {
468 return delegate_->ShowColorChooser(web_contents, initial_color);
471 void ShellWindow::RunFileChooser(WebContents* tab,
472 const content::FileChooserParams& params) {
473 if (window_type_is_panel()) {
474 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
475 // dialogs to be unhosted but still close with the owning web contents.
476 // crbug.com/172502.
477 LOG(WARNING) << "File dialog opened by panel.";
478 return;
481 delegate_->RunFileChooser(tab, params);
484 bool ShellWindow::IsPopupOrPanel(const WebContents* source) const {
485 return true;
488 void ShellWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
489 native_app_window_->SetBounds(pos);
492 void ShellWindow::NavigationStateChanged(
493 const content::WebContents* source, unsigned changed_flags) {
494 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
495 native_app_window_->UpdateWindowTitle();
496 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
497 native_app_window_->UpdateWindowIcon();
500 void ShellWindow::ToggleFullscreenModeForTab(content::WebContents* source,
501 bool enter_fullscreen) {
502 #if !defined(OS_MACOSX)
503 // Do not enter fullscreen mode if disallowed by pref.
504 // TODO(bartfab): Add a test once it becomes possible to simulate a user
505 // gesture. http://crbug.com/174178
506 if (enter_fullscreen &&
507 !profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed)) {
508 return;
510 #endif
512 if (!IsExtensionWithPermissionOrSuggestInConsole(
513 APIPermission::kFullscreen,
514 extension_,
515 source->GetRenderViewHost())) {
516 return;
519 fullscreen_for_tab_ = enter_fullscreen;
521 if (enter_fullscreen) {
522 native_app_window_->SetFullscreen(true);
523 } else if (!fullscreen_for_window_api_) {
524 native_app_window_->SetFullscreen(false);
528 bool ShellWindow::IsFullscreenForTabOrPending(
529 const content::WebContents* source) const {
530 return fullscreen_for_tab_;
533 void ShellWindow::Observe(int type,
534 const content::NotificationSource& source,
535 const content::NotificationDetails& details) {
536 switch (type) {
537 case content::NOTIFICATION_RENDER_VIEW_HOST_CHANGED: {
538 // TODO(jianli): once http://crbug.com/123007 is fixed, we'll no longer
539 // need to make the native window (ShellWindowViews specially) update
540 // the clickthrough region for the new RVH.
541 native_app_window_->RenderViewHostChanged();
542 break;
544 case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
545 const extensions::Extension* unloaded_extension =
546 content::Details<extensions::UnloadedExtensionInfo>(
547 details)->extension;
548 if (extension_ == unloaded_extension)
549 native_app_window_->Close();
550 break;
552 case chrome::NOTIFICATION_APP_TERMINATING:
553 native_app_window_->Close();
554 break;
555 default:
556 NOTREACHED() << "Received unexpected notification";
560 void ShellWindow::SetWebContentsBlocked(content::WebContents* web_contents,
561 bool blocked) {
562 delegate_->SetWebContentsBlocked(web_contents, blocked);
565 bool ShellWindow::IsWebContentsVisible(content::WebContents* web_contents) {
566 return delegate_->IsWebContentsVisible(web_contents);
569 extensions::ActiveTabPermissionGranter*
570 ShellWindow::GetActiveTabPermissionGranter() {
571 // Shell windows don't support the activeTab permission.
572 return NULL;
575 WebContentsModalDialogHost* ShellWindow::GetWebContentsModalDialogHost() {
576 return native_app_window_.get();
579 void ShellWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
580 const std::string& message) {
581 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
582 rvh->Send(new ExtensionMsg_AddMessageToConsole(
583 rvh->GetRoutingID(), level, message));
586 void ShellWindow::SaveWindowPosition() {
587 if (window_key_.empty())
588 return;
589 if (!native_app_window_)
590 return;
592 ShellWindowGeometryCache* cache = ShellWindowGeometryCache::Get(profile());
594 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
595 bounds.Inset(native_app_window_->GetFrameInsets());
596 gfx::Rect screen_bounds =
597 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
598 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
599 cache->SaveGeometry(extension()->id(),
600 window_key_,
601 bounds,
602 screen_bounds,
603 window_state);
606 void ShellWindow::AdjustBoundsToBeVisibleOnScreen(
607 const gfx::Rect& cached_bounds,
608 const gfx::Rect& cached_screen_bounds,
609 const gfx::Rect& current_screen_bounds,
610 const gfx::Size& minimum_size,
611 gfx::Rect* bounds) const {
612 *bounds = cached_bounds;
614 // Reposition and resize the bounds if the cached_screen_bounds is different
615 // from the current screen bounds and the current screen bounds doesn't
616 // completely contain the bounds.
617 if (cached_screen_bounds != current_screen_bounds &&
618 !current_screen_bounds.Contains(cached_bounds)) {
619 bounds->set_width(
620 std::max(minimum_size.width(),
621 std::min(bounds->width(), current_screen_bounds.width())));
622 bounds->set_height(
623 std::max(minimum_size.height(),
624 std::min(bounds->height(), current_screen_bounds.height())));
625 bounds->set_x(
626 std::max(current_screen_bounds.x(),
627 std::min(bounds->x(),
628 current_screen_bounds.right() - bounds->width())));
629 bounds->set_y(
630 std::max(current_screen_bounds.y(),
631 std::min(bounds->y(),
632 current_screen_bounds.bottom() - bounds->height())));
636 // static
637 SkRegion* ShellWindow::RawDraggableRegionsToSkRegion(
638 const std::vector<extensions::DraggableRegion>& regions) {
639 SkRegion* sk_region = new SkRegion;
640 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
641 regions.begin();
642 iter != regions.end(); ++iter) {
643 const extensions::DraggableRegion& region = *iter;
644 sk_region->op(
645 region.bounds.x(),
646 region.bounds.y(),
647 region.bounds.right(),
648 region.bounds.bottom(),
649 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
651 return sk_region;
654 } // namespace apps