Have pretty_print.py find histograms.xml.
[chromium-blink-merge.git] / apps / shell_window.cc
blob1d358c448eef18d8efae99833fbcc9fb45a65b32
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_system.h"
16 #include "chrome/browser/extensions/extension_web_contents_observer.h"
17 #include "chrome/browser/extensions/suggest_permission_util.h"
18 #include "chrome/browser/lifetime/application_lifetime.h"
19 #include "chrome/browser/profiles/profile.h"
20 #include "chrome/common/chrome_switches.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/browser/web_contents_view.h"
34 #include "content/public/common/media_stream_request.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 } // namespace
59 namespace apps {
61 ShellWindow::SizeConstraints::SizeConstraints()
62 : maximum_size_(kUnboundedSize, kUnboundedSize) {
65 ShellWindow::SizeConstraints::SizeConstraints(const gfx::Size& min_size,
66 const gfx::Size& max_size)
67 : minimum_size_(min_size),
68 maximum_size_(max_size) {
71 ShellWindow::SizeConstraints::~SizeConstraints() {}
73 gfx::Size ShellWindow::SizeConstraints::ClampSize(gfx::Size size) const {
74 const gfx::Size max_size = GetMaximumSize();
75 if (max_size.width() != kUnboundedSize)
76 size.set_width(std::min(size.width(), GetMaximumSize().width()));
77 if (max_size.height() != kUnboundedSize)
78 size.set_height(std::min(size.height(), GetMaximumSize().height()));
79 size.SetToMax(GetMinimumSize());
80 return size;
83 bool ShellWindow::SizeConstraints::HasMinimumSize() const {
84 return GetMinimumSize().width() != kUnboundedSize ||
85 GetMinimumSize().height() != kUnboundedSize;
88 bool ShellWindow::SizeConstraints::HasMaximumSize() const {
89 const gfx::Size max_size = GetMaximumSize();
90 return max_size.width() != kUnboundedSize ||
91 max_size.height() != kUnboundedSize;
94 bool ShellWindow::SizeConstraints::HasFixedSize() const {
95 return !GetMinimumSize().IsEmpty() && GetMinimumSize() == GetMaximumSize();
98 gfx::Size ShellWindow::SizeConstraints::GetMinimumSize() const {
99 return minimum_size_;
102 gfx::Size ShellWindow::SizeConstraints::GetMaximumSize() const {
103 return gfx::Size(
104 maximum_size_.width() == kUnboundedSize ?
105 kUnboundedSize :
106 std::max(maximum_size_.width(), minimum_size_.width()),
107 maximum_size_.height() == kUnboundedSize ?
108 kUnboundedSize :
109 std::max(maximum_size_.height(), minimum_size_.height()));
112 void ShellWindow::SizeConstraints::set_minimum_size(const gfx::Size& min_size) {
113 minimum_size_ = min_size;
116 void ShellWindow::SizeConstraints::set_maximum_size(const gfx::Size& max_size) {
117 maximum_size_ = max_size;
120 ShellWindow::CreateParams::CreateParams()
121 : window_type(ShellWindow::WINDOW_TYPE_DEFAULT),
122 frame(ShellWindow::FRAME_CHROME),
123 transparent_background(false),
124 bounds(INT_MIN, INT_MIN, 0, 0),
125 creator_process_id(0),
126 state(ui::SHOW_STATE_DEFAULT),
127 hidden(false),
128 resizable(true),
129 focused(true),
130 always_on_top(false) {}
132 ShellWindow::CreateParams::~CreateParams() {}
134 ShellWindow::Delegate::~Delegate() {}
136 ShellWindow::ShellWindow(Profile* profile,
137 Delegate* delegate,
138 const extensions::Extension* extension)
139 : profile_(profile),
140 extension_(extension),
141 extension_id_(extension->id()),
142 window_type_(WINDOW_TYPE_DEFAULT),
143 delegate_(delegate),
144 image_loader_ptr_factory_(this),
145 fullscreen_types_(FULLSCREEN_TYPE_NONE),
146 show_on_first_paint_(false),
147 first_paint_complete_(false),
148 cached_always_on_top_(false) {
151 void ShellWindow::Init(const GURL& url,
152 ShellWindowContents* shell_window_contents,
153 const CreateParams& params) {
154 // Initialize the render interface and web contents
155 shell_window_contents_.reset(shell_window_contents);
156 shell_window_contents_->Initialize(profile(), url);
157 WebContents* web_contents = shell_window_contents_->GetWebContents();
158 if (CommandLine::ForCurrentProcess()->HasSwitch(
159 switches::kEnableAppsShowOnFirstPaint)) {
160 content::WebContentsObserver::Observe(web_contents);
162 delegate_->InitWebContents(web_contents);
163 WebContentsModalDialogManager::CreateForWebContents(web_contents);
164 extensions::ExtensionWebContentsObserver::CreateForWebContents(web_contents);
166 web_contents->SetDelegate(this);
167 WebContentsModalDialogManager::FromWebContents(web_contents)->
168 SetDelegate(this);
169 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_SHELL);
171 // Initialize the window
172 CreateParams new_params = LoadDefaultsAndConstrain(params);
173 window_type_ = new_params.window_type;
174 window_key_ = new_params.window_key;
175 size_constraints_ = SizeConstraints(new_params.minimum_size,
176 new_params.maximum_size);
178 // Windows cannot be always-on-top in fullscreen mode for security reasons.
179 cached_always_on_top_ = new_params.always_on_top;
180 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
181 new_params.always_on_top = false;
183 native_app_window_.reset(delegate_->CreateNativeAppWindow(this, new_params));
185 if (!new_params.hidden) {
186 // Panels are not activated by default.
187 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
188 : SHOW_ACTIVE);
191 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
192 Fullscreen();
193 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
194 Maximize();
195 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
196 Minimize();
198 OnNativeWindowChanged();
200 // When the render view host is changed, the native window needs to know
201 // about it in case it has any setup to do to make the renderer appear
202 // properly. In particular, on Windows, the view's clickthrough region needs
203 // to be set.
204 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_UNLOADED,
205 content::Source<Profile>(profile_));
206 // Close when the browser process is exiting.
207 registrar_.Add(this, chrome::NOTIFICATION_APP_TERMINATING,
208 content::NotificationService::AllSources());
210 shell_window_contents_->LoadContents(new_params.creator_process_id);
212 if (CommandLine::ForCurrentProcess()->HasSwitch(
213 switches::kEnableAppsShowOnFirstPaint)) {
214 // We want to show the window only when the content has been painted. For
215 // that to happen, we need to define a size for the content, otherwise the
216 // layout will happen in a 0x0 area.
217 // Note: WebContents::GetView() is guaranteed to be non-null.
218 web_contents->GetView()->SizeContents(new_params.bounds.size());
221 // Prevent the browser process from shutting down while this window is open.
222 chrome::StartKeepAlive();
224 UpdateExtensionAppIcon();
226 ShellWindowRegistry::Get(profile_)->AddShellWindow(this);
229 ShellWindow::~ShellWindow() {
230 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
231 // last window open.
232 registrar_.RemoveAll();
234 // Remove shutdown prevention.
235 chrome::EndKeepAlive();
238 void ShellWindow::RequestMediaAccessPermission(
239 content::WebContents* web_contents,
240 const content::MediaStreamRequest& request,
241 const content::MediaResponseCallback& callback) {
242 delegate_->RequestMediaAccessPermission(web_contents, request, callback,
243 extension());
246 WebContents* ShellWindow::OpenURLFromTab(WebContents* source,
247 const content::OpenURLParams& params) {
248 // Don't allow the current tab to be navigated. It would be nice to map all
249 // anchor tags (even those without target="_blank") to new tabs, but right
250 // now we can't distinguish between those and <meta> refreshes or window.href
251 // navigations, which we don't want to allow.
252 // TOOD(mihaip): Can we check for user gestures instead?
253 WindowOpenDisposition disposition = params.disposition;
254 if (disposition == CURRENT_TAB) {
255 AddMessageToDevToolsConsole(
256 content::CONSOLE_MESSAGE_LEVEL_ERROR,
257 base::StringPrintf(
258 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
259 params.url.spec().c_str()));
260 return NULL;
263 // These dispositions aren't really navigations.
264 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
265 disposition == IGNORE_ACTION) {
266 return NULL;
269 WebContents* contents = delegate_->OpenURLFromTab(profile_, source,
270 params);
271 if (!contents) {
272 AddMessageToDevToolsConsole(
273 content::CONSOLE_MESSAGE_LEVEL_ERROR,
274 base::StringPrintf(
275 "Can't navigate to \"%s\"; apps do not support navigation.",
276 params.url.spec().c_str()));
279 return contents;
282 void ShellWindow::AddNewContents(WebContents* source,
283 WebContents* new_contents,
284 WindowOpenDisposition disposition,
285 const gfx::Rect& initial_pos,
286 bool user_gesture,
287 bool* was_blocked) {
288 DCHECK(Profile::FromBrowserContext(new_contents->GetBrowserContext()) ==
289 profile_);
290 delegate_->AddNewContents(profile_, new_contents, disposition,
291 initial_pos, user_gesture, was_blocked);
294 bool ShellWindow::PreHandleKeyboardEvent(
295 content::WebContents* source,
296 const content::NativeWebKeyboardEvent& event,
297 bool* is_keyboard_shortcut) {
298 // Here, we can handle a key event before the content gets it. When we are
299 // fullscreen and it is not forced, we want to allow the user to leave
300 // when ESC is pressed.
301 // However, if the application has the "overrideEscFullscreen" permission, we
302 // should let it override that behavior.
303 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
304 // action is not prevented.
305 // Thus, we should handle the KeyEvent here only if the permission is not set.
306 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
307 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
308 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0) &&
309 !extension_->HasAPIPermission(APIPermission::kOverrideEscFullscreen)) {
310 Restore();
311 return true;
314 return false;
317 void ShellWindow::HandleKeyboardEvent(
318 WebContents* source,
319 const content::NativeWebKeyboardEvent& event) {
320 // If the window is currently fullscreen and not forced, ESC should leave
321 // fullscreen. If this code is being called for ESC, that means that the
322 // KeyEvent's default behavior was not prevented by the content.
323 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
324 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
325 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0)) {
326 Restore();
327 return;
330 native_app_window_->HandleKeyboardEvent(event);
333 void ShellWindow::RequestToLockMouse(WebContents* web_contents,
334 bool user_gesture,
335 bool last_unlocked_by_target) {
336 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
337 APIPermission::kPointerLock,
338 extension_,
339 web_contents->GetRenderViewHost());
341 web_contents->GotResponseToLockMouseRequest(has_permission);
344 void ShellWindow::DidFirstVisuallyNonEmptyPaint(int32 page_id) {
345 first_paint_complete_ = true;
346 if (show_on_first_paint_) {
347 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
348 delayed_show_type_ == SHOW_INACTIVE);
349 Show(delayed_show_type_);
353 void ShellWindow::OnNativeClose() {
354 ShellWindowRegistry::Get(profile_)->RemoveShellWindow(this);
355 if (shell_window_contents_) {
356 WebContents* web_contents = shell_window_contents_->GetWebContents();
357 WebContentsModalDialogManager::FromWebContents(web_contents)->
358 SetDelegate(NULL);
359 shell_window_contents_->NativeWindowClosed();
361 delete this;
364 void ShellWindow::OnNativeWindowChanged() {
365 SaveWindowPosition();
366 if (shell_window_contents_ && native_app_window_)
367 shell_window_contents_->NativeWindowChanged(native_app_window_.get());
370 void ShellWindow::OnNativeWindowActivated() {
371 ShellWindowRegistry::Get(profile_)->ShellWindowActivated(this);
374 content::WebContents* ShellWindow::web_contents() const {
375 return shell_window_contents_->GetWebContents();
378 NativeAppWindow* ShellWindow::GetBaseWindow() {
379 return native_app_window_.get();
382 gfx::NativeWindow ShellWindow::GetNativeWindow() {
383 return GetBaseWindow()->GetNativeWindow();
386 gfx::Rect ShellWindow::GetClientBounds() const {
387 gfx::Rect bounds = native_app_window_->GetBounds();
388 bounds.Inset(native_app_window_->GetFrameInsets());
389 return bounds;
392 base::string16 ShellWindow::GetTitle() const {
393 // WebContents::GetTitle() will return the page's URL if there's no <title>
394 // specified. However, we'd prefer to show the name of the extension in that
395 // case, so we directly inspect the NavigationEntry's title.
396 base::string16 title;
397 if (!web_contents() ||
398 !web_contents()->GetController().GetActiveEntry() ||
399 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
400 title = base::UTF8ToUTF16(extension()->name());
401 } else {
402 title = web_contents()->GetTitle();
404 const base::char16 kBadChars[] = { '\n', 0 };
405 base::RemoveChars(title, kBadChars, &title);
406 return title;
409 void ShellWindow::SetAppIconUrl(const GURL& url) {
410 // Avoid using any previous app icons were are being downloaded.
411 image_loader_ptr_factory_.InvalidateWeakPtrs();
413 // Reset |app_icon_image_| to abort pending image load (if any).
414 app_icon_image_.reset();
416 app_icon_url_ = url;
417 web_contents()->DownloadImage(
418 url,
419 true, // is a favicon
420 0, // no maximum size
421 base::Bind(&ShellWindow::DidDownloadFavicon,
422 image_loader_ptr_factory_.GetWeakPtr()));
425 void ShellWindow::UpdateShape(scoped_ptr<SkRegion> region) {
426 native_app_window_->UpdateShape(region.Pass());
429 void ShellWindow::UpdateDraggableRegions(
430 const std::vector<extensions::DraggableRegion>& regions) {
431 native_app_window_->UpdateDraggableRegions(regions);
434 void ShellWindow::UpdateAppIcon(const gfx::Image& image) {
435 if (image.IsEmpty())
436 return;
437 app_icon_ = image;
438 native_app_window_->UpdateWindowIcon();
439 ShellWindowRegistry::Get(profile_)->ShellWindowIconChanged(this);
442 void ShellWindow::Fullscreen() {
443 #if !defined(OS_MACOSX)
444 // Do not enter fullscreen mode if disallowed by pref.
445 if (!profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed))
446 return;
447 #endif
448 fullscreen_types_ |= FULLSCREEN_TYPE_WINDOW_API;
449 SetNativeWindowFullscreen(fullscreen_types_);
452 void ShellWindow::Maximize() {
453 GetBaseWindow()->Maximize();
456 void ShellWindow::Minimize() {
457 GetBaseWindow()->Minimize();
460 void ShellWindow::Restore() {
461 if (fullscreen_types_ != FULLSCREEN_TYPE_NONE) {
462 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
463 SetNativeWindowFullscreen(fullscreen_types_);
464 } else {
465 GetBaseWindow()->Restore();
469 void ShellWindow::OSFullscreen() {
470 #if !defined(OS_MACOSX)
471 // Do not enter fullscreen mode if disallowed by pref.
472 if (!profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed))
473 return;
474 #endif
475 fullscreen_types_ |= FULLSCREEN_TYPE_OS;
476 SetNativeWindowFullscreen(fullscreen_types_);
479 void ShellWindow::ForcedFullscreen() {
480 fullscreen_types_ |= FULLSCREEN_TYPE_FORCED;
481 SetNativeWindowFullscreen(fullscreen_types_);
484 void ShellWindow::SetMinimumSize(const gfx::Size& min_size) {
485 size_constraints_.set_minimum_size(min_size);
486 OnSizeConstraintsChanged();
489 void ShellWindow::SetMaximumSize(const gfx::Size& max_size) {
490 size_constraints_.set_maximum_size(max_size);
491 OnSizeConstraintsChanged();
494 void ShellWindow::Show(ShowType show_type) {
495 if (CommandLine::ForCurrentProcess()->HasSwitch(
496 switches::kEnableAppsShowOnFirstPaint)) {
497 show_on_first_paint_ = true;
499 if (!first_paint_complete_) {
500 delayed_show_type_ = show_type;
501 return;
505 switch (show_type) {
506 case SHOW_ACTIVE:
507 GetBaseWindow()->Show();
508 break;
509 case SHOW_INACTIVE:
510 GetBaseWindow()->ShowInactive();
511 break;
515 void ShellWindow::Hide() {
516 // This is there to prevent race conditions with Hide() being called before
517 // there was a non-empty paint. It should have no effect in a non-racy
518 // scenario where the application is hiding then showing a window: the second
519 // show will not be delayed.
520 show_on_first_paint_ = false;
521 GetBaseWindow()->Hide();
524 void ShellWindow::SetAlwaysOnTop(bool always_on_top) {
525 if (cached_always_on_top_ == always_on_top)
526 return;
528 cached_always_on_top_ = always_on_top;
530 // As a security measure, do not allow fullscreen windows to be on top.
531 // The property will be applied when the window exits fullscreen.
532 bool fullscreen = (fullscreen_types_ != FULLSCREEN_TYPE_NONE);
533 if (!fullscreen)
534 native_app_window_->SetAlwaysOnTop(always_on_top);
536 OnNativeWindowChanged();
539 bool ShellWindow::IsAlwaysOnTop() const {
540 return cached_always_on_top_;
543 //------------------------------------------------------------------------------
544 // Private methods
546 void ShellWindow::DidDownloadFavicon(
547 int id,
548 int http_status_code,
549 const GURL& image_url,
550 const std::vector<SkBitmap>& bitmaps,
551 const std::vector<gfx::Size>& original_bitmap_sizes) {
552 if (image_url != app_icon_url_ || bitmaps.empty())
553 return;
555 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
556 // whose height >= the preferred size.
557 int largest_index = 0;
558 for (size_t i = 1; i < bitmaps.size(); ++i) {
559 if (bitmaps[i].height() < delegate_->PreferredIconSize())
560 break;
561 largest_index = i;
563 const SkBitmap& largest = bitmaps[largest_index];
564 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
567 void ShellWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
568 DCHECK_EQ(app_icon_image_.get(), image);
570 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
573 void ShellWindow::UpdateExtensionAppIcon() {
574 // Avoid using any previous app icons were are being downloaded.
575 image_loader_ptr_factory_.InvalidateWeakPtrs();
577 app_icon_image_.reset(new extensions::IconImage(
578 profile(),
579 extension(),
580 extensions::IconsInfo::GetIcons(extension()),
581 delegate_->PreferredIconSize(),
582 extensions::IconsInfo::GetDefaultAppIcon(),
583 this));
585 // Triggers actual image loading with 1x resources. The 2x resource will
586 // be handled by IconImage class when requested.
587 app_icon_image_->image_skia().GetRepresentation(1.0f);
590 void ShellWindow::OnSizeConstraintsChanged() {
591 native_app_window_->UpdateWindowMinMaxSize();
592 gfx::Rect bounds = GetClientBounds();
593 gfx::Size constrained_size = size_constraints_.ClampSize(bounds.size());
594 if (bounds.size() != constrained_size) {
595 bounds.set_size(constrained_size);
596 native_app_window_->SetBounds(bounds);
598 OnNativeWindowChanged();
601 void ShellWindow::SetNativeWindowFullscreen(int fullscreen_types) {
602 native_app_window_->SetFullscreen(fullscreen_types);
604 if (!cached_always_on_top_)
605 return;
607 bool is_on_top = native_app_window_->IsAlwaysOnTop();
608 bool fullscreen = (fullscreen_types != FULLSCREEN_TYPE_NONE);
609 if (fullscreen && is_on_top) {
610 // When entering fullscreen, ensure windows are not always-on-top.
611 native_app_window_->SetAlwaysOnTop(false);
612 } else if (!fullscreen && !is_on_top) {
613 // When exiting fullscreen, reinstate always-on-top.
614 native_app_window_->SetAlwaysOnTop(true);
618 void ShellWindow::CloseContents(WebContents* contents) {
619 native_app_window_->Close();
622 bool ShellWindow::ShouldSuppressDialogs() {
623 return true;
626 content::ColorChooser* ShellWindow::OpenColorChooser(
627 WebContents* web_contents,
628 SkColor initial_color,
629 const std::vector<content::ColorSuggestion>& suggestionss) {
630 return delegate_->ShowColorChooser(web_contents, initial_color);
633 void ShellWindow::RunFileChooser(WebContents* tab,
634 const content::FileChooserParams& params) {
635 if (window_type_is_panel()) {
636 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
637 // dialogs to be unhosted but still close with the owning web contents.
638 // crbug.com/172502.
639 LOG(WARNING) << "File dialog opened by panel.";
640 return;
643 delegate_->RunFileChooser(tab, params);
646 bool ShellWindow::IsPopupOrPanel(const WebContents* source) const {
647 return true;
650 void ShellWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
651 native_app_window_->SetBounds(pos);
654 void ShellWindow::NavigationStateChanged(
655 const content::WebContents* source, unsigned changed_flags) {
656 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
657 native_app_window_->UpdateWindowTitle();
658 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
659 native_app_window_->UpdateWindowIcon();
662 void ShellWindow::ToggleFullscreenModeForTab(content::WebContents* source,
663 bool enter_fullscreen) {
664 #if !defined(OS_MACOSX)
665 // Do not enter fullscreen mode if disallowed by pref.
666 // TODO(bartfab): Add a test once it becomes possible to simulate a user
667 // gesture. http://crbug.com/174178
668 if (enter_fullscreen &&
669 !profile()->GetPrefs()->GetBoolean(prefs::kAppFullscreenAllowed)) {
670 return;
672 #endif
674 if (!IsExtensionWithPermissionOrSuggestInConsole(
675 APIPermission::kFullscreen,
676 extension_,
677 source->GetRenderViewHost())) {
678 return;
681 if (enter_fullscreen)
682 fullscreen_types_ |= FULLSCREEN_TYPE_HTML_API;
683 else
684 fullscreen_types_ &= ~FULLSCREEN_TYPE_HTML_API;
685 SetNativeWindowFullscreen(fullscreen_types_);
688 bool ShellWindow::IsFullscreenForTabOrPending(
689 const content::WebContents* source) const {
690 return ((fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0);
693 void ShellWindow::Observe(int type,
694 const content::NotificationSource& source,
695 const content::NotificationDetails& details) {
696 switch (type) {
697 case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
698 const extensions::Extension* unloaded_extension =
699 content::Details<extensions::UnloadedExtensionInfo>(
700 details)->extension;
701 if (extension_ == unloaded_extension)
702 native_app_window_->Close();
703 break;
705 case chrome::NOTIFICATION_APP_TERMINATING:
706 native_app_window_->Close();
707 break;
708 default:
709 NOTREACHED() << "Received unexpected notification";
713 void ShellWindow::SetWebContentsBlocked(content::WebContents* web_contents,
714 bool blocked) {
715 delegate_->SetWebContentsBlocked(web_contents, blocked);
718 bool ShellWindow::IsWebContentsVisible(content::WebContents* web_contents) {
719 return delegate_->IsWebContentsVisible(web_contents);
722 extensions::ActiveTabPermissionGranter*
723 ShellWindow::GetActiveTabPermissionGranter() {
724 // Shell windows don't support the activeTab permission.
725 return NULL;
728 WebContentsModalDialogHost* ShellWindow::GetWebContentsModalDialogHost() {
729 return native_app_window_.get();
732 void ShellWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
733 const std::string& message) {
734 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
735 rvh->Send(new ExtensionMsg_AddMessageToConsole(
736 rvh->GetRoutingID(), level, message));
739 void ShellWindow::SaveWindowPosition() {
740 if (window_key_.empty())
741 return;
742 if (!native_app_window_)
743 return;
745 ShellWindowGeometryCache* cache = ShellWindowGeometryCache::Get(profile());
747 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
748 bounds.Inset(native_app_window_->GetFrameInsets());
749 gfx::Rect screen_bounds =
750 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
751 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
752 cache->SaveGeometry(extension()->id(),
753 window_key_,
754 bounds,
755 screen_bounds,
756 window_state);
759 void ShellWindow::AdjustBoundsToBeVisibleOnScreen(
760 const gfx::Rect& cached_bounds,
761 const gfx::Rect& cached_screen_bounds,
762 const gfx::Rect& current_screen_bounds,
763 const gfx::Size& minimum_size,
764 gfx::Rect* bounds) const {
765 *bounds = cached_bounds;
767 // Reposition and resize the bounds if the cached_screen_bounds is different
768 // from the current screen bounds and the current screen bounds doesn't
769 // completely contain the bounds.
770 if (cached_screen_bounds != current_screen_bounds &&
771 !current_screen_bounds.Contains(cached_bounds)) {
772 bounds->set_width(
773 std::max(minimum_size.width(),
774 std::min(bounds->width(), current_screen_bounds.width())));
775 bounds->set_height(
776 std::max(minimum_size.height(),
777 std::min(bounds->height(), current_screen_bounds.height())));
778 bounds->set_x(
779 std::max(current_screen_bounds.x(),
780 std::min(bounds->x(),
781 current_screen_bounds.right() - bounds->width())));
782 bounds->set_y(
783 std::max(current_screen_bounds.y(),
784 std::min(bounds->y(),
785 current_screen_bounds.bottom() - bounds->height())));
789 ShellWindow::CreateParams ShellWindow::LoadDefaultsAndConstrain(
790 CreateParams params) const {
791 if (params.bounds.width() == 0)
792 params.bounds.set_width(kDefaultWidth);
793 if (params.bounds.height() == 0)
794 params.bounds.set_height(kDefaultHeight);
796 // If left and top are left undefined, the native shell window will center
797 // the window on the main screen in a platform-defined manner.
799 // Load cached state if it exists.
800 if (!params.window_key.empty()) {
801 ShellWindowGeometryCache* cache = ShellWindowGeometryCache::Get(profile());
803 gfx::Rect cached_bounds;
804 gfx::Rect cached_screen_bounds;
805 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
806 if (cache->GetGeometry(extension()->id(), params.window_key,
807 &cached_bounds, &cached_screen_bounds,
808 &cached_state)) {
809 // App window has cached screen bounds, make sure it fits on screen in
810 // case the screen resolution changed.
811 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
812 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
813 gfx::Rect current_screen_bounds = display.work_area();
814 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
815 cached_screen_bounds,
816 current_screen_bounds,
817 params.minimum_size,
818 &params.bounds);
819 params.state = cached_state;
823 SizeConstraints size_constraints(params.minimum_size, params.maximum_size);
824 params.bounds.set_size(size_constraints.ClampSize(params.bounds.size()));
825 params.minimum_size = size_constraints.GetMinimumSize();
826 params.maximum_size = size_constraints.GetMaximumSize();
828 return params;
831 // static
832 SkRegion* ShellWindow::RawDraggableRegionsToSkRegion(
833 const std::vector<extensions::DraggableRegion>& regions) {
834 SkRegion* sk_region = new SkRegion;
835 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
836 regions.begin();
837 iter != regions.end(); ++iter) {
838 const extensions::DraggableRegion& region = *iter;
839 sk_region->op(
840 region.bounds.x(),
841 region.bounds.y(),
842 region.bounds.right(),
843 region.bounds.bottom(),
844 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
846 return sk_region;
849 } // namespace apps