Add more checks to investigate SupervisedUserPrefStore crash at startup.
[chromium-blink-merge.git] / extensions / browser / app_window / app_window.cc
blob83f29714f43fc036ca6371e82a0fa4f2ebf2827e
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 "extensions/browser/app_window/app_window.h"
7 #include <algorithm>
8 #include <string>
9 #include <vector>
11 #include "base/command_line.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/values.h"
15 #include "components/web_modal/web_contents_modal_dialog_manager.h"
16 #include "content/public/browser/browser_context.h"
17 #include "content/public/browser/invalidate_type.h"
18 #include "content/public/browser/navigation_entry.h"
19 #include "content/public/browser/notification_details.h"
20 #include "content/public/browser/notification_service.h"
21 #include "content/public/browser/notification_source.h"
22 #include "content/public/browser/notification_types.h"
23 #include "content/public/browser/render_view_host.h"
24 #include "content/public/browser/resource_dispatcher_host.h"
25 #include "content/public/browser/web_contents.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/media_stream_request.h"
28 #include "extensions/browser/app_window/app_delegate.h"
29 #include "extensions/browser/app_window/app_web_contents_helper.h"
30 #include "extensions/browser/app_window/app_window_client.h"
31 #include "extensions/browser/app_window/app_window_geometry_cache.h"
32 #include "extensions/browser/app_window/app_window_registry.h"
33 #include "extensions/browser/app_window/native_app_window.h"
34 #include "extensions/browser/app_window/size_constraints.h"
35 #include "extensions/browser/extension_registry.h"
36 #include "extensions/browser/extension_system.h"
37 #include "extensions/browser/extensions_browser_client.h"
38 #include "extensions/browser/notification_types.h"
39 #include "extensions/browser/process_manager.h"
40 #include "extensions/browser/suggest_permission_util.h"
41 #include "extensions/browser/view_type_utils.h"
42 #include "extensions/common/draggable_region.h"
43 #include "extensions/common/extension.h"
44 #include "extensions/common/manifest_handlers/icons_handler.h"
45 #include "extensions/common/permissions/permissions_data.h"
46 #include "extensions/common/switches.h"
47 #include "extensions/grit/extensions_browser_resources.h"
48 #include "third_party/skia/include/core/SkRegion.h"
49 #include "ui/base/resource/resource_bundle.h"
50 #include "ui/gfx/screen.h"
52 #if !defined(OS_MACOSX)
53 #include "base/prefs/pref_service.h"
54 #include "extensions/browser/pref_names.h"
55 #endif
57 using content::BrowserContext;
58 using content::ConsoleMessageLevel;
59 using content::WebContents;
60 using web_modal::WebContentsModalDialogHost;
61 using web_modal::WebContentsModalDialogManager;
63 namespace extensions {
65 namespace {
67 const int kDefaultWidth = 512;
68 const int kDefaultHeight = 384;
70 void SetConstraintProperty(const std::string& name,
71 int value,
72 base::DictionaryValue* bounds_properties) {
73 if (value != SizeConstraints::kUnboundedSize)
74 bounds_properties->SetInteger(name, value);
75 else
76 bounds_properties->Set(name, base::Value::CreateNullValue());
79 void SetBoundsProperties(const gfx::Rect& bounds,
80 const gfx::Size& min_size,
81 const gfx::Size& max_size,
82 const std::string& bounds_name,
83 base::DictionaryValue* window_properties) {
84 scoped_ptr<base::DictionaryValue> bounds_properties(
85 new base::DictionaryValue());
87 bounds_properties->SetInteger("left", bounds.x());
88 bounds_properties->SetInteger("top", bounds.y());
89 bounds_properties->SetInteger("width", bounds.width());
90 bounds_properties->SetInteger("height", bounds.height());
92 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
93 SetConstraintProperty(
94 "minHeight", min_size.height(), bounds_properties.get());
95 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
96 SetConstraintProperty(
97 "maxHeight", max_size.height(), bounds_properties.get());
99 window_properties->Set(bounds_name, bounds_properties.release());
102 // Combines the constraints of the content and window, and returns constraints
103 // for the window.
104 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
105 const gfx::Size& content_constraints,
106 const gfx::Insets& frame_insets) {
107 gfx::Size combined_constraints(window_constraints);
108 if (content_constraints.width() > 0) {
109 combined_constraints.set_width(
110 content_constraints.width() + frame_insets.width());
112 if (content_constraints.height() > 0) {
113 combined_constraints.set_height(
114 content_constraints.height() + frame_insets.height());
116 return combined_constraints;
119 // Combines the constraints of the content and window, and returns constraints
120 // for the content.
121 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
122 const gfx::Size& content_constraints,
123 const gfx::Insets& frame_insets) {
124 gfx::Size combined_constraints(content_constraints);
125 if (window_constraints.width() > 0) {
126 combined_constraints.set_width(
127 std::max(0, window_constraints.width() - frame_insets.width()));
129 if (window_constraints.height() > 0) {
130 combined_constraints.set_height(
131 std::max(0, window_constraints.height() - frame_insets.height()));
133 return combined_constraints;
136 } // namespace
138 // AppWindow::BoundsSpecification
140 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
142 AppWindow::BoundsSpecification::BoundsSpecification()
143 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
145 AppWindow::BoundsSpecification::~BoundsSpecification() {}
147 void AppWindow::BoundsSpecification::ResetBounds() {
148 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
151 // AppWindow::CreateParams
153 AppWindow::CreateParams::CreateParams()
154 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
155 frame(AppWindow::FRAME_CHROME),
156 has_frame_color(false),
157 active_frame_color(SK_ColorBLACK),
158 inactive_frame_color(SK_ColorBLACK),
159 alpha_enabled(false),
160 is_ime_window(false),
161 creator_process_id(0),
162 state(ui::SHOW_STATE_DEFAULT),
163 hidden(false),
164 resizable(true),
165 focused(true),
166 always_on_top(false),
167 visible_on_all_workspaces(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
230 AppWindow::AppWindow(BrowserContext* context,
231 AppDelegate* app_delegate,
232 const Extension* extension)
233 : browser_context_(context),
234 extension_id_(extension->id()),
235 window_type_(WINDOW_TYPE_DEFAULT),
236 app_delegate_(app_delegate),
237 fullscreen_types_(FULLSCREEN_TYPE_NONE),
238 show_on_first_paint_(false),
239 first_paint_complete_(false),
240 has_been_shown_(false),
241 can_send_events_(false),
242 is_hidden_(false),
243 cached_always_on_top_(false),
244 requested_alpha_enabled_(false),
245 image_loader_ptr_factory_(this) {
246 ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
247 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
248 << "Only off the record window may be opened in the guest mode.";
251 void AppWindow::Init(const GURL& url,
252 AppWindowContents* app_window_contents,
253 const CreateParams& params) {
254 // Initialize the render interface and web contents
255 app_window_contents_.reset(app_window_contents);
256 app_window_contents_->Initialize(browser_context(), url);
258 content::WebContentsObserver::Observe(web_contents());
259 app_delegate_->InitWebContents(web_contents());
261 WebContentsModalDialogManager::CreateForWebContents(web_contents());
263 web_contents()->SetDelegate(this);
264 WebContentsModalDialogManager::FromWebContents(web_contents())
265 ->SetDelegate(this);
266 SetViewType(web_contents(), VIEW_TYPE_APP_WINDOW);
268 // Initialize the window
269 CreateParams new_params = LoadDefaults(params);
270 window_type_ = new_params.window_type;
271 window_key_ = new_params.window_key;
273 // Windows cannot be always-on-top in fullscreen mode for security reasons.
274 cached_always_on_top_ = new_params.always_on_top;
275 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
276 new_params.always_on_top = false;
278 requested_alpha_enabled_ = new_params.alpha_enabled;
280 AppWindowClient* app_window_client = AppWindowClient::Get();
281 native_app_window_.reset(
282 app_window_client->CreateNativeAppWindow(this, &new_params));
284 helper_.reset(new AppWebContentsHelper(
285 browser_context_, extension_id_, web_contents(), app_delegate_.get()));
287 popup_manager_.reset(
288 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
289 popup_manager_->RegisterWith(web_contents());
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);
303 // These states may cause the window to show, so they are ignored if the
304 // window is initially hidden.
305 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
306 Fullscreen();
307 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
308 Maximize();
309 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
310 Minimize();
313 OnNativeWindowChanged();
315 // When the render view host is changed, the native window needs to know
316 // about it in case it has any setup to do to make the renderer appear
317 // properly. In particular, on Windows, the view's clickthrough region needs
318 // to be set[
319 ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
320 registrar_.Add(this,
321 NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
322 content::Source<content::BrowserContext>(
323 client->GetOriginalContext(browser_context_)));
324 // Update the app menu if an ephemeral app becomes installed.
325 registrar_.Add(this,
326 NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
327 content::Source<content::BrowserContext>(
328 client->GetOriginalContext(browser_context_)));
330 // Close when the browser process is exiting.
331 app_delegate_->SetTerminatingCallback(
332 base::Bind(&NativeAppWindow::Close,
333 base::Unretained(native_app_window_.get())));
335 app_window_contents_->LoadContents(new_params.creator_process_id);
337 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
338 extensions::switches::kEnableAppsShowOnFirstPaint)) {
339 // We want to show the window only when the content has been painted. For
340 // that to happen, we need to define a size for the content, otherwise the
341 // layout will happen in a 0x0 area.
342 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
343 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
344 initial_bounds.Inset(frame_insets);
345 app_delegate_->ResizeWebContents(web_contents(), initial_bounds.size());
349 AppWindow::~AppWindow() {
352 void AppWindow::RequestMediaAccessPermission(
353 content::WebContents* web_contents,
354 const content::MediaStreamRequest& request,
355 const content::MediaResponseCallback& callback) {
356 DCHECK_EQ(AppWindow::web_contents(), web_contents);
357 helper_->RequestMediaAccessPermission(request, callback);
360 bool AppWindow::CheckMediaAccessPermission(content::WebContents* web_contents,
361 const GURL& security_origin,
362 content::MediaStreamType type) {
363 DCHECK_EQ(AppWindow::web_contents(), web_contents);
364 return helper_->CheckMediaAccessPermission(security_origin, type);
367 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
368 const content::OpenURLParams& params) {
369 DCHECK_EQ(web_contents(), source);
370 return helper_->OpenURLFromTab(params);
373 void AppWindow::AddNewContents(WebContents* source,
374 WebContents* new_contents,
375 WindowOpenDisposition disposition,
376 const gfx::Rect& initial_rect,
377 bool user_gesture,
378 bool* was_blocked) {
379 DCHECK(new_contents->GetBrowserContext() == browser_context_);
380 app_delegate_->AddNewContents(browser_context_,
381 new_contents,
382 disposition,
383 initial_rect,
384 user_gesture,
385 was_blocked);
388 bool AppWindow::PreHandleKeyboardEvent(
389 content::WebContents* source,
390 const content::NativeWebKeyboardEvent& event,
391 bool* is_keyboard_shortcut) {
392 const Extension* extension = GetExtension();
393 if (!extension)
394 return false;
396 // Here, we can handle a key event before the content gets it. When we are
397 // fullscreen and it is not forced, we want to allow the user to leave
398 // when ESC is pressed.
399 // However, if the application has the "overrideEscFullscreen" permission, we
400 // should let it override that behavior.
401 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
402 // action is not prevented.
403 // Thus, we should handle the KeyEvent here only if the permission is not set.
404 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
405 !IsForcedFullscreen() &&
406 !extension->permissions_data()->HasAPIPermission(
407 APIPermission::kOverrideEscFullscreen)) {
408 Restore();
409 return true;
412 return false;
415 void AppWindow::HandleKeyboardEvent(
416 WebContents* source,
417 const content::NativeWebKeyboardEvent& event) {
418 // If the window is currently fullscreen and not forced, ESC should leave
419 // fullscreen. If this code is being called for ESC, that means that the
420 // KeyEvent's default behavior was not prevented by the content.
421 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
422 !IsForcedFullscreen()) {
423 Restore();
424 return;
427 native_app_window_->HandleKeyboardEvent(event);
430 void AppWindow::RequestToLockMouse(WebContents* web_contents,
431 bool user_gesture,
432 bool last_unlocked_by_target) {
433 DCHECK_EQ(AppWindow::web_contents(), web_contents);
434 helper_->RequestToLockMouse();
437 bool AppWindow::PreHandleGestureEvent(WebContents* source,
438 const blink::WebGestureEvent& event) {
439 return AppWebContentsHelper::ShouldSuppressGestureEvent(event);
442 void AppWindow::RenderViewCreated(content::RenderViewHost* render_view_host) {
443 app_delegate_->RenderViewCreated(render_view_host);
446 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
447 first_paint_complete_ = true;
448 if (show_on_first_paint_) {
449 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
450 delayed_show_type_ == SHOW_INACTIVE);
451 Show(delayed_show_type_);
455 void AppWindow::OnNativeClose() {
456 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
457 if (app_window_contents_) {
458 WebContentsModalDialogManager* modal_dialog_manager =
459 WebContentsModalDialogManager::FromWebContents(web_contents());
460 if (modal_dialog_manager) // May be null in unit tests.
461 modal_dialog_manager->SetDelegate(nullptr);
462 app_window_contents_->NativeWindowClosed();
464 delete this;
467 void AppWindow::OnNativeWindowChanged() {
468 SaveWindowPosition();
470 #if defined(OS_WIN)
471 if (native_app_window_ && cached_always_on_top_ && !IsFullscreen() &&
472 !native_app_window_->IsMaximized() &&
473 !native_app_window_->IsMinimized()) {
474 UpdateNativeAlwaysOnTop();
476 #endif
478 if (app_window_contents_ && native_app_window_)
479 app_window_contents_->NativeWindowChanged(native_app_window_.get());
482 void AppWindow::OnNativeWindowActivated() {
483 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
486 content::WebContents* AppWindow::web_contents() const {
487 return app_window_contents_->GetWebContents();
490 const Extension* AppWindow::GetExtension() const {
491 return ExtensionRegistry::Get(browser_context_)
492 ->enabled_extensions()
493 .GetByID(extension_id_);
496 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
498 gfx::NativeWindow AppWindow::GetNativeWindow() {
499 return GetBaseWindow()->GetNativeWindow();
502 gfx::Rect AppWindow::GetClientBounds() const {
503 gfx::Rect bounds = native_app_window_->GetBounds();
504 bounds.Inset(native_app_window_->GetFrameInsets());
505 return bounds;
508 base::string16 AppWindow::GetTitle() const {
509 const Extension* extension = GetExtension();
510 if (!extension)
511 return base::string16();
513 // WebContents::GetTitle() will return the page's URL if there's no <title>
514 // specified. However, we'd prefer to show the name of the extension in that
515 // case, so we directly inspect the NavigationEntry's title.
516 base::string16 title;
517 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
518 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
519 title = base::UTF8ToUTF16(extension->name());
520 } else {
521 title = web_contents()->GetTitle();
523 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
524 return title;
527 void AppWindow::SetAppIconUrl(const GURL& url) {
528 // If the same url is being used for the badge, ignore it.
529 if (url == badge_icon_url_)
530 return;
532 // Avoid using any previous icons that were being downloaded.
533 image_loader_ptr_factory_.InvalidateWeakPtrs();
535 // Reset |app_icon_image_| to abort pending image load (if any).
536 app_icon_image_.reset();
538 app_icon_url_ = url;
539 web_contents()->DownloadImage(
540 url,
541 true, // is a favicon
542 0, // no maximum size
543 base::Bind(&AppWindow::DidDownloadFavicon,
544 image_loader_ptr_factory_.GetWeakPtr()));
547 void AppWindow::SetBadgeIconUrl(const GURL& url) {
548 // Avoid using any previous icons that were being downloaded.
549 image_loader_ptr_factory_.InvalidateWeakPtrs();
551 // Reset |app_icon_image_| to abort pending image load (if any).
552 badge_icon_image_.reset();
554 badge_icon_url_ = url;
555 web_contents()->DownloadImage(
556 url,
557 true, // is a favicon
558 0, // no maximum size
559 base::Bind(&AppWindow::DidDownloadFavicon,
560 image_loader_ptr_factory_.GetWeakPtr()));
563 void AppWindow::ClearBadge() {
564 badge_icon_image_.reset();
565 badge_icon_url_ = GURL();
566 UpdateBadgeIcon(gfx::Image());
569 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
570 native_app_window_->UpdateShape(region.Pass());
573 void AppWindow::UpdateDraggableRegions(
574 const std::vector<DraggableRegion>& regions) {
575 native_app_window_->UpdateDraggableRegions(regions);
578 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
579 if (image.IsEmpty())
580 return;
581 app_icon_ = image;
582 native_app_window_->UpdateWindowIcon();
583 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
586 void AppWindow::SetFullscreen(FullscreenType type, bool enable) {
587 DCHECK_NE(FULLSCREEN_TYPE_NONE, type);
589 if (enable) {
590 #if !defined(OS_MACOSX)
591 // Do not enter fullscreen mode if disallowed by pref.
592 // TODO(bartfab): Add a test once it becomes possible to simulate a user
593 // gesture. http://crbug.com/174178
594 if (type != FULLSCREEN_TYPE_FORCED) {
595 PrefService* prefs =
596 ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
597 browser_context());
598 if (!prefs->GetBoolean(pref_names::kAppFullscreenAllowed))
599 return;
601 #endif
602 fullscreen_types_ |= type;
603 } else {
604 fullscreen_types_ &= ~type;
606 SetNativeWindowFullscreen();
609 bool AppWindow::IsFullscreen() const {
610 return fullscreen_types_ != FULLSCREEN_TYPE_NONE;
613 bool AppWindow::IsForcedFullscreen() const {
614 return (fullscreen_types_ & FULLSCREEN_TYPE_FORCED) != 0;
617 bool AppWindow::IsHtmlApiFullscreen() const {
618 return (fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0;
621 void AppWindow::Fullscreen() {
622 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API, true);
625 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
627 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
629 void AppWindow::Restore() {
630 if (IsFullscreen()) {
631 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
632 SetNativeWindowFullscreen();
633 } else {
634 GetBaseWindow()->Restore();
638 void AppWindow::OSFullscreen() {
639 SetFullscreen(FULLSCREEN_TYPE_OS, true);
642 void AppWindow::ForcedFullscreen() {
643 SetFullscreen(FULLSCREEN_TYPE_FORCED, true);
646 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
647 const gfx::Size& max_size) {
648 SizeConstraints constraints(min_size, max_size);
649 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
650 constraints.GetMaximumSize());
652 gfx::Rect bounds = GetClientBounds();
653 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
654 if (bounds.size() != constrained_size) {
655 bounds.set_size(constrained_size);
656 bounds.Inset(-native_app_window_->GetFrameInsets());
657 native_app_window_->SetBounds(bounds);
659 OnNativeWindowChanged();
662 void AppWindow::Show(ShowType show_type) {
663 app_delegate_->OnShow();
664 bool was_hidden = is_hidden_ || !has_been_shown_;
665 is_hidden_ = false;
667 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
668 switches::kEnableAppsShowOnFirstPaint)) {
669 show_on_first_paint_ = true;
671 if (!first_paint_complete_) {
672 delayed_show_type_ = show_type;
673 return;
677 switch (show_type) {
678 case SHOW_ACTIVE:
679 GetBaseWindow()->Show();
680 break;
681 case SHOW_INACTIVE:
682 GetBaseWindow()->ShowInactive();
683 break;
685 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this, was_hidden);
687 has_been_shown_ = true;
688 SendOnWindowShownIfShown();
691 void AppWindow::Hide() {
692 // This is there to prevent race conditions with Hide() being called before
693 // there was a non-empty paint. It should have no effect in a non-racy
694 // scenario where the application is hiding then showing a window: the second
695 // show will not be delayed.
696 is_hidden_ = true;
697 show_on_first_paint_ = false;
698 GetBaseWindow()->Hide();
699 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
700 app_delegate_->OnHide();
703 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
704 if (cached_always_on_top_ == always_on_top)
705 return;
707 cached_always_on_top_ = always_on_top;
709 // As a security measure, do not allow fullscreen windows or windows that
710 // overlap the taskbar to be on top. The property will be applied when the
711 // window exits fullscreen and moves away from the taskbar.
712 if (!IsFullscreen() && !IntersectsWithTaskbar())
713 native_app_window_->SetAlwaysOnTop(always_on_top);
715 OnNativeWindowChanged();
718 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
720 void AppWindow::SetInterceptAllKeys(bool want_all_keys) {
721 native_app_window_->SetInterceptAllKeys(want_all_keys);
724 void AppWindow::WindowEventsReady() {
725 can_send_events_ = true;
726 SendOnWindowShownIfShown();
729 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
730 DCHECK(properties);
732 properties->SetBoolean("fullscreen",
733 native_app_window_->IsFullscreenOrPending());
734 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
735 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
736 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
737 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
738 properties->SetBoolean(
739 "alphaEnabled",
740 requested_alpha_enabled_ && native_app_window_->CanHaveAlphaEnabled());
742 // These properties are undocumented and are to enable testing. Alpha is
743 // removed to
744 // make the values easier to check.
745 SkColor transparent_white = ~SK_ColorBLACK;
746 properties->SetInteger(
747 "activeFrameColor",
748 native_app_window_->ActiveFrameColor() & transparent_white);
749 properties->SetInteger(
750 "inactiveFrameColor",
751 native_app_window_->InactiveFrameColor() & transparent_white);
753 gfx::Rect content_bounds = GetClientBounds();
754 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
755 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
756 SetBoundsProperties(content_bounds,
757 content_min_size,
758 content_max_size,
759 "innerBounds",
760 properties);
762 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
763 gfx::Rect frame_bounds = native_app_window_->GetBounds();
764 gfx::Size frame_min_size = SizeConstraints::AddFrameToConstraints(
765 content_min_size, frame_insets);
766 gfx::Size frame_max_size = SizeConstraints::AddFrameToConstraints(
767 content_max_size, frame_insets);
768 SetBoundsProperties(frame_bounds,
769 frame_min_size,
770 frame_max_size,
771 "outerBounds",
772 properties);
775 //------------------------------------------------------------------------------
776 // Private methods
778 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
779 badge_icon_ = image;
780 native_app_window_->UpdateBadgeIcon();
783 void AppWindow::DidDownloadFavicon(
784 int id,
785 int http_status_code,
786 const GURL& image_url,
787 const std::vector<SkBitmap>& bitmaps,
788 const std::vector<gfx::Size>& original_bitmap_sizes) {
789 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
790 bitmaps.empty()) {
791 return;
794 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
795 // whose height >= the preferred size.
796 int largest_index = 0;
797 for (size_t i = 1; i < bitmaps.size(); ++i) {
798 if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
799 break;
800 largest_index = i;
802 const SkBitmap& largest = bitmaps[largest_index];
803 if (image_url == app_icon_url_) {
804 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
805 return;
808 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
811 void AppWindow::OnExtensionIconImageChanged(IconImage* image) {
812 DCHECK_EQ(app_icon_image_.get(), image);
814 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
817 void AppWindow::UpdateExtensionAppIcon() {
818 // Avoid using any previous app icons were being downloaded.
819 image_loader_ptr_factory_.InvalidateWeakPtrs();
821 const Extension* extension = GetExtension();
822 if (!extension)
823 return;
825 gfx::ImageSkia app_default_icon =
826 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
827 IDR_APP_DEFAULT_ICON);
829 app_icon_image_.reset(new IconImage(browser_context(),
830 extension,
831 IconsInfo::GetIcons(extension),
832 app_delegate_->PreferredIconSize(),
833 app_default_icon,
834 this));
836 // Triggers actual image loading with 1x resources. The 2x resource will
837 // be handled by IconImage class when requested.
838 app_icon_image_->image_skia().GetRepresentation(1.0f);
841 void AppWindow::SetNativeWindowFullscreen() {
842 native_app_window_->SetFullscreen(fullscreen_types_);
844 if (cached_always_on_top_)
845 UpdateNativeAlwaysOnTop();
848 bool AppWindow::IntersectsWithTaskbar() const {
849 #if defined(OS_WIN)
850 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
851 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
852 std::vector<gfx::Display> displays = screen->GetAllDisplays();
854 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
855 it != displays.end();
856 ++it) {
857 gfx::Rect taskbar_bounds = it->bounds();
858 taskbar_bounds.Subtract(it->work_area());
859 if (taskbar_bounds.IsEmpty())
860 continue;
862 if (window_bounds.Intersects(taskbar_bounds))
863 return true;
865 #endif
867 return false;
870 void AppWindow::UpdateNativeAlwaysOnTop() {
871 DCHECK(cached_always_on_top_);
872 bool is_on_top = native_app_window_->IsAlwaysOnTop();
873 bool fullscreen = IsFullscreen();
874 bool intersects_taskbar = IntersectsWithTaskbar();
876 if (is_on_top && (fullscreen || intersects_taskbar)) {
877 // When entering fullscreen or overlapping the taskbar, ensure windows are
878 // not always-on-top.
879 native_app_window_->SetAlwaysOnTop(false);
880 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
881 // When exiting fullscreen and moving away from the taskbar, reinstate
882 // always-on-top.
883 native_app_window_->SetAlwaysOnTop(true);
887 void AppWindow::SendOnWindowShownIfShown() {
888 if (!can_send_events_ || !has_been_shown_)
889 return;
891 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
892 ::switches::kTestType)) {
893 app_window_contents_->DispatchWindowShownForTests();
897 void AppWindow::CloseContents(WebContents* contents) {
898 native_app_window_->Close();
901 bool AppWindow::ShouldSuppressDialogs(WebContents* source) {
902 return true;
905 content::ColorChooser* AppWindow::OpenColorChooser(
906 WebContents* web_contents,
907 SkColor initial_color,
908 const std::vector<content::ColorSuggestion>& suggestions) {
909 return app_delegate_->ShowColorChooser(web_contents, initial_color);
912 void AppWindow::RunFileChooser(WebContents* tab,
913 const content::FileChooserParams& params) {
914 if (window_type_is_panel()) {
915 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
916 // dialogs to be unhosted but still close with the owning web contents.
917 // crbug.com/172502.
918 LOG(WARNING) << "File dialog opened by panel.";
919 return;
922 app_delegate_->RunFileChooser(tab, params);
925 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
927 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
928 native_app_window_->SetBounds(pos);
931 void AppWindow::NavigationStateChanged(content::WebContents* source,
932 content::InvalidateTypes changed_flags) {
933 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
934 native_app_window_->UpdateWindowTitle();
935 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
936 native_app_window_->UpdateWindowIcon();
939 void AppWindow::EnterFullscreenModeForTab(content::WebContents* source,
940 const GURL& origin) {
941 ToggleFullscreenModeForTab(source, true);
944 void AppWindow::ExitFullscreenModeForTab(content::WebContents* source) {
945 ToggleFullscreenModeForTab(source, false);
948 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
949 bool enter_fullscreen) {
950 const Extension* extension = GetExtension();
951 if (!extension)
952 return;
954 if (!IsExtensionWithPermissionOrSuggestInConsole(
955 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
956 return;
959 SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
962 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
963 const {
964 return IsHtmlApiFullscreen();
967 void AppWindow::Observe(int type,
968 const content::NotificationSource& source,
969 const content::NotificationDetails& details) {
970 switch (type) {
971 case NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
972 const Extension* unloaded_extension =
973 content::Details<UnloadedExtensionInfo>(details)->extension;
974 if (extension_id_ == unloaded_extension->id())
975 native_app_window_->Close();
976 break;
978 case NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
979 const Extension* installed_extension =
980 content::Details<const InstalledExtensionInfo>(details)->extension;
981 DCHECK(installed_extension);
982 if (installed_extension->id() == extension_id())
983 native_app_window_->UpdateShelfMenu();
984 break;
986 default:
987 NOTREACHED() << "Received unexpected notification";
991 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
992 bool blocked) {
993 app_delegate_->SetWebContentsBlocked(web_contents, blocked);
996 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
997 return app_delegate_->IsWebContentsVisible(web_contents);
1000 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
1001 return native_app_window_.get();
1004 void AppWindow::SaveWindowPosition() {
1005 if (window_key_.empty())
1006 return;
1007 if (!native_app_window_)
1008 return;
1010 AppWindowGeometryCache* cache =
1011 AppWindowGeometryCache::Get(browser_context());
1013 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
1014 gfx::Rect screen_bounds =
1015 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
1016 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1017 cache->SaveGeometry(
1018 extension_id(), window_key_, bounds, screen_bounds, window_state);
1021 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1022 const gfx::Rect& cached_bounds,
1023 const gfx::Rect& cached_screen_bounds,
1024 const gfx::Rect& current_screen_bounds,
1025 const gfx::Size& minimum_size,
1026 gfx::Rect* bounds) const {
1027 *bounds = cached_bounds;
1029 // Reposition and resize the bounds if the cached_screen_bounds is different
1030 // from the current screen bounds and the current screen bounds doesn't
1031 // completely contain the bounds.
1032 if (cached_screen_bounds != current_screen_bounds &&
1033 !current_screen_bounds.Contains(cached_bounds)) {
1034 bounds->set_width(
1035 std::max(minimum_size.width(),
1036 std::min(bounds->width(), current_screen_bounds.width())));
1037 bounds->set_height(
1038 std::max(minimum_size.height(),
1039 std::min(bounds->height(), current_screen_bounds.height())));
1040 bounds->set_x(
1041 std::max(current_screen_bounds.x(),
1042 std::min(bounds->x(),
1043 current_screen_bounds.right() - bounds->width())));
1044 bounds->set_y(
1045 std::max(current_screen_bounds.y(),
1046 std::min(bounds->y(),
1047 current_screen_bounds.bottom() - bounds->height())));
1051 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1052 const {
1053 // Ensure width and height are specified.
1054 if (params.content_spec.bounds.width() == 0 &&
1055 params.window_spec.bounds.width() == 0) {
1056 params.content_spec.bounds.set_width(kDefaultWidth);
1058 if (params.content_spec.bounds.height() == 0 &&
1059 params.window_spec.bounds.height() == 0) {
1060 params.content_spec.bounds.set_height(kDefaultHeight);
1063 // If left and top are left undefined, the native app window will center
1064 // the window on the main screen in a platform-defined manner.
1066 // Load cached state if it exists.
1067 if (!params.window_key.empty()) {
1068 AppWindowGeometryCache* cache =
1069 AppWindowGeometryCache::Get(browser_context());
1071 gfx::Rect cached_bounds;
1072 gfx::Rect cached_screen_bounds;
1073 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1074 if (cache->GetGeometry(extension_id(),
1075 params.window_key,
1076 &cached_bounds,
1077 &cached_screen_bounds,
1078 &cached_state)) {
1079 // App window has cached screen bounds, make sure it fits on screen in
1080 // case the screen resolution changed.
1081 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1082 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1083 gfx::Rect current_screen_bounds = display.work_area();
1084 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1085 params.GetWindowMaximumSize(gfx::Insets()));
1086 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1087 cached_screen_bounds,
1088 current_screen_bounds,
1089 constraints.GetMinimumSize(),
1090 &params.window_spec.bounds);
1091 params.state = cached_state;
1093 // Since we are restoring a cached state, reset the content bounds spec to
1094 // ensure it is not used.
1095 params.content_spec.ResetBounds();
1099 return params;
1102 // static
1103 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1104 const std::vector<DraggableRegion>& regions) {
1105 SkRegion* sk_region = new SkRegion;
1106 for (std::vector<DraggableRegion>::const_iterator iter = regions.begin();
1107 iter != regions.end();
1108 ++iter) {
1109 const DraggableRegion& region = *iter;
1110 sk_region->op(
1111 region.bounds.x(),
1112 region.bounds.y(),
1113 region.bounds.right(),
1114 region.bounds.bottom(),
1115 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1117 return sk_region;
1120 } // namespace extensions