[Mac] Make app window backgrounds white.
[chromium-blink-merge.git] / apps / app_window.cc
blob814d2e0ae82f470d9016b39b416201cc9098eb9a
1 // Copyright 2014 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/app_window.h"
7 #include <algorithm>
9 #include "apps/app_window_geometry_cache.h"
10 #include "apps/app_window_registry.h"
11 #include "apps/apps_client.h"
12 #include "apps/size_constraints.h"
13 #include "apps/ui/native_app_window.h"
14 #include "apps/ui/web_contents_sizer.h"
15 #include "base/command_line.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/values.h"
19 #include "chrome/browser/chrome_notification_types.h"
20 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
21 #include "chrome/browser/extensions/suggest_permission_util.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "components/web_modal/web_contents_modal_dialog_manager.h"
24 #include "content/public/browser/browser_context.h"
25 #include "content/public/browser/invalidate_type.h"
26 #include "content/public/browser/navigation_entry.h"
27 #include "content/public/browser/notification_details.h"
28 #include "content/public/browser/notification_service.h"
29 #include "content/public/browser/notification_source.h"
30 #include "content/public/browser/notification_types.h"
31 #include "content/public/browser/render_view_host.h"
32 #include "content/public/browser/resource_dispatcher_host.h"
33 #include "content/public/browser/web_contents.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/media_stream_request.h"
36 #include "extensions/browser/extension_registry.h"
37 #include "extensions/browser/extension_system.h"
38 #include "extensions/browser/extensions_browser_client.h"
39 #include "extensions/browser/process_manager.h"
40 #include "extensions/browser/view_type_utils.h"
41 #include "extensions/common/extension.h"
42 #include "extensions/common/extension_messages.h"
43 #include "extensions/common/manifest_handlers/icons_handler.h"
44 #include "extensions/common/permissions/permissions_data.h"
45 #include "grit/theme_resources.h"
46 #include "third_party/skia/include/core/SkRegion.h"
47 #include "ui/base/resource/resource_bundle.h"
48 #include "ui/gfx/screen.h"
50 #if !defined(OS_MACOSX)
51 #include "apps/pref_names.h"
52 #include "base/prefs/pref_service.h"
53 #endif
55 using content::BrowserContext;
56 using content::ConsoleMessageLevel;
57 using content::WebContents;
58 using extensions::APIPermission;
59 using web_modal::WebContentsModalDialogHost;
60 using web_modal::WebContentsModalDialogManager;
62 namespace apps {
64 namespace {
66 const int kDefaultWidth = 512;
67 const int kDefaultHeight = 384;
69 bool IsFullscreen(int fullscreen_types) {
70 return fullscreen_types != apps::AppWindow::FULLSCREEN_TYPE_NONE;
73 void SetConstraintProperty(const std::string& name,
74 int value,
75 base::DictionaryValue* bounds_properties) {
76 if (value != SizeConstraints::kUnboundedSize)
77 bounds_properties->SetInteger(name, value);
78 else
79 bounds_properties->Set(name, base::Value::CreateNullValue());
82 void SetBoundsProperties(const gfx::Rect& bounds,
83 const gfx::Size& min_size,
84 const gfx::Size& max_size,
85 const std::string& bounds_name,
86 base::DictionaryValue* window_properties) {
87 scoped_ptr<base::DictionaryValue> bounds_properties(
88 new base::DictionaryValue());
90 bounds_properties->SetInteger("left", bounds.x());
91 bounds_properties->SetInteger("top", bounds.y());
92 bounds_properties->SetInteger("width", bounds.width());
93 bounds_properties->SetInteger("height", bounds.height());
95 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
96 SetConstraintProperty(
97 "minHeight", min_size.height(), bounds_properties.get());
98 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
99 SetConstraintProperty(
100 "maxHeight", max_size.height(), bounds_properties.get());
102 window_properties->Set(bounds_name, bounds_properties.release());
105 // Combines the constraints of the content and window, and returns constraints
106 // for the window.
107 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
108 const gfx::Size& content_constraints,
109 const gfx::Insets& frame_insets) {
110 gfx::Size combined_constraints(window_constraints);
111 if (content_constraints.width() > 0) {
112 combined_constraints.set_width(
113 content_constraints.width() + frame_insets.width());
115 if (content_constraints.height() > 0) {
116 combined_constraints.set_height(
117 content_constraints.height() + frame_insets.height());
119 return combined_constraints;
122 // Combines the constraints of the content and window, and returns constraints
123 // for the content.
124 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
125 const gfx::Size& content_constraints,
126 const gfx::Insets& frame_insets) {
127 gfx::Size combined_constraints(content_constraints);
128 if (window_constraints.width() > 0) {
129 combined_constraints.set_width(
130 std::max(0, window_constraints.width() - frame_insets.width()));
132 if (window_constraints.height() > 0) {
133 combined_constraints.set_height(
134 std::max(0, window_constraints.height() - frame_insets.height()));
136 return combined_constraints;
139 } // namespace
141 // AppWindow::BoundsSpecification
143 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
145 AppWindow::BoundsSpecification::BoundsSpecification()
146 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
148 AppWindow::BoundsSpecification::~BoundsSpecification() {}
150 void AppWindow::BoundsSpecification::ResetBounds() {
151 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
154 // AppWindow::CreateParams
156 AppWindow::CreateParams::CreateParams()
157 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
158 frame(AppWindow::FRAME_CHROME),
159 has_frame_color(false),
160 active_frame_color(SK_ColorBLACK),
161 inactive_frame_color(SK_ColorBLACK),
162 transparent_background(false),
163 creator_process_id(0),
164 state(ui::SHOW_STATE_DEFAULT),
165 hidden(false),
166 resizable(true),
167 focused(true),
168 always_on_top(false) {}
170 AppWindow::CreateParams::~CreateParams() {}
172 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
173 const gfx::Insets& frame_insets) const {
174 // Combine into a single window bounds.
175 gfx::Rect combined_bounds(window_spec.bounds);
176 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
177 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
178 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
179 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
180 if (content_spec.bounds.width() > 0) {
181 combined_bounds.set_width(
182 content_spec.bounds.width() + frame_insets.width());
184 if (content_spec.bounds.height() > 0) {
185 combined_bounds.set_height(
186 content_spec.bounds.height() + frame_insets.height());
189 // Constrain the bounds.
190 SizeConstraints constraints(
191 GetCombinedWindowConstraints(
192 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
193 GetCombinedWindowConstraints(
194 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
195 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
197 return combined_bounds;
200 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
201 const gfx::Insets& frame_insets) const {
202 return GetCombinedContentConstraints(window_spec.minimum_size,
203 content_spec.minimum_size,
204 frame_insets);
207 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
208 const gfx::Insets& frame_insets) const {
209 return GetCombinedContentConstraints(window_spec.maximum_size,
210 content_spec.maximum_size,
211 frame_insets);
214 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
215 const gfx::Insets& frame_insets) const {
216 return GetCombinedWindowConstraints(window_spec.minimum_size,
217 content_spec.minimum_size,
218 frame_insets);
221 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
222 const gfx::Insets& frame_insets) const {
223 return GetCombinedWindowConstraints(window_spec.maximum_size,
224 content_spec.maximum_size,
225 frame_insets);
228 // AppWindow::Delegate
230 AppWindow::Delegate::~Delegate() {}
232 // AppWindow
234 AppWindow::AppWindow(BrowserContext* context,
235 Delegate* delegate,
236 const extensions::Extension* extension)
237 : browser_context_(context),
238 extension_id_(extension->id()),
239 window_type_(WINDOW_TYPE_DEFAULT),
240 delegate_(delegate),
241 image_loader_ptr_factory_(this),
242 fullscreen_types_(FULLSCREEN_TYPE_NONE),
243 show_on_first_paint_(false),
244 first_paint_complete_(false),
245 has_been_shown_(false),
246 can_send_events_(false),
247 is_hidden_(false),
248 cached_always_on_top_(false) {
249 extensions::ExtensionsBrowserClient* client =
250 extensions::ExtensionsBrowserClient::Get();
251 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
252 << "Only off the record window may be opened in the guest mode.";
255 void AppWindow::Init(const GURL& url,
256 AppWindowContents* app_window_contents,
257 const CreateParams& params) {
258 // Initialize the render interface and web contents
259 app_window_contents_.reset(app_window_contents);
260 app_window_contents_->Initialize(browser_context(), url);
261 WebContents* web_contents = app_window_contents_->GetWebContents();
262 if (CommandLine::ForCurrentProcess()->HasSwitch(
263 switches::kEnableAppsShowOnFirstPaint)) {
264 content::WebContentsObserver::Observe(web_contents);
266 delegate_->InitWebContents(web_contents);
267 WebContentsModalDialogManager::CreateForWebContents(web_contents);
268 // TODO(jamescook): Delegate out this creation.
269 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
270 web_contents);
272 web_contents->SetDelegate(this);
273 WebContentsModalDialogManager::FromWebContents(web_contents)
274 ->SetDelegate(this);
275 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_WINDOW);
277 // Initialize the window
278 CreateParams new_params = LoadDefaults(params);
279 window_type_ = new_params.window_type;
280 window_key_ = new_params.window_key;
282 // Windows cannot be always-on-top in fullscreen mode for security reasons.
283 cached_always_on_top_ = new_params.always_on_top;
284 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
285 new_params.always_on_top = false;
287 native_app_window_.reset(delegate_->CreateNativeAppWindow(this, new_params));
289 // Prevent the browser process from shutting down while this window exists.
290 AppsClient::Get()->IncrementKeepAliveCount();
291 UpdateExtensionAppIcon();
292 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
294 if (new_params.hidden) {
295 // Although the window starts hidden by default, calling Hide() here
296 // notifies observers of the window being hidden.
297 Hide();
298 } else {
299 // Panels are not activated by default.
300 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
301 : SHOW_ACTIVE);
304 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
305 Fullscreen();
306 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
307 Maximize();
308 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
309 Minimize();
311 OnNativeWindowChanged();
313 // When the render view host is changed, the native window needs to know
314 // about it in case it has any setup to do to make the renderer appear
315 // properly. In particular, on Windows, the view's clickthrough region needs
316 // to be set.
317 extensions::ExtensionsBrowserClient* client =
318 extensions::ExtensionsBrowserClient::Get();
319 registrar_.Add(this,
320 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
321 content::Source<content::BrowserContext>(
322 client->GetOriginalContext(browser_context_)));
323 // Close when the browser process is exiting.
324 registrar_.Add(this,
325 chrome::NOTIFICATION_APP_TERMINATING,
326 content::NotificationService::AllSources());
327 // Update the app menu if an ephemeral app becomes installed.
328 registrar_.Add(this,
329 chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED,
330 content::Source<content::BrowserContext>(
331 client->GetOriginalContext(browser_context_)));
333 app_window_contents_->LoadContents(new_params.creator_process_id);
335 if (CommandLine::ForCurrentProcess()->HasSwitch(
336 switches::kEnableAppsShowOnFirstPaint)) {
337 // We want to show the window only when the content has been painted. For
338 // that to happen, we need to define a size for the content, otherwise the
339 // layout will happen in a 0x0 area.
340 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
341 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
342 initial_bounds.Inset(frame_insets);
343 apps::ResizeWebContents(web_contents, initial_bounds.size());
347 AppWindow::~AppWindow() {
348 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
349 // last window open.
350 registrar_.RemoveAll();
352 // Remove shutdown prevention.
353 AppsClient::Get()->DecrementKeepAliveCount();
356 void AppWindow::RequestMediaAccessPermission(
357 content::WebContents* web_contents,
358 const content::MediaStreamRequest& request,
359 const content::MediaResponseCallback& callback) {
360 const extensions::Extension* extension = GetExtension();
361 if (!extension)
362 return;
364 delegate_->RequestMediaAccessPermission(
365 web_contents, request, callback, extension);
368 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
369 const content::OpenURLParams& params) {
370 // Don't allow the current tab to be navigated. It would be nice to map all
371 // anchor tags (even those without target="_blank") to new tabs, but right
372 // now we can't distinguish between those and <meta> refreshes or window.href
373 // navigations, which we don't want to allow.
374 // TOOD(mihaip): Can we check for user gestures instead?
375 WindowOpenDisposition disposition = params.disposition;
376 if (disposition == CURRENT_TAB) {
377 AddMessageToDevToolsConsole(
378 content::CONSOLE_MESSAGE_LEVEL_ERROR,
379 base::StringPrintf(
380 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
381 params.url.spec().c_str()));
382 return NULL;
385 // These dispositions aren't really navigations.
386 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
387 disposition == IGNORE_ACTION) {
388 return NULL;
391 WebContents* contents =
392 delegate_->OpenURLFromTab(browser_context_, source, params);
393 if (!contents) {
394 AddMessageToDevToolsConsole(
395 content::CONSOLE_MESSAGE_LEVEL_ERROR,
396 base::StringPrintf(
397 "Can't navigate to \"%s\"; apps do not support navigation.",
398 params.url.spec().c_str()));
401 return contents;
404 void AppWindow::AddNewContents(WebContents* source,
405 WebContents* new_contents,
406 WindowOpenDisposition disposition,
407 const gfx::Rect& initial_pos,
408 bool user_gesture,
409 bool* was_blocked) {
410 DCHECK(new_contents->GetBrowserContext() == browser_context_);
411 delegate_->AddNewContents(browser_context_,
412 new_contents,
413 disposition,
414 initial_pos,
415 user_gesture,
416 was_blocked);
419 bool AppWindow::PreHandleKeyboardEvent(
420 content::WebContents* source,
421 const content::NativeWebKeyboardEvent& event,
422 bool* is_keyboard_shortcut) {
423 const extensions::Extension* extension = GetExtension();
424 if (!extension)
425 return false;
427 // Here, we can handle a key event before the content gets it. When we are
428 // fullscreen and it is not forced, we want to allow the user to leave
429 // when ESC is pressed.
430 // However, if the application has the "overrideEscFullscreen" permission, we
431 // should let it override that behavior.
432 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
433 // action is not prevented.
434 // Thus, we should handle the KeyEvent here only if the permission is not set.
435 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
436 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
437 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0) &&
438 !extension->permissions_data()->HasAPIPermission(
439 APIPermission::kOverrideEscFullscreen)) {
440 Restore();
441 return true;
444 return false;
447 void AppWindow::HandleKeyboardEvent(
448 WebContents* source,
449 const content::NativeWebKeyboardEvent& event) {
450 // If the window is currently fullscreen and not forced, ESC should leave
451 // fullscreen. If this code is being called for ESC, that means that the
452 // KeyEvent's default behavior was not prevented by the content.
453 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
454 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
455 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0)) {
456 Restore();
457 return;
460 native_app_window_->HandleKeyboardEvent(event);
463 void AppWindow::RequestToLockMouse(WebContents* web_contents,
464 bool user_gesture,
465 bool last_unlocked_by_target) {
466 const extensions::Extension* extension = GetExtension();
467 if (!extension)
468 return;
470 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
471 APIPermission::kPointerLock,
472 extension,
473 web_contents->GetRenderViewHost());
475 web_contents->GotResponseToLockMouseRequest(has_permission);
478 bool AppWindow::PreHandleGestureEvent(WebContents* source,
479 const blink::WebGestureEvent& event) {
480 // Disable pinch zooming in app windows.
481 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
482 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
483 event.type == blink::WebGestureEvent::GesturePinchEnd;
486 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
487 first_paint_complete_ = true;
488 if (show_on_first_paint_) {
489 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
490 delayed_show_type_ == SHOW_INACTIVE);
491 Show(delayed_show_type_);
495 void AppWindow::OnNativeClose() {
496 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
497 if (app_window_contents_) {
498 WebContents* web_contents = app_window_contents_->GetWebContents();
499 WebContentsModalDialogManager::FromWebContents(web_contents)
500 ->SetDelegate(NULL);
501 app_window_contents_->NativeWindowClosed();
503 delete this;
506 void AppWindow::OnNativeWindowChanged() {
507 SaveWindowPosition();
509 #if defined(OS_WIN)
510 if (native_app_window_ && cached_always_on_top_ &&
511 !IsFullscreen(fullscreen_types_) && !native_app_window_->IsMaximized() &&
512 !native_app_window_->IsMinimized()) {
513 UpdateNativeAlwaysOnTop();
515 #endif
517 if (app_window_contents_ && native_app_window_)
518 app_window_contents_->NativeWindowChanged(native_app_window_.get());
521 void AppWindow::OnNativeWindowActivated() {
522 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
525 content::WebContents* AppWindow::web_contents() const {
526 return app_window_contents_->GetWebContents();
529 const extensions::Extension* AppWindow::GetExtension() const {
530 return extensions::ExtensionRegistry::Get(browser_context_)
531 ->enabled_extensions()
532 .GetByID(extension_id_);
535 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
537 gfx::NativeWindow AppWindow::GetNativeWindow() {
538 return GetBaseWindow()->GetNativeWindow();
541 gfx::Rect AppWindow::GetClientBounds() const {
542 gfx::Rect bounds = native_app_window_->GetBounds();
543 bounds.Inset(native_app_window_->GetFrameInsets());
544 return bounds;
547 base::string16 AppWindow::GetTitle() const {
548 const extensions::Extension* extension = GetExtension();
549 if (!extension)
550 return base::string16();
552 // WebContents::GetTitle() will return the page's URL if there's no <title>
553 // specified. However, we'd prefer to show the name of the extension in that
554 // case, so we directly inspect the NavigationEntry's title.
555 base::string16 title;
556 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
557 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
558 title = base::UTF8ToUTF16(extension->name());
559 } else {
560 title = web_contents()->GetTitle();
562 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
563 return title;
566 void AppWindow::SetAppIconUrl(const GURL& url) {
567 // If the same url is being used for the badge, ignore it.
568 if (url == badge_icon_url_)
569 return;
571 // Avoid using any previous icons that were being downloaded.
572 image_loader_ptr_factory_.InvalidateWeakPtrs();
574 // Reset |app_icon_image_| to abort pending image load (if any).
575 app_icon_image_.reset();
577 app_icon_url_ = url;
578 web_contents()->DownloadImage(
579 url,
580 true, // is a favicon
581 0, // no maximum size
582 base::Bind(&AppWindow::DidDownloadFavicon,
583 image_loader_ptr_factory_.GetWeakPtr()));
586 void AppWindow::SetBadgeIconUrl(const GURL& url) {
587 // Avoid using any previous icons that were being downloaded.
588 image_loader_ptr_factory_.InvalidateWeakPtrs();
590 // Reset |app_icon_image_| to abort pending image load (if any).
591 badge_icon_image_.reset();
593 badge_icon_url_ = url;
594 web_contents()->DownloadImage(
595 url,
596 true, // is a favicon
597 0, // no maximum size
598 base::Bind(&AppWindow::DidDownloadFavicon,
599 image_loader_ptr_factory_.GetWeakPtr()));
602 void AppWindow::ClearBadge() {
603 badge_icon_image_.reset();
604 badge_icon_url_ = GURL();
605 UpdateBadgeIcon(gfx::Image());
608 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
609 native_app_window_->UpdateShape(region.Pass());
612 void AppWindow::UpdateDraggableRegions(
613 const std::vector<extensions::DraggableRegion>& regions) {
614 native_app_window_->UpdateDraggableRegions(regions);
617 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
618 if (image.IsEmpty())
619 return;
620 app_icon_ = image;
621 native_app_window_->UpdateWindowIcon();
622 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
625 void AppWindow::Fullscreen() {
626 #if !defined(OS_MACOSX)
627 // Do not enter fullscreen mode if disallowed by pref.
628 PrefService* prefs =
629 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
630 browser_context());
631 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
632 return;
633 #endif
634 fullscreen_types_ |= FULLSCREEN_TYPE_WINDOW_API;
635 SetNativeWindowFullscreen();
638 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
640 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
642 void AppWindow::Restore() {
643 if (IsFullscreen(fullscreen_types_)) {
644 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
645 SetNativeWindowFullscreen();
646 } else {
647 GetBaseWindow()->Restore();
651 void AppWindow::OSFullscreen() {
652 #if !defined(OS_MACOSX)
653 // Do not enter fullscreen mode if disallowed by pref.
654 PrefService* prefs =
655 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
656 browser_context());
657 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
658 return;
659 #endif
660 fullscreen_types_ |= FULLSCREEN_TYPE_OS;
661 SetNativeWindowFullscreen();
664 void AppWindow::ForcedFullscreen() {
665 fullscreen_types_ |= FULLSCREEN_TYPE_FORCED;
666 SetNativeWindowFullscreen();
669 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
670 const gfx::Size& max_size) {
671 SizeConstraints constraints(min_size, max_size);
672 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
673 constraints.GetMaximumSize());
675 gfx::Rect bounds = GetClientBounds();
676 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
677 if (bounds.size() != constrained_size) {
678 bounds.set_size(constrained_size);
679 bounds.Inset(-native_app_window_->GetFrameInsets());
680 native_app_window_->SetBounds(bounds);
682 OnNativeWindowChanged();
685 void AppWindow::Show(ShowType show_type) {
686 is_hidden_ = false;
688 if (CommandLine::ForCurrentProcess()->HasSwitch(
689 switches::kEnableAppsShowOnFirstPaint)) {
690 show_on_first_paint_ = true;
692 if (!first_paint_complete_) {
693 delayed_show_type_ = show_type;
694 return;
698 switch (show_type) {
699 case SHOW_ACTIVE:
700 GetBaseWindow()->Show();
701 break;
702 case SHOW_INACTIVE:
703 GetBaseWindow()->ShowInactive();
704 break;
706 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this);
708 has_been_shown_ = true;
709 SendOnWindowShownIfShown();
712 void AppWindow::Hide() {
713 // This is there to prevent race conditions with Hide() being called before
714 // there was a non-empty paint. It should have no effect in a non-racy
715 // scenario where the application is hiding then showing a window: the second
716 // show will not be delayed.
717 is_hidden_ = true;
718 show_on_first_paint_ = false;
719 GetBaseWindow()->Hide();
720 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
723 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
724 if (cached_always_on_top_ == always_on_top)
725 return;
727 cached_always_on_top_ = always_on_top;
729 // As a security measure, do not allow fullscreen windows or windows that
730 // overlap the taskbar to be on top. The property will be applied when the
731 // window exits fullscreen and moves away from the taskbar.
732 if (!IsFullscreen(fullscreen_types_) && !IntersectsWithTaskbar())
733 native_app_window_->SetAlwaysOnTop(always_on_top);
735 OnNativeWindowChanged();
738 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
740 void AppWindow::WindowEventsReady() {
741 can_send_events_ = true;
742 SendOnWindowShownIfShown();
745 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
746 DCHECK(properties);
748 properties->SetBoolean("fullscreen",
749 native_app_window_->IsFullscreenOrPending());
750 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
751 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
752 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
753 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
755 // These properties are undocumented and are to enable testing. Alpha is
756 // removed to
757 // make the values easier to check.
758 SkColor transparent_white = ~SK_ColorBLACK;
759 properties->SetInteger(
760 "activeFrameColor",
761 native_app_window_->ActiveFrameColor() & transparent_white);
762 properties->SetInteger(
763 "inactiveFrameColor",
764 native_app_window_->InactiveFrameColor() & transparent_white);
766 gfx::Rect content_bounds = GetClientBounds();
767 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
768 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
769 SetBoundsProperties(content_bounds,
770 content_min_size,
771 content_max_size,
772 "innerBounds",
773 properties);
775 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
776 gfx::Rect frame_bounds = native_app_window_->GetBounds();
777 gfx::Size frame_min_size =
778 SizeConstraints::AddFrameToConstraints(content_min_size, frame_insets);
779 gfx::Size frame_max_size =
780 SizeConstraints::AddFrameToConstraints(content_max_size, frame_insets);
781 SetBoundsProperties(frame_bounds,
782 frame_min_size,
783 frame_max_size,
784 "outerBounds",
785 properties);
788 //------------------------------------------------------------------------------
789 // Private methods
791 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
792 badge_icon_ = image;
793 native_app_window_->UpdateBadgeIcon();
796 void AppWindow::DidDownloadFavicon(
797 int id,
798 int http_status_code,
799 const GURL& image_url,
800 const std::vector<SkBitmap>& bitmaps,
801 const std::vector<gfx::Size>& original_bitmap_sizes) {
802 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
803 bitmaps.empty()) {
804 return;
807 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
808 // whose height >= the preferred size.
809 int largest_index = 0;
810 for (size_t i = 1; i < bitmaps.size(); ++i) {
811 if (bitmaps[i].height() < delegate_->PreferredIconSize())
812 break;
813 largest_index = i;
815 const SkBitmap& largest = bitmaps[largest_index];
816 if (image_url == app_icon_url_) {
817 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
818 return;
821 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
824 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
825 DCHECK_EQ(app_icon_image_.get(), image);
827 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
830 void AppWindow::UpdateExtensionAppIcon() {
831 // Avoid using any previous app icons were being downloaded.
832 image_loader_ptr_factory_.InvalidateWeakPtrs();
834 const gfx::ImageSkia& default_icon =
835 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
836 IDR_APP_DEFAULT_ICON);
838 const extensions::Extension* extension = GetExtension();
839 if (!extension)
840 return;
842 app_icon_image_.reset(
843 new extensions::IconImage(browser_context(),
844 extension,
845 extensions::IconsInfo::GetIcons(extension),
846 delegate_->PreferredIconSize(),
847 default_icon,
848 this));
850 // Triggers actual image loading with 1x resources. The 2x resource will
851 // be handled by IconImage class when requested.
852 app_icon_image_->image_skia().GetRepresentation(1.0f);
855 void AppWindow::SetNativeWindowFullscreen() {
856 native_app_window_->SetFullscreen(fullscreen_types_);
858 if (cached_always_on_top_)
859 UpdateNativeAlwaysOnTop();
862 bool AppWindow::IntersectsWithTaskbar() const {
863 #if defined(OS_WIN)
864 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
865 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
866 std::vector<gfx::Display> displays = screen->GetAllDisplays();
868 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
869 it != displays.end();
870 ++it) {
871 gfx::Rect taskbar_bounds = it->bounds();
872 taskbar_bounds.Subtract(it->work_area());
873 if (taskbar_bounds.IsEmpty())
874 continue;
876 if (window_bounds.Intersects(taskbar_bounds))
877 return true;
879 #endif
881 return false;
884 void AppWindow::UpdateNativeAlwaysOnTop() {
885 DCHECK(cached_always_on_top_);
886 bool is_on_top = native_app_window_->IsAlwaysOnTop();
887 bool fullscreen = IsFullscreen(fullscreen_types_);
888 bool intersects_taskbar = IntersectsWithTaskbar();
890 if (is_on_top && (fullscreen || intersects_taskbar)) {
891 // When entering fullscreen or overlapping the taskbar, ensure windows are
892 // not always-on-top.
893 native_app_window_->SetAlwaysOnTop(false);
894 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
895 // When exiting fullscreen and moving away from the taskbar, reinstate
896 // always-on-top.
897 native_app_window_->SetAlwaysOnTop(true);
901 void AppWindow::SendOnWindowShownIfShown() {
902 if (!can_send_events_ || !has_been_shown_)
903 return;
905 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType)) {
906 app_window_contents_->DispatchWindowShownForTests();
910 void AppWindow::CloseContents(WebContents* contents) {
911 native_app_window_->Close();
914 bool AppWindow::ShouldSuppressDialogs() { return true; }
916 content::ColorChooser* AppWindow::OpenColorChooser(
917 WebContents* web_contents,
918 SkColor initial_color,
919 const std::vector<content::ColorSuggestion>& suggestionss) {
920 return delegate_->ShowColorChooser(web_contents, initial_color);
923 void AppWindow::RunFileChooser(WebContents* tab,
924 const content::FileChooserParams& params) {
925 if (window_type_is_panel()) {
926 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
927 // dialogs to be unhosted but still close with the owning web contents.
928 // crbug.com/172502.
929 LOG(WARNING) << "File dialog opened by panel.";
930 return;
933 delegate_->RunFileChooser(tab, params);
936 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
938 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
939 native_app_window_->SetBounds(pos);
942 void AppWindow::NavigationStateChanged(const content::WebContents* source,
943 unsigned changed_flags) {
944 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
945 native_app_window_->UpdateWindowTitle();
946 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
947 native_app_window_->UpdateWindowIcon();
950 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
951 bool enter_fullscreen) {
952 #if !defined(OS_MACOSX)
953 // Do not enter fullscreen mode if disallowed by pref.
954 // TODO(bartfab): Add a test once it becomes possible to simulate a user
955 // gesture. http://crbug.com/174178
956 PrefService* prefs =
957 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
958 browser_context());
959 if (enter_fullscreen && !prefs->GetBoolean(prefs::kAppFullscreenAllowed)) {
960 return;
962 #endif
964 const extensions::Extension* extension = GetExtension();
965 if (!extension)
966 return;
968 if (!IsExtensionWithPermissionOrSuggestInConsole(
969 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
970 return;
973 if (enter_fullscreen)
974 fullscreen_types_ |= FULLSCREEN_TYPE_HTML_API;
975 else
976 fullscreen_types_ &= ~FULLSCREEN_TYPE_HTML_API;
977 SetNativeWindowFullscreen();
980 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
981 const {
982 return ((fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0);
985 void AppWindow::Observe(int type,
986 const content::NotificationSource& source,
987 const content::NotificationDetails& details) {
988 switch (type) {
989 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
990 const extensions::Extension* unloaded_extension =
991 content::Details<extensions::UnloadedExtensionInfo>(details)
992 ->extension;
993 if (extension_id_ == unloaded_extension->id())
994 native_app_window_->Close();
995 break;
997 case chrome::NOTIFICATION_EXTENSION_INSTALLED_DEPRECATED: {
998 const extensions::Extension* installed_extension =
999 content::Details<const extensions::InstalledExtensionInfo>(details)
1000 ->extension;
1001 DCHECK(installed_extension);
1002 if (installed_extension->id() == extension_id())
1003 native_app_window_->UpdateShelfMenu();
1004 break;
1006 case chrome::NOTIFICATION_APP_TERMINATING:
1007 native_app_window_->Close();
1008 break;
1009 default:
1010 NOTREACHED() << "Received unexpected notification";
1014 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
1015 bool blocked) {
1016 delegate_->SetWebContentsBlocked(web_contents, blocked);
1019 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
1020 return delegate_->IsWebContentsVisible(web_contents);
1023 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
1024 return native_app_window_.get();
1027 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
1028 const std::string& message) {
1029 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
1030 rvh->Send(new ExtensionMsg_AddMessageToConsole(
1031 rvh->GetRoutingID(), level, message));
1034 void AppWindow::SaveWindowPosition() {
1035 if (window_key_.empty())
1036 return;
1037 if (!native_app_window_)
1038 return;
1040 AppWindowGeometryCache* cache =
1041 AppWindowGeometryCache::Get(browser_context());
1043 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
1044 gfx::Rect screen_bounds =
1045 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
1046 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1047 cache->SaveGeometry(
1048 extension_id(), window_key_, bounds, screen_bounds, window_state);
1051 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1052 const gfx::Rect& cached_bounds,
1053 const gfx::Rect& cached_screen_bounds,
1054 const gfx::Rect& current_screen_bounds,
1055 const gfx::Size& minimum_size,
1056 gfx::Rect* bounds) const {
1057 *bounds = cached_bounds;
1059 // Reposition and resize the bounds if the cached_screen_bounds is different
1060 // from the current screen bounds and the current screen bounds doesn't
1061 // completely contain the bounds.
1062 if (cached_screen_bounds != current_screen_bounds &&
1063 !current_screen_bounds.Contains(cached_bounds)) {
1064 bounds->set_width(
1065 std::max(minimum_size.width(),
1066 std::min(bounds->width(), current_screen_bounds.width())));
1067 bounds->set_height(
1068 std::max(minimum_size.height(),
1069 std::min(bounds->height(), current_screen_bounds.height())));
1070 bounds->set_x(
1071 std::max(current_screen_bounds.x(),
1072 std::min(bounds->x(),
1073 current_screen_bounds.right() - bounds->width())));
1074 bounds->set_y(
1075 std::max(current_screen_bounds.y(),
1076 std::min(bounds->y(),
1077 current_screen_bounds.bottom() - bounds->height())));
1081 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1082 const {
1083 // Ensure width and height are specified.
1084 if (params.content_spec.bounds.width() == 0 &&
1085 params.window_spec.bounds.width() == 0) {
1086 params.content_spec.bounds.set_width(kDefaultWidth);
1088 if (params.content_spec.bounds.height() == 0 &&
1089 params.window_spec.bounds.height() == 0) {
1090 params.content_spec.bounds.set_height(kDefaultHeight);
1093 // If left and top are left undefined, the native app window will center
1094 // the window on the main screen in a platform-defined manner.
1096 // Load cached state if it exists.
1097 if (!params.window_key.empty()) {
1098 AppWindowGeometryCache* cache =
1099 AppWindowGeometryCache::Get(browser_context());
1101 gfx::Rect cached_bounds;
1102 gfx::Rect cached_screen_bounds;
1103 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1104 if (cache->GetGeometry(extension_id(),
1105 params.window_key,
1106 &cached_bounds,
1107 &cached_screen_bounds,
1108 &cached_state)) {
1109 // App window has cached screen bounds, make sure it fits on screen in
1110 // case the screen resolution changed.
1111 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1112 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1113 gfx::Rect current_screen_bounds = display.work_area();
1114 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1115 params.GetWindowMaximumSize(gfx::Insets()));
1116 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1117 cached_screen_bounds,
1118 current_screen_bounds,
1119 constraints.GetMinimumSize(),
1120 &params.window_spec.bounds);
1121 params.state = cached_state;
1123 // Since we are restoring a cached state, reset the content bounds spec to
1124 // ensure it is not used.
1125 params.content_spec.ResetBounds();
1129 return params;
1132 // static
1133 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1134 const std::vector<extensions::DraggableRegion>& regions) {
1135 SkRegion* sk_region = new SkRegion;
1136 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
1137 regions.begin();
1138 iter != regions.end();
1139 ++iter) {
1140 const extensions::DraggableRegion& region = *iter;
1141 sk_region->op(
1142 region.bounds.x(),
1143 region.bounds.y(),
1144 region.bounds.right(),
1145 region.bounds.bottom(),
1146 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1148 return sk_region;
1151 } // namespace apps