Delete chrome.mediaGalleriesPrivate because the functionality unique to it has since...
[chromium-blink-merge.git] / extensions / browser / app_window / app_window.cc
blobfe9b75826db0b38d2566f463df12b2d2dc5fe933
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_pos,
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_pos,
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 bool was_hidden = is_hidden_ || !has_been_shown_;
664 is_hidden_ = false;
666 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
667 switches::kEnableAppsShowOnFirstPaint)) {
668 show_on_first_paint_ = true;
670 if (!first_paint_complete_) {
671 delayed_show_type_ = show_type;
672 return;
676 switch (show_type) {
677 case SHOW_ACTIVE:
678 GetBaseWindow()->Show();
679 break;
680 case SHOW_INACTIVE:
681 GetBaseWindow()->ShowInactive();
682 break;
684 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this, was_hidden);
686 has_been_shown_ = true;
687 SendOnWindowShownIfShown();
690 void AppWindow::Hide() {
691 // This is there to prevent race conditions with Hide() being called before
692 // there was a non-empty paint. It should have no effect in a non-racy
693 // scenario where the application is hiding then showing a window: the second
694 // show will not be delayed.
695 is_hidden_ = true;
696 show_on_first_paint_ = false;
697 GetBaseWindow()->Hide();
698 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
701 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
702 if (cached_always_on_top_ == always_on_top)
703 return;
705 cached_always_on_top_ = always_on_top;
707 // As a security measure, do not allow fullscreen windows or windows that
708 // overlap the taskbar to be on top. The property will be applied when the
709 // window exits fullscreen and moves away from the taskbar.
710 if (!IsFullscreen() && !IntersectsWithTaskbar())
711 native_app_window_->SetAlwaysOnTop(always_on_top);
713 OnNativeWindowChanged();
716 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
718 void AppWindow::SetInterceptAllKeys(bool want_all_keys) {
719 native_app_window_->SetInterceptAllKeys(want_all_keys);
722 void AppWindow::WindowEventsReady() {
723 can_send_events_ = true;
724 SendOnWindowShownIfShown();
727 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
728 DCHECK(properties);
730 properties->SetBoolean("fullscreen",
731 native_app_window_->IsFullscreenOrPending());
732 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
733 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
734 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
735 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
736 properties->SetBoolean(
737 "alphaEnabled",
738 requested_alpha_enabled_ && native_app_window_->CanHaveAlphaEnabled());
740 // These properties are undocumented and are to enable testing. Alpha is
741 // removed to
742 // make the values easier to check.
743 SkColor transparent_white = ~SK_ColorBLACK;
744 properties->SetInteger(
745 "activeFrameColor",
746 native_app_window_->ActiveFrameColor() & transparent_white);
747 properties->SetInteger(
748 "inactiveFrameColor",
749 native_app_window_->InactiveFrameColor() & transparent_white);
751 gfx::Rect content_bounds = GetClientBounds();
752 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
753 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
754 SetBoundsProperties(content_bounds,
755 content_min_size,
756 content_max_size,
757 "innerBounds",
758 properties);
760 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
761 gfx::Rect frame_bounds = native_app_window_->GetBounds();
762 gfx::Size frame_min_size = SizeConstraints::AddFrameToConstraints(
763 content_min_size, frame_insets);
764 gfx::Size frame_max_size = SizeConstraints::AddFrameToConstraints(
765 content_max_size, frame_insets);
766 SetBoundsProperties(frame_bounds,
767 frame_min_size,
768 frame_max_size,
769 "outerBounds",
770 properties);
773 //------------------------------------------------------------------------------
774 // Private methods
776 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
777 badge_icon_ = image;
778 native_app_window_->UpdateBadgeIcon();
781 void AppWindow::DidDownloadFavicon(
782 int id,
783 int http_status_code,
784 const GURL& image_url,
785 const std::vector<SkBitmap>& bitmaps,
786 const std::vector<gfx::Size>& original_bitmap_sizes) {
787 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
788 bitmaps.empty()) {
789 return;
792 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
793 // whose height >= the preferred size.
794 int largest_index = 0;
795 for (size_t i = 1; i < bitmaps.size(); ++i) {
796 if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
797 break;
798 largest_index = i;
800 const SkBitmap& largest = bitmaps[largest_index];
801 if (image_url == app_icon_url_) {
802 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
803 return;
806 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
809 void AppWindow::OnExtensionIconImageChanged(IconImage* image) {
810 DCHECK_EQ(app_icon_image_.get(), image);
812 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
815 void AppWindow::UpdateExtensionAppIcon() {
816 // Avoid using any previous app icons were being downloaded.
817 image_loader_ptr_factory_.InvalidateWeakPtrs();
819 const Extension* extension = GetExtension();
820 if (!extension)
821 return;
823 gfx::ImageSkia app_default_icon =
824 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
825 IDR_APP_DEFAULT_ICON);
827 app_icon_image_.reset(new IconImage(browser_context(),
828 extension,
829 IconsInfo::GetIcons(extension),
830 app_delegate_->PreferredIconSize(),
831 app_default_icon,
832 this));
834 // Triggers actual image loading with 1x resources. The 2x resource will
835 // be handled by IconImage class when requested.
836 app_icon_image_->image_skia().GetRepresentation(1.0f);
839 void AppWindow::SetNativeWindowFullscreen() {
840 native_app_window_->SetFullscreen(fullscreen_types_);
842 if (cached_always_on_top_)
843 UpdateNativeAlwaysOnTop();
846 bool AppWindow::IntersectsWithTaskbar() const {
847 #if defined(OS_WIN)
848 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
849 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
850 std::vector<gfx::Display> displays = screen->GetAllDisplays();
852 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
853 it != displays.end();
854 ++it) {
855 gfx::Rect taskbar_bounds = it->bounds();
856 taskbar_bounds.Subtract(it->work_area());
857 if (taskbar_bounds.IsEmpty())
858 continue;
860 if (window_bounds.Intersects(taskbar_bounds))
861 return true;
863 #endif
865 return false;
868 void AppWindow::UpdateNativeAlwaysOnTop() {
869 DCHECK(cached_always_on_top_);
870 bool is_on_top = native_app_window_->IsAlwaysOnTop();
871 bool fullscreen = IsFullscreen();
872 bool intersects_taskbar = IntersectsWithTaskbar();
874 if (is_on_top && (fullscreen || intersects_taskbar)) {
875 // When entering fullscreen or overlapping the taskbar, ensure windows are
876 // not always-on-top.
877 native_app_window_->SetAlwaysOnTop(false);
878 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
879 // When exiting fullscreen and moving away from the taskbar, reinstate
880 // always-on-top.
881 native_app_window_->SetAlwaysOnTop(true);
885 void AppWindow::SendOnWindowShownIfShown() {
886 if (!can_send_events_ || !has_been_shown_)
887 return;
889 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
890 ::switches::kTestType)) {
891 app_window_contents_->DispatchWindowShownForTests();
895 void AppWindow::CloseContents(WebContents* contents) {
896 native_app_window_->Close();
899 bool AppWindow::ShouldSuppressDialogs(WebContents* source) {
900 return true;
903 content::ColorChooser* AppWindow::OpenColorChooser(
904 WebContents* web_contents,
905 SkColor initial_color,
906 const std::vector<content::ColorSuggestion>& suggestions) {
907 return app_delegate_->ShowColorChooser(web_contents, initial_color);
910 void AppWindow::RunFileChooser(WebContents* tab,
911 const content::FileChooserParams& params) {
912 if (window_type_is_panel()) {
913 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
914 // dialogs to be unhosted but still close with the owning web contents.
915 // crbug.com/172502.
916 LOG(WARNING) << "File dialog opened by panel.";
917 return;
920 app_delegate_->RunFileChooser(tab, params);
923 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
925 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
926 native_app_window_->SetBounds(pos);
929 void AppWindow::NavigationStateChanged(content::WebContents* source,
930 content::InvalidateTypes changed_flags) {
931 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
932 native_app_window_->UpdateWindowTitle();
933 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
934 native_app_window_->UpdateWindowIcon();
937 void AppWindow::EnterFullscreenModeForTab(content::WebContents* source,
938 const GURL& origin) {
939 ToggleFullscreenModeForTab(source, true);
942 void AppWindow::ExitFullscreenModeForTab(content::WebContents* source) {
943 ToggleFullscreenModeForTab(source, false);
946 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
947 bool enter_fullscreen) {
948 const Extension* extension = GetExtension();
949 if (!extension)
950 return;
952 if (!IsExtensionWithPermissionOrSuggestInConsole(
953 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
954 return;
957 SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
960 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
961 const {
962 return IsHtmlApiFullscreen();
965 void AppWindow::Observe(int type,
966 const content::NotificationSource& source,
967 const content::NotificationDetails& details) {
968 switch (type) {
969 case NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
970 const Extension* unloaded_extension =
971 content::Details<UnloadedExtensionInfo>(details)->extension;
972 if (extension_id_ == unloaded_extension->id())
973 native_app_window_->Close();
974 break;
976 case NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
977 const Extension* installed_extension =
978 content::Details<const InstalledExtensionInfo>(details)->extension;
979 DCHECK(installed_extension);
980 if (installed_extension->id() == extension_id())
981 native_app_window_->UpdateShelfMenu();
982 break;
984 default:
985 NOTREACHED() << "Received unexpected notification";
989 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
990 bool blocked) {
991 app_delegate_->SetWebContentsBlocked(web_contents, blocked);
994 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
995 return app_delegate_->IsWebContentsVisible(web_contents);
998 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
999 return native_app_window_.get();
1002 void AppWindow::SaveWindowPosition() {
1003 if (window_key_.empty())
1004 return;
1005 if (!native_app_window_)
1006 return;
1008 AppWindowGeometryCache* cache =
1009 AppWindowGeometryCache::Get(browser_context());
1011 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
1012 gfx::Rect screen_bounds =
1013 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
1014 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1015 cache->SaveGeometry(
1016 extension_id(), window_key_, bounds, screen_bounds, window_state);
1019 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1020 const gfx::Rect& cached_bounds,
1021 const gfx::Rect& cached_screen_bounds,
1022 const gfx::Rect& current_screen_bounds,
1023 const gfx::Size& minimum_size,
1024 gfx::Rect* bounds) const {
1025 *bounds = cached_bounds;
1027 // Reposition and resize the bounds if the cached_screen_bounds is different
1028 // from the current screen bounds and the current screen bounds doesn't
1029 // completely contain the bounds.
1030 if (cached_screen_bounds != current_screen_bounds &&
1031 !current_screen_bounds.Contains(cached_bounds)) {
1032 bounds->set_width(
1033 std::max(minimum_size.width(),
1034 std::min(bounds->width(), current_screen_bounds.width())));
1035 bounds->set_height(
1036 std::max(minimum_size.height(),
1037 std::min(bounds->height(), current_screen_bounds.height())));
1038 bounds->set_x(
1039 std::max(current_screen_bounds.x(),
1040 std::min(bounds->x(),
1041 current_screen_bounds.right() - bounds->width())));
1042 bounds->set_y(
1043 std::max(current_screen_bounds.y(),
1044 std::min(bounds->y(),
1045 current_screen_bounds.bottom() - bounds->height())));
1049 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1050 const {
1051 // Ensure width and height are specified.
1052 if (params.content_spec.bounds.width() == 0 &&
1053 params.window_spec.bounds.width() == 0) {
1054 params.content_spec.bounds.set_width(kDefaultWidth);
1056 if (params.content_spec.bounds.height() == 0 &&
1057 params.window_spec.bounds.height() == 0) {
1058 params.content_spec.bounds.set_height(kDefaultHeight);
1061 // If left and top are left undefined, the native app window will center
1062 // the window on the main screen in a platform-defined manner.
1064 // Load cached state if it exists.
1065 if (!params.window_key.empty()) {
1066 AppWindowGeometryCache* cache =
1067 AppWindowGeometryCache::Get(browser_context());
1069 gfx::Rect cached_bounds;
1070 gfx::Rect cached_screen_bounds;
1071 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1072 if (cache->GetGeometry(extension_id(),
1073 params.window_key,
1074 &cached_bounds,
1075 &cached_screen_bounds,
1076 &cached_state)) {
1077 // App window has cached screen bounds, make sure it fits on screen in
1078 // case the screen resolution changed.
1079 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1080 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1081 gfx::Rect current_screen_bounds = display.work_area();
1082 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1083 params.GetWindowMaximumSize(gfx::Insets()));
1084 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1085 cached_screen_bounds,
1086 current_screen_bounds,
1087 constraints.GetMinimumSize(),
1088 &params.window_spec.bounds);
1089 params.state = cached_state;
1091 // Since we are restoring a cached state, reset the content bounds spec to
1092 // ensure it is not used.
1093 params.content_spec.ResetBounds();
1097 return params;
1100 // static
1101 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1102 const std::vector<DraggableRegion>& regions) {
1103 SkRegion* sk_region = new SkRegion;
1104 for (std::vector<DraggableRegion>::const_iterator iter = regions.begin();
1105 iter != regions.end();
1106 ++iter) {
1107 const DraggableRegion& region = *iter;
1108 sk_region->op(
1109 region.bounds.x(),
1110 region.bounds.y(),
1111 region.bounds.right(),
1112 region.bounds.bottom(),
1113 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1115 return sk_region;
1118 } // namespace extensions