Revert 257022 "Implement wallpaper policy"
[chromium-blink-merge.git] / apps / app_window.cc
blobe96bda484b8e2c1f64f859b8a55ac4c38d390e9e
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 "base/command_line.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/values.h"
18 #include "chrome/browser/chrome_notification_types.h"
19 #include "chrome/browser/extensions/extension_web_contents_observer.h"
20 #include "chrome/browser/extensions/suggest_permission_util.h"
21 #include "chrome/common/chrome_switches.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/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/browser/web_contents_view.h"
35 #include "content/public/common/media_stream_request.h"
36 #include "extensions/browser/extension_system.h"
37 #include "extensions/browser/extensions_browser_client.h"
38 #include "extensions/browser/process_manager.h"
39 #include "extensions/browser/view_type_utils.h"
40 #include "extensions/common/extension.h"
41 #include "extensions/common/extension_messages.h"
42 #include "third_party/skia/include/core/SkRegion.h"
43 #include "ui/gfx/screen.h"
45 #if !defined(OS_MACOSX)
46 #include "apps/pref_names.h"
47 #include "base/prefs/pref_service.h"
48 #endif
50 using content::BrowserContext;
51 using content::ConsoleMessageLevel;
52 using content::WebContents;
53 using extensions::APIPermission;
54 using web_modal::WebContentsModalDialogHost;
55 using web_modal::WebContentsModalDialogManager;
57 namespace apps {
59 namespace {
61 const int kDefaultWidth = 512;
62 const int kDefaultHeight = 384;
64 bool IsFullscreen(int fullscreen_types) {
65 return fullscreen_types != apps::AppWindow::FULLSCREEN_TYPE_NONE;
68 void SetConstraintProperty(const std::string& name,
69 int value,
70 base::DictionaryValue* bounds_properties) {
71 if (value != SizeConstraints::kUnboundedSize)
72 bounds_properties->SetInteger(name, value);
73 else
74 bounds_properties->Set(name, base::Value::CreateNullValue());
77 void SetBoundsProperties(const gfx::Rect& bounds,
78 const gfx::Size& min_size,
79 const gfx::Size& max_size,
80 const std::string& bounds_name,
81 base::DictionaryValue* window_properties) {
82 scoped_ptr<base::DictionaryValue> bounds_properties(
83 new base::DictionaryValue());
85 bounds_properties->SetInteger("left", bounds.x());
86 bounds_properties->SetInteger("top", bounds.y());
87 bounds_properties->SetInteger("width", bounds.width());
88 bounds_properties->SetInteger("height", bounds.height());
90 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
91 SetConstraintProperty(
92 "minHeight", min_size.height(), bounds_properties.get());
93 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
94 SetConstraintProperty(
95 "maxHeight", max_size.height(), bounds_properties.get());
97 window_properties->Set(bounds_name, bounds_properties.release());
100 // Combines the constraints of the content and window, and returns constraints
101 // for the window.
102 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
103 const gfx::Size& content_constraints,
104 const gfx::Insets& frame_insets) {
105 gfx::Size combined_constraints(window_constraints);
106 if (content_constraints.width() > 0) {
107 combined_constraints.set_width(
108 content_constraints.width() + frame_insets.width());
110 if (content_constraints.height() > 0) {
111 combined_constraints.set_height(
112 content_constraints.height() + frame_insets.height());
114 return combined_constraints;
117 // Combines the constraints of the content and window, and returns constraints
118 // for the content.
119 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
120 const gfx::Size& content_constraints,
121 const gfx::Insets& frame_insets) {
122 gfx::Size combined_constraints(content_constraints);
123 if (window_constraints.width() > 0) {
124 combined_constraints.set_width(
125 std::max(0, window_constraints.width() - frame_insets.width()));
127 if (window_constraints.height() > 0) {
128 combined_constraints.set_height(
129 std::max(0, window_constraints.height() - frame_insets.height()));
131 return combined_constraints;
134 } // namespace
136 // AppWindow::BoundsSpecification
138 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
140 AppWindow::BoundsSpecification::BoundsSpecification()
141 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
143 AppWindow::BoundsSpecification::~BoundsSpecification() {}
145 void AppWindow::BoundsSpecification::ResetBounds() {
146 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
149 // AppWindow::CreateParams
151 AppWindow::CreateParams::CreateParams()
152 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
153 frame(AppWindow::FRAME_CHROME),
154 has_frame_color(false),
155 transparent_background(false),
156 creator_process_id(0),
157 state(ui::SHOW_STATE_DEFAULT),
158 hidden(false),
159 resizable(true),
160 focused(true),
161 always_on_top(false) {}
163 AppWindow::CreateParams::~CreateParams() {}
165 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
166 const gfx::Insets& frame_insets) const {
167 // Combine into a single window bounds.
168 gfx::Rect combined_bounds(window_spec.bounds);
169 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
170 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
171 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
172 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
173 if (content_spec.bounds.width() > 0) {
174 combined_bounds.set_width(
175 content_spec.bounds.width() + frame_insets.width());
177 if (content_spec.bounds.height() > 0) {
178 combined_bounds.set_height(
179 content_spec.bounds.height() + frame_insets.height());
182 // Constrain the bounds.
183 SizeConstraints constraints(
184 GetCombinedWindowConstraints(
185 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
186 GetCombinedWindowConstraints(
187 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
188 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
190 return combined_bounds;
193 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
194 const gfx::Insets& frame_insets) const {
195 return GetCombinedContentConstraints(window_spec.minimum_size,
196 content_spec.minimum_size,
197 frame_insets);
200 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
201 const gfx::Insets& frame_insets) const {
202 return GetCombinedContentConstraints(window_spec.maximum_size,
203 content_spec.maximum_size,
204 frame_insets);
207 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
208 const gfx::Insets& frame_insets) const {
209 return GetCombinedWindowConstraints(window_spec.minimum_size,
210 content_spec.minimum_size,
211 frame_insets);
214 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
215 const gfx::Insets& frame_insets) const {
216 return GetCombinedWindowConstraints(window_spec.maximum_size,
217 content_spec.maximum_size,
218 frame_insets);
221 // AppWindow::Delegate
223 AppWindow::Delegate::~Delegate() {}
225 // AppWindow
227 AppWindow::AppWindow(BrowserContext* context,
228 Delegate* delegate,
229 const extensions::Extension* extension)
230 : browser_context_(context),
231 extension_(extension),
232 extension_id_(extension->id()),
233 window_type_(WINDOW_TYPE_DEFAULT),
234 delegate_(delegate),
235 image_loader_ptr_factory_(this),
236 fullscreen_types_(FULLSCREEN_TYPE_NONE),
237 show_on_first_paint_(false),
238 first_paint_complete_(false),
239 cached_always_on_top_(false) {
240 extensions::ExtensionsBrowserClient* client =
241 extensions::ExtensionsBrowserClient::Get();
242 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
243 << "Only off the record window may be opened in the guest mode.";
246 void AppWindow::Init(const GURL& url,
247 AppWindowContents* app_window_contents,
248 const CreateParams& params) {
249 // Initialize the render interface and web contents
250 app_window_contents_.reset(app_window_contents);
251 app_window_contents_->Initialize(browser_context(), url);
252 WebContents* web_contents = app_window_contents_->GetWebContents();
253 if (CommandLine::ForCurrentProcess()->HasSwitch(
254 switches::kEnableAppsShowOnFirstPaint)) {
255 content::WebContentsObserver::Observe(web_contents);
257 delegate_->InitWebContents(web_contents);
258 WebContentsModalDialogManager::CreateForWebContents(web_contents);
259 extensions::ExtensionWebContentsObserver::CreateForWebContents(web_contents);
261 web_contents->SetDelegate(this);
262 WebContentsModalDialogManager::FromWebContents(web_contents)
263 ->SetDelegate(this);
264 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_WINDOW);
266 // Initialize the window
267 CreateParams new_params = LoadDefaults(params);
268 window_type_ = new_params.window_type;
269 window_key_ = new_params.window_key;
271 // Windows cannot be always-on-top in fullscreen mode for security reasons.
272 cached_always_on_top_ = new_params.always_on_top;
273 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
274 new_params.always_on_top = false;
276 native_app_window_.reset(delegate_->CreateNativeAppWindow(this, new_params));
278 if (!new_params.hidden) {
279 // Panels are not activated by default.
280 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
281 : SHOW_ACTIVE);
284 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
285 Fullscreen();
286 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
287 Maximize();
288 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
289 Minimize();
291 OnNativeWindowChanged();
293 // When the render view host is changed, the native window needs to know
294 // about it in case it has any setup to do to make the renderer appear
295 // properly. In particular, on Windows, the view's clickthrough region needs
296 // to be set.
297 extensions::ExtensionsBrowserClient* client =
298 extensions::ExtensionsBrowserClient::Get();
299 registrar_.Add(this,
300 chrome::NOTIFICATION_EXTENSION_UNLOADED,
301 content::Source<content::BrowserContext>(
302 client->GetOriginalContext(browser_context_)));
303 // Close when the browser process is exiting.
304 registrar_.Add(this,
305 chrome::NOTIFICATION_APP_TERMINATING,
306 content::NotificationService::AllSources());
307 // Update the app menu if an ephemeral app becomes installed.
308 registrar_.Add(this,
309 chrome::NOTIFICATION_EXTENSION_INSTALLED,
310 content::Source<content::BrowserContext>(
311 client->GetOriginalContext(browser_context_)));
313 app_window_contents_->LoadContents(new_params.creator_process_id);
315 if (CommandLine::ForCurrentProcess()->HasSwitch(
316 switches::kEnableAppsShowOnFirstPaint)) {
317 // We want to show the window only when the content has been painted. For
318 // that to happen, we need to define a size for the content, otherwise the
319 // layout will happen in a 0x0 area.
320 // Note: WebContents::GetView() is guaranteed to be non-null.
321 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
322 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
323 initial_bounds.Inset(frame_insets);
324 web_contents->GetView()->SizeContents(initial_bounds.size());
327 // Prevent the browser process from shutting down while this window is open.
328 AppsClient::Get()->IncrementKeepAliveCount();
330 UpdateExtensionAppIcon();
332 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
335 AppWindow::~AppWindow() {
336 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
337 // last window open.
338 registrar_.RemoveAll();
340 // Remove shutdown prevention.
341 AppsClient::Get()->DecrementKeepAliveCount();
344 void AppWindow::RequestMediaAccessPermission(
345 content::WebContents* web_contents,
346 const content::MediaStreamRequest& request,
347 const content::MediaResponseCallback& callback) {
348 delegate_->RequestMediaAccessPermission(
349 web_contents, request, callback, extension());
352 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
353 const content::OpenURLParams& params) {
354 // Don't allow the current tab to be navigated. It would be nice to map all
355 // anchor tags (even those without target="_blank") to new tabs, but right
356 // now we can't distinguish between those and <meta> refreshes or window.href
357 // navigations, which we don't want to allow.
358 // TOOD(mihaip): Can we check for user gestures instead?
359 WindowOpenDisposition disposition = params.disposition;
360 if (disposition == CURRENT_TAB) {
361 AddMessageToDevToolsConsole(
362 content::CONSOLE_MESSAGE_LEVEL_ERROR,
363 base::StringPrintf(
364 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
365 params.url.spec().c_str()));
366 return NULL;
369 // These dispositions aren't really navigations.
370 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
371 disposition == IGNORE_ACTION) {
372 return NULL;
375 WebContents* contents =
376 delegate_->OpenURLFromTab(browser_context_, source, params);
377 if (!contents) {
378 AddMessageToDevToolsConsole(
379 content::CONSOLE_MESSAGE_LEVEL_ERROR,
380 base::StringPrintf(
381 "Can't navigate to \"%s\"; apps do not support navigation.",
382 params.url.spec().c_str()));
385 return contents;
388 void AppWindow::AddNewContents(WebContents* source,
389 WebContents* new_contents,
390 WindowOpenDisposition disposition,
391 const gfx::Rect& initial_pos,
392 bool user_gesture,
393 bool* was_blocked) {
394 DCHECK(new_contents->GetBrowserContext() == browser_context_);
395 delegate_->AddNewContents(browser_context_,
396 new_contents,
397 disposition,
398 initial_pos,
399 user_gesture,
400 was_blocked);
403 bool AppWindow::PreHandleKeyboardEvent(
404 content::WebContents* source,
405 const content::NativeWebKeyboardEvent& event,
406 bool* is_keyboard_shortcut) {
407 // Here, we can handle a key event before the content gets it. When we are
408 // fullscreen and it is not forced, we want to allow the user to leave
409 // when ESC is pressed.
410 // However, if the application has the "overrideEscFullscreen" permission, we
411 // should let it override that behavior.
412 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
413 // action is not prevented.
414 // Thus, we should handle the KeyEvent here only if the permission is not set.
415 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
416 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
417 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0) &&
418 !extension_->HasAPIPermission(APIPermission::kOverrideEscFullscreen)) {
419 Restore();
420 return true;
423 return false;
426 void AppWindow::HandleKeyboardEvent(
427 WebContents* source,
428 const content::NativeWebKeyboardEvent& event) {
429 // If the window is currently fullscreen and not forced, ESC should leave
430 // fullscreen. If this code is being called for ESC, that means that the
431 // KeyEvent's default behavior was not prevented by the content.
432 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
433 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
434 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0)) {
435 Restore();
436 return;
439 native_app_window_->HandleKeyboardEvent(event);
442 void AppWindow::RequestToLockMouse(WebContents* web_contents,
443 bool user_gesture,
444 bool last_unlocked_by_target) {
445 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
446 APIPermission::kPointerLock,
447 extension_,
448 web_contents->GetRenderViewHost());
450 web_contents->GotResponseToLockMouseRequest(has_permission);
453 bool AppWindow::PreHandleGestureEvent(WebContents* source,
454 const blink::WebGestureEvent& event) {
455 // Disable pinch zooming in app windows.
456 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
457 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
458 event.type == blink::WebGestureEvent::GesturePinchEnd;
461 void AppWindow::DidFirstVisuallyNonEmptyPaint(int32 page_id) {
462 first_paint_complete_ = true;
463 if (show_on_first_paint_) {
464 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
465 delayed_show_type_ == SHOW_INACTIVE);
466 Show(delayed_show_type_);
470 void AppWindow::OnNativeClose() {
471 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
472 if (app_window_contents_) {
473 WebContents* web_contents = app_window_contents_->GetWebContents();
474 WebContentsModalDialogManager::FromWebContents(web_contents)
475 ->SetDelegate(NULL);
476 app_window_contents_->NativeWindowClosed();
478 delete this;
481 void AppWindow::OnNativeWindowChanged() {
482 SaveWindowPosition();
484 #if defined(OS_WIN)
485 if (native_app_window_ && cached_always_on_top_ &&
486 !IsFullscreen(fullscreen_types_) && !native_app_window_->IsMaximized() &&
487 !native_app_window_->IsMinimized()) {
488 UpdateNativeAlwaysOnTop();
490 #endif
492 if (app_window_contents_ && native_app_window_)
493 app_window_contents_->NativeWindowChanged(native_app_window_.get());
496 void AppWindow::OnNativeWindowActivated() {
497 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
500 content::WebContents* AppWindow::web_contents() const {
501 return app_window_contents_->GetWebContents();
504 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
506 gfx::NativeWindow AppWindow::GetNativeWindow() {
507 return GetBaseWindow()->GetNativeWindow();
510 gfx::Rect AppWindow::GetClientBounds() const {
511 gfx::Rect bounds = native_app_window_->GetBounds();
512 bounds.Inset(native_app_window_->GetFrameInsets());
513 return bounds;
516 base::string16 AppWindow::GetTitle() const {
517 // WebContents::GetTitle() will return the page's URL if there's no <title>
518 // specified. However, we'd prefer to show the name of the extension in that
519 // case, so we directly inspect the NavigationEntry's title.
520 base::string16 title;
521 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
522 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
523 title = base::UTF8ToUTF16(extension()->name());
524 } else {
525 title = web_contents()->GetTitle();
527 const base::char16 kBadChars[] = {'\n', 0};
528 base::RemoveChars(title, kBadChars, &title);
529 return title;
532 void AppWindow::SetAppIconUrl(const GURL& url) {
533 // If the same url is being used for the badge, ignore it.
534 if (url == badge_icon_url_)
535 return;
537 // Avoid using any previous icons that were being downloaded.
538 image_loader_ptr_factory_.InvalidateWeakPtrs();
540 // Reset |app_icon_image_| to abort pending image load (if any).
541 app_icon_image_.reset();
543 app_icon_url_ = url;
544 web_contents()->DownloadImage(
545 url,
546 true, // is a favicon
547 0, // no maximum size
548 base::Bind(&AppWindow::DidDownloadFavicon,
549 image_loader_ptr_factory_.GetWeakPtr()));
552 void AppWindow::SetBadgeIconUrl(const GURL& url) {
553 // Avoid using any previous icons that were being downloaded.
554 image_loader_ptr_factory_.InvalidateWeakPtrs();
556 // Reset |app_icon_image_| to abort pending image load (if any).
557 badge_icon_image_.reset();
559 badge_icon_url_ = url;
560 web_contents()->DownloadImage(
561 url,
562 true, // is a favicon
563 0, // no maximum size
564 base::Bind(&AppWindow::DidDownloadFavicon,
565 image_loader_ptr_factory_.GetWeakPtr()));
568 void AppWindow::ClearBadge() {
569 badge_icon_image_.reset();
570 badge_icon_url_ = GURL();
571 UpdateBadgeIcon(gfx::Image());
574 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
575 native_app_window_->UpdateShape(region.Pass());
578 void AppWindow::UpdateDraggableRegions(
579 const std::vector<extensions::DraggableRegion>& regions) {
580 native_app_window_->UpdateDraggableRegions(regions);
583 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
584 if (image.IsEmpty())
585 return;
586 app_icon_ = image;
587 native_app_window_->UpdateWindowIcon();
588 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
591 void AppWindow::Fullscreen() {
592 #if !defined(OS_MACOSX)
593 // Do not enter fullscreen mode if disallowed by pref.
594 PrefService* prefs =
595 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
596 browser_context());
597 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
598 return;
599 #endif
600 fullscreen_types_ |= FULLSCREEN_TYPE_WINDOW_API;
601 SetNativeWindowFullscreen();
604 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
606 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
608 void AppWindow::Restore() {
609 if (IsFullscreen(fullscreen_types_)) {
610 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
611 SetNativeWindowFullscreen();
612 } else {
613 GetBaseWindow()->Restore();
617 void AppWindow::OSFullscreen() {
618 #if !defined(OS_MACOSX)
619 // Do not enter fullscreen mode if disallowed by pref.
620 PrefService* prefs =
621 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
622 browser_context());
623 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
624 return;
625 #endif
626 fullscreen_types_ |= FULLSCREEN_TYPE_OS;
627 SetNativeWindowFullscreen();
630 void AppWindow::ForcedFullscreen() {
631 fullscreen_types_ |= FULLSCREEN_TYPE_FORCED;
632 SetNativeWindowFullscreen();
635 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
636 const gfx::Size& max_size) {
637 SizeConstraints constraints(min_size, max_size);
638 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
639 constraints.GetMaximumSize());
641 gfx::Rect bounds = GetClientBounds();
642 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
643 if (bounds.size() != constrained_size) {
644 bounds.set_size(constrained_size);
645 bounds.Inset(-native_app_window_->GetFrameInsets());
646 native_app_window_->SetBounds(bounds);
648 OnNativeWindowChanged();
651 void AppWindow::Show(ShowType show_type) {
652 if (CommandLine::ForCurrentProcess()->HasSwitch(
653 switches::kEnableAppsShowOnFirstPaint)) {
654 show_on_first_paint_ = true;
656 if (!first_paint_complete_) {
657 delayed_show_type_ = show_type;
658 return;
662 switch (show_type) {
663 case SHOW_ACTIVE:
664 GetBaseWindow()->Show();
665 break;
666 case SHOW_INACTIVE:
667 GetBaseWindow()->ShowInactive();
668 break;
672 void AppWindow::Hide() {
673 // This is there to prevent race conditions with Hide() being called before
674 // there was a non-empty paint. It should have no effect in a non-racy
675 // scenario where the application is hiding then showing a window: the second
676 // show will not be delayed.
677 show_on_first_paint_ = false;
678 GetBaseWindow()->Hide();
681 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
682 if (cached_always_on_top_ == always_on_top)
683 return;
685 cached_always_on_top_ = always_on_top;
687 // As a security measure, do not allow fullscreen windows or windows that
688 // overlap the taskbar to be on top. The property will be applied when the
689 // window exits fullscreen and moves away from the taskbar.
690 if (!IsFullscreen(fullscreen_types_) && !IntersectsWithTaskbar())
691 native_app_window_->SetAlwaysOnTop(always_on_top);
693 OnNativeWindowChanged();
696 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
698 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
699 DCHECK(properties);
701 properties->SetBoolean("fullscreen",
702 native_app_window_->IsFullscreenOrPending());
703 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
704 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
705 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
706 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
707 properties->SetInteger("frameColor", native_app_window_->FrameColor());
709 gfx::Rect content_bounds = GetClientBounds();
710 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
711 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
712 SetBoundsProperties(content_bounds,
713 content_min_size,
714 content_max_size,
715 "innerBounds",
716 properties);
718 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
719 gfx::Rect frame_bounds = native_app_window_->GetBounds();
720 gfx::Size frame_min_size =
721 SizeConstraints::AddFrameToConstraints(content_min_size, frame_insets);
722 gfx::Size frame_max_size =
723 SizeConstraints::AddFrameToConstraints(content_max_size, frame_insets);
724 SetBoundsProperties(frame_bounds,
725 frame_min_size,
726 frame_max_size,
727 "outerBounds",
728 properties);
731 //------------------------------------------------------------------------------
732 // Private methods
734 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
735 badge_icon_ = image;
736 native_app_window_->UpdateBadgeIcon();
739 void AppWindow::DidDownloadFavicon(
740 int id,
741 int http_status_code,
742 const GURL& image_url,
743 const std::vector<SkBitmap>& bitmaps,
744 const std::vector<gfx::Size>& original_bitmap_sizes) {
745 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
746 bitmaps.empty()) {
747 return;
750 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
751 // whose height >= the preferred size.
752 int largest_index = 0;
753 for (size_t i = 1; i < bitmaps.size(); ++i) {
754 if (bitmaps[i].height() < delegate_->PreferredIconSize())
755 break;
756 largest_index = i;
758 const SkBitmap& largest = bitmaps[largest_index];
759 if (image_url == app_icon_url_) {
760 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
761 return;
764 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
767 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
768 DCHECK_EQ(app_icon_image_.get(), image);
770 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
773 void AppWindow::UpdateExtensionAppIcon() {
774 // Avoid using any previous app icons were being downloaded.
775 image_loader_ptr_factory_.InvalidateWeakPtrs();
777 app_icon_image_.reset(
778 new extensions::IconImage(browser_context(),
779 extension(),
780 extensions::IconsInfo::GetIcons(extension()),
781 delegate_->PreferredIconSize(),
782 extensions::IconsInfo::GetDefaultAppIcon(),
783 this));
785 // Triggers actual image loading with 1x resources. The 2x resource will
786 // be handled by IconImage class when requested.
787 app_icon_image_->image_skia().GetRepresentation(1.0f);
790 void AppWindow::SetNativeWindowFullscreen() {
791 native_app_window_->SetFullscreen(fullscreen_types_);
793 if (cached_always_on_top_)
794 UpdateNativeAlwaysOnTop();
797 bool AppWindow::IntersectsWithTaskbar() const {
798 #if defined(OS_WIN)
799 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
800 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
801 std::vector<gfx::Display> displays = screen->GetAllDisplays();
803 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
804 it != displays.end();
805 ++it) {
806 gfx::Rect taskbar_bounds = it->bounds();
807 taskbar_bounds.Subtract(it->work_area());
808 if (taskbar_bounds.IsEmpty())
809 continue;
811 if (window_bounds.Intersects(taskbar_bounds))
812 return true;
814 #endif
816 return false;
819 void AppWindow::UpdateNativeAlwaysOnTop() {
820 DCHECK(cached_always_on_top_);
821 bool is_on_top = native_app_window_->IsAlwaysOnTop();
822 bool fullscreen = IsFullscreen(fullscreen_types_);
823 bool intersects_taskbar = IntersectsWithTaskbar();
825 if (is_on_top && (fullscreen || intersects_taskbar)) {
826 // When entering fullscreen or overlapping the taskbar, ensure windows are
827 // not always-on-top.
828 native_app_window_->SetAlwaysOnTop(false);
829 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
830 // When exiting fullscreen and moving away from the taskbar, reinstate
831 // always-on-top.
832 native_app_window_->SetAlwaysOnTop(true);
836 void AppWindow::CloseContents(WebContents* contents) {
837 native_app_window_->Close();
840 bool AppWindow::ShouldSuppressDialogs() { return true; }
842 content::ColorChooser* AppWindow::OpenColorChooser(
843 WebContents* web_contents,
844 SkColor initial_color,
845 const std::vector<content::ColorSuggestion>& suggestionss) {
846 return delegate_->ShowColorChooser(web_contents, initial_color);
849 void AppWindow::RunFileChooser(WebContents* tab,
850 const content::FileChooserParams& params) {
851 if (window_type_is_panel()) {
852 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
853 // dialogs to be unhosted but still close with the owning web contents.
854 // crbug.com/172502.
855 LOG(WARNING) << "File dialog opened by panel.";
856 return;
859 delegate_->RunFileChooser(tab, params);
862 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
864 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
865 native_app_window_->SetBounds(pos);
868 void AppWindow::NavigationStateChanged(const content::WebContents* source,
869 unsigned changed_flags) {
870 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
871 native_app_window_->UpdateWindowTitle();
872 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
873 native_app_window_->UpdateWindowIcon();
876 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
877 bool enter_fullscreen) {
878 #if !defined(OS_MACOSX)
879 // Do not enter fullscreen mode if disallowed by pref.
880 // TODO(bartfab): Add a test once it becomes possible to simulate a user
881 // gesture. http://crbug.com/174178
882 PrefService* prefs =
883 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
884 browser_context());
885 if (enter_fullscreen && !prefs->GetBoolean(prefs::kAppFullscreenAllowed)) {
886 return;
888 #endif
890 if (!IsExtensionWithPermissionOrSuggestInConsole(
891 APIPermission::kFullscreen,
892 extension_,
893 source->GetRenderViewHost())) {
894 return;
897 if (enter_fullscreen)
898 fullscreen_types_ |= FULLSCREEN_TYPE_HTML_API;
899 else
900 fullscreen_types_ &= ~FULLSCREEN_TYPE_HTML_API;
901 SetNativeWindowFullscreen();
904 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
905 const {
906 return ((fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0);
909 void AppWindow::Observe(int type,
910 const content::NotificationSource& source,
911 const content::NotificationDetails& details) {
912 switch (type) {
913 case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
914 const extensions::Extension* unloaded_extension =
915 content::Details<extensions::UnloadedExtensionInfo>(details)
916 ->extension;
917 if (extension_ == unloaded_extension)
918 native_app_window_->Close();
919 break;
921 case chrome::NOTIFICATION_EXTENSION_INSTALLED: {
922 const extensions::Extension* installed_extension =
923 content::Details<const extensions::InstalledExtensionInfo>(details)
924 ->extension;
925 DCHECK(installed_extension);
926 if (installed_extension->id() == extension_->id())
927 native_app_window_->UpdateShelfMenu();
928 break;
930 case chrome::NOTIFICATION_APP_TERMINATING:
931 native_app_window_->Close();
932 break;
933 default:
934 NOTREACHED() << "Received unexpected notification";
938 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
939 bool blocked) {
940 delegate_->SetWebContentsBlocked(web_contents, blocked);
943 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
944 return delegate_->IsWebContentsVisible(web_contents);
947 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
948 return native_app_window_.get();
951 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
952 const std::string& message) {
953 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
954 rvh->Send(new ExtensionMsg_AddMessageToConsole(
955 rvh->GetRoutingID(), level, message));
958 void AppWindow::SaveWindowPosition() {
959 if (window_key_.empty())
960 return;
961 if (!native_app_window_)
962 return;
964 AppWindowGeometryCache* cache =
965 AppWindowGeometryCache::Get(browser_context());
967 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
968 gfx::Rect screen_bounds =
969 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
970 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
971 cache->SaveGeometry(
972 extension()->id(), window_key_, bounds, screen_bounds, window_state);
975 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
976 const gfx::Rect& cached_bounds,
977 const gfx::Rect& cached_screen_bounds,
978 const gfx::Rect& current_screen_bounds,
979 const gfx::Size& minimum_size,
980 gfx::Rect* bounds) const {
981 *bounds = cached_bounds;
983 // Reposition and resize the bounds if the cached_screen_bounds is different
984 // from the current screen bounds and the current screen bounds doesn't
985 // completely contain the bounds.
986 if (cached_screen_bounds != current_screen_bounds &&
987 !current_screen_bounds.Contains(cached_bounds)) {
988 bounds->set_width(
989 std::max(minimum_size.width(),
990 std::min(bounds->width(), current_screen_bounds.width())));
991 bounds->set_height(
992 std::max(minimum_size.height(),
993 std::min(bounds->height(), current_screen_bounds.height())));
994 bounds->set_x(
995 std::max(current_screen_bounds.x(),
996 std::min(bounds->x(),
997 current_screen_bounds.right() - bounds->width())));
998 bounds->set_y(
999 std::max(current_screen_bounds.y(),
1000 std::min(bounds->y(),
1001 current_screen_bounds.bottom() - bounds->height())));
1005 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1006 const {
1007 // Ensure width and height are specified.
1008 if (params.content_spec.bounds.width() == 0 &&
1009 params.window_spec.bounds.width() == 0) {
1010 params.content_spec.bounds.set_width(kDefaultWidth);
1012 if (params.content_spec.bounds.height() == 0 &&
1013 params.window_spec.bounds.height() == 0) {
1014 params.content_spec.bounds.set_height(kDefaultHeight);
1017 // If left and top are left undefined, the native app window will center
1018 // the window on the main screen in a platform-defined manner.
1020 // Load cached state if it exists.
1021 if (!params.window_key.empty()) {
1022 AppWindowGeometryCache* cache =
1023 AppWindowGeometryCache::Get(browser_context());
1025 gfx::Rect cached_bounds;
1026 gfx::Rect cached_screen_bounds;
1027 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1028 if (cache->GetGeometry(extension()->id(),
1029 params.window_key,
1030 &cached_bounds,
1031 &cached_screen_bounds,
1032 &cached_state)) {
1034 // App window has cached screen bounds, make sure it fits on screen in
1035 // case the screen resolution changed.
1036 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1037 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1038 gfx::Rect current_screen_bounds = display.work_area();
1039 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1040 params.GetWindowMaximumSize(gfx::Insets()));
1041 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1042 cached_screen_bounds,
1043 current_screen_bounds,
1044 constraints.GetMinimumSize(),
1045 &params.window_spec.bounds);
1046 params.state = cached_state;
1048 // Since we are restoring a cached state, reset the content bounds spec to
1049 // ensure it is not used.
1050 params.content_spec.ResetBounds();
1054 return params;
1057 // static
1058 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1059 const std::vector<extensions::DraggableRegion>& regions) {
1060 SkRegion* sk_region = new SkRegion;
1061 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
1062 regions.begin();
1063 iter != regions.end();
1064 ++iter) {
1065 const extensions::DraggableRegion& region = *iter;
1066 sk_region->op(
1067 region.bounds.x(),
1068 region.bounds.y(),
1069 region.bounds.right(),
1070 region.bounds.bottom(),
1071 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1073 return sk_region;
1076 } // namespace apps