Close crashed incognito-mode app's shell window.
[chromium-blink-merge.git] / apps / shell_window.cc
blob49726ccc8430db54622d7eadfae9fcd98afac91a
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/command_line.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/values.h"
14 #include "chrome/browser/chrome_notification_types.h"
15 #include "chrome/browser/extensions/extension_web_contents_observer.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/chrome_switches.h"
20 #include "chrome/common/extensions/extension_messages.h"
21 #include "chrome/common/extensions/manifest_handlers/icons_handler.h"
22 #include "components/web_modal/web_contents_modal_dialog_manager.h"
23 #include "content/public/browser/invalidate_type.h"
24 #include "content/public/browser/navigation_entry.h"
25 #include "content/public/browser/notification_details.h"
26 #include "content/public/browser/notification_service.h"
27 #include "content/public/browser/notification_source.h"
28 #include "content/public/browser/notification_types.h"
29 #include "content/public/browser/render_view_host.h"
30 #include "content/public/browser/resource_dispatcher_host.h"
31 #include "content/public/browser/web_contents.h"
32 #include "content/public/browser/web_contents_view.h"
33 #include "content/public/common/media_stream_request.h"
34 #include "extensions/browser/extension_system.h"
35 #include "extensions/browser/process_manager.h"
36 #include "extensions/browser/view_type_utils.h"
37 #include "extensions/common/extension.h"
38 #include "third_party/skia/include/core/SkRegion.h"
39 #include "ui/gfx/screen.h"
41 #if !defined(OS_MACOSX)
42 #include "apps/pref_names.h"
43 #include "base/prefs/pref_service.h"
44 #endif
46 using content::ConsoleMessageLevel;
47 using content::WebContents;
48 using extensions::APIPermission;
49 using web_modal::WebContentsModalDialogHost;
50 using web_modal::WebContentsModalDialogManager;
52 namespace {
54 const int kDefaultWidth = 512;
55 const int kDefaultHeight = 384;
57 bool IsFullscreen(int fullscreen_types) {
58 return fullscreen_types != apps::ShellWindow::FULLSCREEN_TYPE_NONE;
61 } // namespace
63 namespace apps {
65 ShellWindow::SizeConstraints::SizeConstraints()
66 : maximum_size_(kUnboundedSize, kUnboundedSize) {
69 ShellWindow::SizeConstraints::SizeConstraints(const gfx::Size& min_size,
70 const gfx::Size& max_size)
71 : minimum_size_(min_size),
72 maximum_size_(max_size) {
75 ShellWindow::SizeConstraints::~SizeConstraints() {}
77 gfx::Size ShellWindow::SizeConstraints::ClampSize(gfx::Size size) const {
78 const gfx::Size max_size = GetMaximumSize();
79 if (max_size.width() != kUnboundedSize)
80 size.set_width(std::min(size.width(), GetMaximumSize().width()));
81 if (max_size.height() != kUnboundedSize)
82 size.set_height(std::min(size.height(), GetMaximumSize().height()));
83 size.SetToMax(GetMinimumSize());
84 return size;
87 bool ShellWindow::SizeConstraints::HasMinimumSize() const {
88 return GetMinimumSize().width() != kUnboundedSize ||
89 GetMinimumSize().height() != kUnboundedSize;
92 bool ShellWindow::SizeConstraints::HasMaximumSize() const {
93 const gfx::Size max_size = GetMaximumSize();
94 return max_size.width() != kUnboundedSize ||
95 max_size.height() != kUnboundedSize;
98 bool ShellWindow::SizeConstraints::HasFixedSize() const {
99 return !GetMinimumSize().IsEmpty() && GetMinimumSize() == GetMaximumSize();
102 gfx::Size ShellWindow::SizeConstraints::GetMinimumSize() const {
103 return minimum_size_;
106 gfx::Size ShellWindow::SizeConstraints::GetMaximumSize() const {
107 return gfx::Size(
108 maximum_size_.width() == kUnboundedSize ?
109 kUnboundedSize :
110 std::max(maximum_size_.width(), minimum_size_.width()),
111 maximum_size_.height() == kUnboundedSize ?
112 kUnboundedSize :
113 std::max(maximum_size_.height(), minimum_size_.height()));
116 void ShellWindow::SizeConstraints::set_minimum_size(const gfx::Size& min_size) {
117 minimum_size_ = min_size;
120 void ShellWindow::SizeConstraints::set_maximum_size(const gfx::Size& max_size) {
121 maximum_size_ = max_size;
124 ShellWindow::CreateParams::CreateParams()
125 : window_type(ShellWindow::WINDOW_TYPE_DEFAULT),
126 frame(ShellWindow::FRAME_CHROME),
127 transparent_background(false),
128 bounds(INT_MIN, INT_MIN, 0, 0),
129 creator_process_id(0),
130 state(ui::SHOW_STATE_DEFAULT),
131 hidden(false),
132 resizable(true),
133 focused(true),
134 always_on_top(false) {}
136 ShellWindow::CreateParams::~CreateParams() {}
138 ShellWindow::Delegate::~Delegate() {}
140 ShellWindow::ShellWindow(Profile* profile,
141 Delegate* delegate,
142 const extensions::Extension* extension)
143 : profile_(profile),
144 extension_(extension),
145 extension_id_(extension->id()),
146 window_type_(WINDOW_TYPE_DEFAULT),
147 delegate_(delegate),
148 image_loader_ptr_factory_(this),
149 fullscreen_types_(FULLSCREEN_TYPE_NONE),
150 show_on_first_paint_(false),
151 first_paint_complete_(false),
152 cached_always_on_top_(false) {
153 CHECK(!profile->IsGuestSession() || profile->IsOffTheRecord())
154 << "Only off the record window may be opened in the guest mode.";
157 void ShellWindow::Init(const GURL& url,
158 ShellWindowContents* shell_window_contents,
159 const CreateParams& params) {
160 // Initialize the render interface and web contents
161 shell_window_contents_.reset(shell_window_contents);
162 shell_window_contents_->Initialize(profile(), url);
163 WebContents* web_contents = shell_window_contents_->GetWebContents();
164 if (CommandLine::ForCurrentProcess()->HasSwitch(
165 switches::kEnableAppsShowOnFirstPaint)) {
166 content::WebContentsObserver::Observe(web_contents);
168 delegate_->InitWebContents(web_contents);
169 WebContentsModalDialogManager::CreateForWebContents(web_contents);
170 extensions::ExtensionWebContentsObserver::CreateForWebContents(web_contents);
172 web_contents->SetDelegate(this);
173 WebContentsModalDialogManager::FromWebContents(web_contents)->
174 SetDelegate(this);
175 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_SHELL);
177 // Initialize the window
178 CreateParams new_params = LoadDefaultsAndConstrain(params);
179 window_type_ = new_params.window_type;
180 window_key_ = new_params.window_key;
181 size_constraints_ = SizeConstraints(new_params.minimum_size,
182 new_params.maximum_size);
184 // Windows cannot be always-on-top in fullscreen mode for security reasons.
185 cached_always_on_top_ = new_params.always_on_top;
186 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
187 new_params.always_on_top = false;
189 native_app_window_.reset(delegate_->CreateNativeAppWindow(this, new_params));
191 if (!new_params.hidden) {
192 // Panels are not activated by default.
193 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
194 : SHOW_ACTIVE);
197 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
198 Fullscreen();
199 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
200 Maximize();
201 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
202 Minimize();
204 OnNativeWindowChanged();
206 // When the render view host is changed, the native window needs to know
207 // about it in case it has any setup to do to make the renderer appear
208 // properly. In particular, on Windows, the view's clickthrough region needs
209 // to be set.
210 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
211 content::Source<Profile>(profile_->GetOriginalProfile()));
212 // Close when the browser process is exiting.
213 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
214 content::NotificationService::AllSources());
216 shell_window_contents_->LoadContents(new_params.creator_process_id);
218 if (CommandLine::ForCurrentProcess()->HasSwitch(
219 switches::kEnableAppsShowOnFirstPaint)) {
220 // We want to show the window only when the content has been painted. For
221 // that to happen, we need to define a size for the content, otherwise the
222 // layout will happen in a 0x0 area.
223 // Note: WebContents::GetView() is guaranteed to be non-null.
224 web_contents->GetView()->SizeContents(new_params.bounds.size());
227 // Prevent the browser process from shutting down while this window is open.
228 chrome::StartKeepAlive();
230 UpdateExtensionAppIcon();
232 ShellWindowRegistry::Get(profile_)->AddShellWindow(this);
235 ShellWindow::~ShellWindow() {
236 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
237 // last window open.
238 registrar_.RemoveAll();
240 // Remove shutdown prevention.
241 chrome::EndKeepAlive();
244 void ShellWindow::RequestMediaAccessPermission(
245 content::WebContents* web_contents,
246 const content::MediaStreamRequest& request,
247 const content::MediaResponseCallback& callback) {
248 delegate_->RequestMediaAccessPermission(web_contents, request, callback,
249 extension());
252 WebContents* ShellWindow::OpenURLFromTab(WebContents* source,
253 const content::OpenURLParams& params) {
254 // Don't allow the current tab to be navigated. It would be nice to map all
255 // anchor tags (even those without target="_blank") to new tabs, but right
256 // now we can't distinguish between those and <meta> refreshes or window.href
257 // navigations, which we don't want to allow.
258 // TOOD(mihaip): Can we check for user gestures instead?
259 WindowOpenDisposition disposition = params.disposition;
260 if (disposition == CURRENT_TAB) {
261 AddMessageToDevToolsConsole(
262 content::CONSOLE_MESSAGE_LEVEL_ERROR,
263 base::StringPrintf(
264 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
265 params.url.spec().c_str()));
266 return NULL;
269 // These dispositions aren't really navigations.
270 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
271 disposition == IGNORE_ACTION) {
272 return NULL;
275 WebContents* contents = delegate_->OpenURLFromTab(profile_, source,
276 params);
277 if (!contents) {
278 AddMessageToDevToolsConsole(
279 content::CONSOLE_MESSAGE_LEVEL_ERROR,
280 base::StringPrintf(
281 "Can't navigate to \"%s\"; apps do not support navigation.",
282 params.url.spec().c_str()));
285 return contents;
288 void ShellWindow::AddNewContents(WebContents* source,
289 WebContents* new_contents,
290 WindowOpenDisposition disposition,
291 const gfx::Rect& initial_pos,
292 bool user_gesture,
293 bool* was_blocked) {
294 DCHECK(Profile::FromBrowserContext(new_contents->GetBrowserContext()) ==
295 profile_);
296 delegate_->AddNewContents(profile_, new_contents, disposition,
297 initial_pos, user_gesture, was_blocked);
300 bool ShellWindow::PreHandleKeyboardEvent(
301 content::WebContents* source,
302 const content::NativeWebKeyboardEvent& event,
303 bool* is_keyboard_shortcut) {
304 // Here, we can handle a key event before the content gets it. When we are
305 // fullscreen and it is not forced, we want to allow the user to leave
306 // when ESC is pressed.
307 // However, if the application has the "overrideEscFullscreen" permission, we
308 // should let it override that behavior.
309 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
310 // action is not prevented.
311 // Thus, we should handle the KeyEvent here only if the permission is not set.
312 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
313 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
314 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0) &&
315 !extension_->HasAPIPermission(APIPermission::kOverrideEscFullscreen)) {
316 Restore();
317 return true;
320 return false;
323 void ShellWindow::HandleKeyboardEvent(
324 WebContents* source,
325 const content::NativeWebKeyboardEvent& event) {
326 // If the window is currently fullscreen and not forced, ESC should leave
327 // fullscreen. If this code is being called for ESC, that means that the
328 // KeyEvent's default behavior was not prevented by the content.
329 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
330 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
331 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0)) {
332 Restore();
333 return;
336 native_app_window_->HandleKeyboardEvent(event);
339 void ShellWindow::RequestToLockMouse(WebContents* web_contents,
340 bool user_gesture,
341 bool last_unlocked_by_target) {
342 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
343 APIPermission::kPointerLock,
344 extension_,
345 web_contents->GetRenderViewHost());
347 web_contents->GotResponseToLockMouseRequest(has_permission);
350 bool ShellWindow::PreHandleGestureEvent(
351 WebContents* source,
352 const blink::WebGestureEvent& event) {
353 // Disable pinch zooming in shell windows.
354 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
355 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
356 event.type == blink::WebGestureEvent::GesturePinchEnd;
359 void ShellWindow::DidFirstVisuallyNonEmptyPaint(int32 page_id) {
360 first_paint_complete_ = true;
361 if (show_on_first_paint_) {
362 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
363 delayed_show_type_ == SHOW_INACTIVE);
364 Show(delayed_show_type_);
368 void ShellWindow::OnNativeClose() {
369 ShellWindowRegistry::Get(profile_)->RemoveShellWindow(this);
370 if (shell_window_contents_) {
371 WebContents* web_contents = shell_window_contents_->GetWebContents();
372 WebContentsModalDialogManager::FromWebContents(web_contents)->
373 SetDelegate(NULL);
374 shell_window_contents_->NativeWindowClosed();
376 delete this;
379 void ShellWindow::OnNativeWindowChanged() {
380 SaveWindowPosition();
382 #if defined(OS_WIN)
383 if (native_app_window_ &&
384 cached_always_on_top_ &&
385 !IsFullscreen(fullscreen_types_) &&
386 !native_app_window_->IsMaximized() &&
387 !native_app_window_->IsMinimized()) {
388 UpdateNativeAlwaysOnTop();
390 #endif
392 if (shell_window_contents_ && native_app_window_)
393 shell_window_contents_->NativeWindowChanged(native_app_window_.get());
396 void ShellWindow::OnNativeWindowActivated() {
397 ShellWindowRegistry::Get(profile_)->ShellWindowActivated(this);
400 content::WebContents* ShellWindow::web_contents() const {
401 return shell_window_contents_->GetWebContents();
404 NativeAppWindow* ShellWindow::GetBaseWindow() {
405 return native_app_window_.get();
408 gfx::NativeWindow ShellWindow::GetNativeWindow() {
409 return GetBaseWindow()->GetNativeWindow();
412 gfx::Rect ShellWindow::GetClientBounds() const {
413 gfx::Rect bounds = native_app_window_->GetBounds();
414 bounds.Inset(native_app_window_->GetFrameInsets());
415 return bounds;
418 base::string16 ShellWindow::GetTitle() const {
419 // WebContents::GetTitle() will return the page's URL if there's no <title>
420 // specified. However, we'd prefer to show the name of the extension in that
421 // case, so we directly inspect the NavigationEntry's title.
422 base::string16 title;
423 if (!web_contents() ||
424 !web_contents()->GetController().GetActiveEntry() ||
425 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
426 title = base::UTF8ToUTF16(extension()->name());
427 } else {
428 title = web_contents()->GetTitle();
430 const base::char16 kBadChars[] = { '\n', 0 };
431 base::RemoveChars(title, kBadChars, &title);
432 return title;
435 void ShellWindow::SetAppIconUrl(const GURL& url) {
436 // Avoid using any previous app icons were are being downloaded.
437 image_loader_ptr_factory_.InvalidateWeakPtrs();
439 // Reset |app_icon_image_| to abort pending image load (if any).
440 app_icon_image_.reset();
442 app_icon_url_ = url;
443 web_contents()->DownloadImage(
444 url,
445 true, // is a favicon
446 0, // no maximum size
447 base::Bind(&ShellWindow::DidDownloadFavicon,
448 image_loader_ptr_factory_.GetWeakPtr()));
451 void ShellWindow::UpdateShape(scoped_ptr<SkRegion> region) {
452 native_app_window_->UpdateShape(region.Pass());
455 void ShellWindow::UpdateDraggableRegions(
456 const std::vector<extensions::DraggableRegion>& regions) {
457 native_app_window_->UpdateDraggableRegions(regions);
460 void ShellWindow::UpdateAppIcon(const gfx::Image& image) {
461 if (image.IsEmpty())
462 return;
463 app_icon_ = image;
464 native_app_window_->UpdateWindowIcon();
465 ShellWindowRegistry::Get(profile_)->ShellWindowIconChanged(this);
468 void ShellWindow::Fullscreen() {
469 #if !defined(OS_MACOSX)
470 // Do not enter fullscreen mode if disallowed by pref.
471 if (!profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed))
472 return;
473 #endif
474 fullscreen_types_ |= FULLSCREEN_TYPE_WINDOW_API;
475 SetNativeWindowFullscreen();
478 void ShellWindow::Maximize() {
479 GetBaseWindow()->Maximize();
482 void ShellWindow::Minimize() {
483 GetBaseWindow()->Minimize();
486 void ShellWindow::Restore() {
487 if (IsFullscreen(fullscreen_types_)) {
488 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
489 SetNativeWindowFullscreen();
490 } else {
491 GetBaseWindow()->Restore();
495 void ShellWindow::OSFullscreen() {
496 #if !defined(OS_MACOSX)
497 // Do not enter fullscreen mode if disallowed by pref.
498 if (!profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed))
499 return;
500 #endif
501 fullscreen_types_ |= FULLSCREEN_TYPE_OS;
502 SetNativeWindowFullscreen();
505 void ShellWindow::ForcedFullscreen() {
506 fullscreen_types_ |= FULLSCREEN_TYPE_FORCED;
507 SetNativeWindowFullscreen();
510 void ShellWindow::SetMinimumSize(const gfx::Size& min_size) {
511 size_constraints_.set_minimum_size(min_size);
512 OnSizeConstraintsChanged();
515 void ShellWindow::SetMaximumSize(const gfx::Size& max_size) {
516 size_constraints_.set_maximum_size(max_size);
517 OnSizeConstraintsChanged();
520 void ShellWindow::Show(ShowType show_type) {
521 if (CommandLine::ForCurrentProcess()->HasSwitch(
522 switches::kEnableAppsShowOnFirstPaint)) {
523 show_on_first_paint_ = true;
525 if (!first_paint_complete_) {
526 delayed_show_type_ = show_type;
527 return;
531 switch (show_type) {
532 case SHOW_ACTIVE:
533 GetBaseWindow()->Show();
534 break;
535 case SHOW_INACTIVE:
536 GetBaseWindow()->ShowInactive();
537 break;
541 void ShellWindow::Hide() {
542 // This is there to prevent race conditions with Hide() being called before
543 // there was a non-empty paint. It should have no effect in a non-racy
544 // scenario where the application is hiding then showing a window: the second
545 // show will not be delayed.
546 show_on_first_paint_ = false;
547 GetBaseWindow()->Hide();
550 void ShellWindow::SetAlwaysOnTop(bool always_on_top) {
551 if (cached_always_on_top_ == always_on_top)
552 return;
554 cached_always_on_top_ = always_on_top;
556 // As a security measure, do not allow fullscreen windows or windows that
557 // overlap the taskbar to be on top. The property will be applied when the
558 // window exits fullscreen and moves away from the taskbar.
559 if (!IsFullscreen(fullscreen_types_) && !IntersectsWithTaskbar())
560 native_app_window_->SetAlwaysOnTop(always_on_top);
562 OnNativeWindowChanged();
565 bool ShellWindow::IsAlwaysOnTop() const {
566 return cached_always_on_top_;
569 //------------------------------------------------------------------------------
570 // Private methods
572 void ShellWindow::DidDownloadFavicon(
573 int id,
574 int http_status_code,
575 const GURL& image_url,
576 const std::vector<SkBitmap>& bitmaps,
577 const std::vector<gfx::Size>& original_bitmap_sizes) {
578 if (image_url != app_icon_url_ || bitmaps.empty())
579 return;
581 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
582 // whose height >= the preferred size.
583 int largest_index = 0;
584 for (size_t i = 1; i < bitmaps.size(); ++i) {
585 if (bitmaps[i].height() < delegate_->PreferredIconSize())
586 break;
587 largest_index = i;
589 const SkBitmap& largest = bitmaps[largest_index];
590 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
593 void ShellWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
594 DCHECK_EQ(app_icon_image_.get(), image);
596 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
599 void ShellWindow::UpdateExtensionAppIcon() {
600 // Avoid using any previous app icons were are being downloaded.
601 image_loader_ptr_factory_.InvalidateWeakPtrs();
603 app_icon_image_.reset(new extensions::IconImage(
604 profile(),
605 extension(),
606 extensions::IconsInfo::GetIcons(extension()),
607 delegate_->PreferredIconSize(),
608 extensions::IconsInfo::GetDefaultAppIcon(),
609 this));
611 // Triggers actual image loading with 1x resources. The 2x resource will
612 // be handled by IconImage class when requested.
613 app_icon_image_->image_skia().GetRepresentation(1.0f);
616 void ShellWindow::OnSizeConstraintsChanged() {
617 native_app_window_->UpdateWindowMinMaxSize();
618 gfx::Rect bounds = GetClientBounds();
619 gfx::Size constrained_size = size_constraints_.ClampSize(bounds.size());
620 if (bounds.size() != constrained_size) {
621 bounds.set_size(constrained_size);
622 native_app_window_->SetBounds(bounds);
624 OnNativeWindowChanged();
627 void ShellWindow::SetNativeWindowFullscreen() {
628 native_app_window_->SetFullscreen(fullscreen_types_);
630 if (cached_always_on_top_)
631 UpdateNativeAlwaysOnTop();
634 bool ShellWindow::IntersectsWithTaskbar() const {
635 #if defined(OS_WIN)
636 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
637 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
638 std::vector<gfx::Display> displays = screen->GetAllDisplays();
640 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
641 it != displays.end(); ++it) {
642 gfx::Rect taskbar_bounds = it->bounds();
643 taskbar_bounds.Subtract(it->work_area());
644 if (taskbar_bounds.IsEmpty())
645 continue;
647 if (window_bounds.Intersects(taskbar_bounds))
648 return true;
650 #endif
652 return false;
655 void ShellWindow::UpdateNativeAlwaysOnTop() {
656 DCHECK(cached_always_on_top_);
657 bool is_on_top = native_app_window_->IsAlwaysOnTop();
658 bool fullscreen = IsFullscreen(fullscreen_types_);
659 bool intersects_taskbar = IntersectsWithTaskbar();
661 if (is_on_top && (fullscreen || intersects_taskbar)) {
662 // When entering fullscreen or overlapping the taskbar, ensure windows are
663 // not always-on-top.
664 native_app_window_->SetAlwaysOnTop(false);
665 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
666 // When exiting fullscreen and moving away from the taskbar, reinstate
667 // always-on-top.
668 native_app_window_->SetAlwaysOnTop(true);
672 void ShellWindow::CloseContents(WebContents* contents) {
673 native_app_window_->Close();
676 bool ShellWindow::ShouldSuppressDialogs() {
677 return true;
680 content::ColorChooser* ShellWindow::OpenColorChooser(
681 WebContents* web_contents,
682 SkColor initial_color,
683 const std::vector<content::ColorSuggestion>& suggestionss) {
684 return delegate_->ShowColorChooser(web_contents, initial_color);
687 void ShellWindow::RunFileChooser(WebContents* tab,
688 const content::FileChooserParams& params) {
689 if (window_type_is_panel()) {
690 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
691 // dialogs to be unhosted but still close with the owning web contents.
692 // crbug.com/172502.
693 LOG(WARNING) << "File dialog opened by panel.";
694 return;
697 delegate_->RunFileChooser(tab, params);
700 bool ShellWindow::IsPopupOrPanel(const WebContents* source) const {
701 return true;
704 void ShellWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
705 native_app_window_->SetBounds(pos);
708 void ShellWindow::NavigationStateChanged(
709 const content::WebContents* source, unsigned changed_flags) {
710 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
711 native_app_window_->UpdateWindowTitle();
712 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
713 native_app_window_->UpdateWindowIcon();
716 void ShellWindow::ToggleFullscreenModeForTab(content::WebContents* source,
717 bool enter_fullscreen) {
718 #if !defined(OS_MACOSX)
719 // Do not enter fullscreen mode if disallowed by pref.
720 // TODO(bartfab): Add a test once it becomes possible to simulate a user
721 // gesture. http://crbug.com/174178
722 if (enter_fullscreen &&
723 !profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed)) {
724 return;
726 #endif
728 if (!IsExtensionWithPermissionOrSuggestInConsole(
729 APIPermission::kFullscreen,
730 extension_,
731 source->GetRenderViewHost())) {
732 return;
735 if (enter_fullscreen)
736 fullscreen_types_ |= FULLSCREEN_TYPE_HTML_API;
737 else
738 fullscreen_types_ &= ~FULLSCREEN_TYPE_HTML_API;
739 SetNativeWindowFullscreen();
742 bool ShellWindow::IsFullscreenForTabOrPending(
743 const content::WebContents* source) const {
744 return ((fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0);
747 void ShellWindow::Observe(int type,
748 const content::NotificationSource& source,
749 const content::NotificationDetails& details) {
750 switch (type) {
751 case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
752 const extensions::Extension* unloaded_extension =
753 content::Details<extensions::UnloadedExtensionInfo>(
754 details)->extension;
755 if (extension_ == unloaded_extension)
756 native_app_window_->Close();
757 break;
759 case chrome::NOTIFICATION_APP_TERMINATING:
760 native_app_window_->Close();
761 break;
762 default:
763 NOTREACHED() << "Received unexpected notification";
767 void ShellWindow::SetWebContentsBlocked(content::WebContents* web_contents,
768 bool blocked) {
769 delegate_->SetWebContentsBlocked(web_contents, blocked);
772 bool ShellWindow::IsWebContentsVisible(content::WebContents* web_contents) {
773 return delegate_->IsWebContentsVisible(web_contents);
776 extensions::ActiveTabPermissionGranter*
777 ShellWindow::GetActiveTabPermissionGranter() {
778 // Shell windows don't support the activeTab permission.
779 return NULL;
782 WebContentsModalDialogHost* ShellWindow::GetWebContentsModalDialogHost() {
783 return native_app_window_.get();
786 void ShellWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
787 const std::string& message) {
788 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
789 rvh->Send(new ExtensionMsg_AddMessageToConsole(
790 rvh->GetRoutingID(), level, message));
793 void ShellWindow::SaveWindowPosition() {
794 if (window_key_.empty())
795 return;
796 if (!native_app_window_)
797 return;
799 ShellWindowGeometryCache* cache = ShellWindowGeometryCache::Get(profile());
801 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
802 bounds.Inset(native_app_window_->GetFrameInsets());
803 gfx::Rect screen_bounds =
804 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
805 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
806 cache->SaveGeometry(extension()->id(),
807 window_key_,
808 bounds,
809 screen_bounds,
810 window_state);
813 void ShellWindow::AdjustBoundsToBeVisibleOnScreen(
814 const gfx::Rect& cached_bounds,
815 const gfx::Rect& cached_screen_bounds,
816 const gfx::Rect& current_screen_bounds,
817 const gfx::Size& minimum_size,
818 gfx::Rect* bounds) const {
819 *bounds = cached_bounds;
821 // Reposition and resize the bounds if the cached_screen_bounds is different
822 // from the current screen bounds and the current screen bounds doesn't
823 // completely contain the bounds.
824 if (cached_screen_bounds != current_screen_bounds &&
825 !current_screen_bounds.Contains(cached_bounds)) {
826 bounds->set_width(
827 std::max(minimum_size.width(),
828 std::min(bounds->width(), current_screen_bounds.width())));
829 bounds->set_height(
830 std::max(minimum_size.height(),
831 std::min(bounds->height(), current_screen_bounds.height())));
832 bounds->set_x(
833 std::max(current_screen_bounds.x(),
834 std::min(bounds->x(),
835 current_screen_bounds.right() - bounds->width())));
836 bounds->set_y(
837 std::max(current_screen_bounds.y(),
838 std::min(bounds->y(),
839 current_screen_bounds.bottom() - bounds->height())));
843 ShellWindow::CreateParams ShellWindow::LoadDefaultsAndConstrain(
844 CreateParams params) const {
845 if (params.bounds.width() == 0)
846 params.bounds.set_width(kDefaultWidth);
847 if (params.bounds.height() == 0)
848 params.bounds.set_height(kDefaultHeight);
850 // If left and top are left undefined, the native shell window will center
851 // the window on the main screen in a platform-defined manner.
853 // Load cached state if it exists.
854 if (!params.window_key.empty()) {
855 ShellWindowGeometryCache* cache = ShellWindowGeometryCache::Get(profile());
857 gfx::Rect cached_bounds;
858 gfx::Rect cached_screen_bounds;
859 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
860 if (cache->GetGeometry(extension()->id(), params.window_key,
861 &cached_bounds, &cached_screen_bounds,
862 &cached_state)) {
863 // App window has cached screen bounds, make sure it fits on screen in
864 // case the screen resolution changed.
865 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
866 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
867 gfx::Rect current_screen_bounds = display.work_area();
868 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
869 cached_screen_bounds,
870 current_screen_bounds,
871 params.minimum_size,
872 &params.bounds);
873 params.state = cached_state;
877 SizeConstraints size_constraints(params.minimum_size, params.maximum_size);
878 params.bounds.set_size(size_constraints.ClampSize(params.bounds.size()));
879 params.minimum_size = size_constraints.GetMinimumSize();
880 params.maximum_size = size_constraints.GetMaximumSize();
882 return params;
885 // static
886 SkRegion* ShellWindow::RawDraggableRegionsToSkRegion(
887 const std::vector<extensions::DraggableRegion>& regions) {
888 SkRegion* sk_region = new SkRegion;
889 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
890 regions.begin();
891 iter != regions.end(); ++iter) {
892 const extensions::DraggableRegion& region = *iter;
893 sk_region->op(
894 region.bounds.x(),
895 region.bounds.y(),
896 region.bounds.right(),
897 region.bounds.bottom(),
898 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
900 return sk_region;
903 } // namespace apps