Removes app badging code
[chromium-blink-merge.git] / extensions / browser / app_window / app_window.cc
blobc1959a98c82541c665e543ff7fba235de8b74b5f
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/render_view_host.h"
20 #include "content/public/browser/resource_dispatcher_host.h"
21 #include "content/public/browser/web_contents.h"
22 #include "content/public/common/content_switches.h"
23 #include "content/public/common/media_stream_request.h"
24 #include "extensions/browser/app_window/app_delegate.h"
25 #include "extensions/browser/app_window/app_web_contents_helper.h"
26 #include "extensions/browser/app_window/app_window_client.h"
27 #include "extensions/browser/app_window/app_window_geometry_cache.h"
28 #include "extensions/browser/app_window/app_window_registry.h"
29 #include "extensions/browser/app_window/native_app_window.h"
30 #include "extensions/browser/app_window/size_constraints.h"
31 #include "extensions/browser/extension_registry.h"
32 #include "extensions/browser/extension_system.h"
33 #include "extensions/browser/extensions_browser_client.h"
34 #include "extensions/browser/notification_types.h"
35 #include "extensions/browser/process_manager.h"
36 #include "extensions/browser/suggest_permission_util.h"
37 #include "extensions/browser/view_type_utils.h"
38 #include "extensions/common/draggable_region.h"
39 #include "extensions/common/extension.h"
40 #include "extensions/common/manifest_handlers/icons_handler.h"
41 #include "extensions/common/permissions/permissions_data.h"
42 #include "extensions/common/switches.h"
43 #include "extensions/grit/extensions_browser_resources.h"
44 #include "third_party/skia/include/core/SkRegion.h"
45 #include "ui/base/resource/resource_bundle.h"
46 #include "ui/gfx/screen.h"
48 #if !defined(OS_MACOSX)
49 #include "base/prefs/pref_service.h"
50 #include "extensions/browser/pref_names.h"
51 #endif
53 using content::BrowserContext;
54 using content::ConsoleMessageLevel;
55 using content::WebContents;
56 using web_modal::WebContentsModalDialogHost;
57 using web_modal::WebContentsModalDialogManager;
59 namespace extensions {
61 namespace {
63 const int kDefaultWidth = 512;
64 const int kDefaultHeight = 384;
66 void SetConstraintProperty(const std::string& name,
67 int value,
68 base::DictionaryValue* bounds_properties) {
69 if (value != SizeConstraints::kUnboundedSize)
70 bounds_properties->SetInteger(name, value);
71 else
72 bounds_properties->Set(name, base::Value::CreateNullValue());
75 void SetBoundsProperties(const gfx::Rect& bounds,
76 const gfx::Size& min_size,
77 const gfx::Size& max_size,
78 const std::string& bounds_name,
79 base::DictionaryValue* window_properties) {
80 scoped_ptr<base::DictionaryValue> bounds_properties(
81 new base::DictionaryValue());
83 bounds_properties->SetInteger("left", bounds.x());
84 bounds_properties->SetInteger("top", bounds.y());
85 bounds_properties->SetInteger("width", bounds.width());
86 bounds_properties->SetInteger("height", bounds.height());
88 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
89 SetConstraintProperty(
90 "minHeight", min_size.height(), bounds_properties.get());
91 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
92 SetConstraintProperty(
93 "maxHeight", max_size.height(), bounds_properties.get());
95 window_properties->Set(bounds_name, bounds_properties.release());
98 // Combines the constraints of the content and window, and returns constraints
99 // for the window.
100 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
101 const gfx::Size& content_constraints,
102 const gfx::Insets& frame_insets) {
103 gfx::Size combined_constraints(window_constraints);
104 if (content_constraints.width() > 0) {
105 combined_constraints.set_width(
106 content_constraints.width() + frame_insets.width());
108 if (content_constraints.height() > 0) {
109 combined_constraints.set_height(
110 content_constraints.height() + frame_insets.height());
112 return combined_constraints;
115 // Combines the constraints of the content and window, and returns constraints
116 // for the content.
117 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
118 const gfx::Size& content_constraints,
119 const gfx::Insets& frame_insets) {
120 gfx::Size combined_constraints(content_constraints);
121 if (window_constraints.width() > 0) {
122 combined_constraints.set_width(
123 std::max(0, window_constraints.width() - frame_insets.width()));
125 if (window_constraints.height() > 0) {
126 combined_constraints.set_height(
127 std::max(0, window_constraints.height() - frame_insets.height()));
129 return combined_constraints;
132 } // namespace
134 // AppWindow::BoundsSpecification
136 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
138 AppWindow::BoundsSpecification::BoundsSpecification()
139 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
141 AppWindow::BoundsSpecification::~BoundsSpecification() {}
143 void AppWindow::BoundsSpecification::ResetBounds() {
144 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
147 // AppWindow::CreateParams
149 AppWindow::CreateParams::CreateParams()
150 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
151 frame(AppWindow::FRAME_CHROME),
152 has_frame_color(false),
153 active_frame_color(SK_ColorBLACK),
154 inactive_frame_color(SK_ColorBLACK),
155 alpha_enabled(false),
156 is_ime_window(false),
157 creator_process_id(0),
158 state(ui::SHOW_STATE_DEFAULT),
159 hidden(false),
160 resizable(true),
161 focused(true),
162 always_on_top(false),
163 visible_on_all_workspaces(false) {
166 AppWindow::CreateParams::~CreateParams() {}
168 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
169 const gfx::Insets& frame_insets) const {
170 // Combine into a single window bounds.
171 gfx::Rect combined_bounds(window_spec.bounds);
172 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
173 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
174 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
175 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
176 if (content_spec.bounds.width() > 0) {
177 combined_bounds.set_width(
178 content_spec.bounds.width() + frame_insets.width());
180 if (content_spec.bounds.height() > 0) {
181 combined_bounds.set_height(
182 content_spec.bounds.height() + frame_insets.height());
185 // Constrain the bounds.
186 SizeConstraints constraints(
187 GetCombinedWindowConstraints(
188 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
189 GetCombinedWindowConstraints(
190 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
191 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
193 return combined_bounds;
196 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
197 const gfx::Insets& frame_insets) const {
198 return GetCombinedContentConstraints(window_spec.minimum_size,
199 content_spec.minimum_size,
200 frame_insets);
203 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
204 const gfx::Insets& frame_insets) const {
205 return GetCombinedContentConstraints(window_spec.maximum_size,
206 content_spec.maximum_size,
207 frame_insets);
210 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
211 const gfx::Insets& frame_insets) const {
212 return GetCombinedWindowConstraints(window_spec.minimum_size,
213 content_spec.minimum_size,
214 frame_insets);
217 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
218 const gfx::Insets& frame_insets) const {
219 return GetCombinedWindowConstraints(window_spec.maximum_size,
220 content_spec.maximum_size,
221 frame_insets);
224 // AppWindow
226 AppWindow::AppWindow(BrowserContext* context,
227 AppDelegate* app_delegate,
228 const Extension* extension)
229 : browser_context_(context),
230 extension_id_(extension->id()),
231 window_type_(WINDOW_TYPE_DEFAULT),
232 app_delegate_(app_delegate),
233 fullscreen_types_(FULLSCREEN_TYPE_NONE),
234 show_on_first_paint_(false),
235 first_paint_complete_(false),
236 has_been_shown_(false),
237 can_send_events_(false),
238 is_hidden_(false),
239 cached_always_on_top_(false),
240 requested_alpha_enabled_(false),
241 is_ime_window_(false),
242 image_loader_ptr_factory_(this) {
243 ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
244 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
245 << "Only off the record window may be opened in the guest mode.";
248 void AppWindow::Init(const GURL& url,
249 AppWindowContents* app_window_contents,
250 const CreateParams& params) {
251 // Initialize the render interface and web contents
252 app_window_contents_.reset(app_window_contents);
253 app_window_contents_->Initialize(browser_context(), url);
255 initial_url_ = url;
257 content::WebContentsObserver::Observe(web_contents());
258 SetViewType(web_contents(), VIEW_TYPE_APP_WINDOW);
259 app_delegate_->InitWebContents(web_contents());
261 WebContentsModalDialogManager::CreateForWebContents(web_contents());
263 web_contents()->SetDelegate(this);
264 WebContentsModalDialogManager::FromWebContents(web_contents())
265 ->SetDelegate(this);
267 // Initialize the window
268 CreateParams new_params = LoadDefaults(params);
269 window_type_ = new_params.window_type;
270 window_key_ = new_params.window_key;
272 // Windows cannot be always-on-top in fullscreen mode for security reasons.
273 cached_always_on_top_ = new_params.always_on_top;
274 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
275 new_params.always_on_top = false;
277 requested_alpha_enabled_ = new_params.alpha_enabled;
279 is_ime_window_ = params.is_ime_window;
281 AppWindowClient* app_window_client = AppWindowClient::Get();
282 native_app_window_.reset(
283 app_window_client->CreateNativeAppWindow(this, &new_params));
285 helper_.reset(new AppWebContentsHelper(
286 browser_context_, extension_id_, web_contents(), app_delegate_.get()));
288 popup_manager_.reset(
289 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
290 popup_manager_->RegisterWith(web_contents());
292 UpdateExtensionAppIcon();
293 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
295 if (new_params.hidden) {
296 // Although the window starts hidden by default, calling Hide() here
297 // notifies observers of the window being hidden.
298 Hide();
299 } else {
300 // Panels are not activated by default.
301 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
302 : SHOW_ACTIVE);
304 // These states may cause the window to show, so they are ignored if the
305 // window is initially hidden.
306 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
307 Fullscreen();
308 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
309 Maximize();
310 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
311 Minimize();
314 OnNativeWindowChanged();
316 ExtensionRegistry::Get(browser_context_)->AddObserver(this);
318 // Close when the browser process is exiting.
319 app_delegate_->SetTerminatingCallback(
320 base::Bind(&NativeAppWindow::Close,
321 base::Unretained(native_app_window_.get())));
323 app_window_contents_->LoadContents(new_params.creator_process_id);
325 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
326 extensions::switches::kEnableAppsShowOnFirstPaint)) {
327 // We want to show the window only when the content has been painted. For
328 // that to happen, we need to define a size for the content, otherwise the
329 // layout will happen in a 0x0 area.
330 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
331 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
332 initial_bounds.Inset(frame_insets);
333 app_delegate_->ResizeWebContents(web_contents(), initial_bounds.size());
337 AppWindow::~AppWindow() {
338 ExtensionRegistry::Get(browser_context_)->RemoveObserver(this);
341 void AppWindow::RequestMediaAccessPermission(
342 content::WebContents* web_contents,
343 const content::MediaStreamRequest& request,
344 const content::MediaResponseCallback& callback) {
345 DCHECK_EQ(AppWindow::web_contents(), web_contents);
346 helper_->RequestMediaAccessPermission(request, callback);
349 bool AppWindow::CheckMediaAccessPermission(content::WebContents* web_contents,
350 const GURL& security_origin,
351 content::MediaStreamType type) {
352 DCHECK_EQ(AppWindow::web_contents(), web_contents);
353 return helper_->CheckMediaAccessPermission(security_origin, type);
356 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
357 const content::OpenURLParams& params) {
358 DCHECK_EQ(web_contents(), source);
359 return helper_->OpenURLFromTab(params);
362 void AppWindow::AddNewContents(WebContents* source,
363 WebContents* new_contents,
364 WindowOpenDisposition disposition,
365 const gfx::Rect& initial_rect,
366 bool user_gesture,
367 bool* was_blocked) {
368 DCHECK(new_contents->GetBrowserContext() == browser_context_);
369 app_delegate_->AddNewContents(browser_context_,
370 new_contents,
371 disposition,
372 initial_rect,
373 user_gesture,
374 was_blocked);
377 bool AppWindow::PreHandleKeyboardEvent(
378 content::WebContents* source,
379 const content::NativeWebKeyboardEvent& event,
380 bool* is_keyboard_shortcut) {
381 const Extension* extension = GetExtension();
382 if (!extension)
383 return false;
385 // Here, we can handle a key event before the content gets it. When we are
386 // fullscreen and it is not forced, we want to allow the user to leave
387 // when ESC is pressed.
388 // However, if the application has the "overrideEscFullscreen" permission, we
389 // should let it override that behavior.
390 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
391 // action is not prevented.
392 // Thus, we should handle the KeyEvent here only if the permission is not set.
393 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
394 !IsForcedFullscreen() &&
395 !extension->permissions_data()->HasAPIPermission(
396 APIPermission::kOverrideEscFullscreen)) {
397 Restore();
398 return true;
401 return false;
404 void AppWindow::HandleKeyboardEvent(
405 WebContents* source,
406 const content::NativeWebKeyboardEvent& event) {
407 // If the window is currently fullscreen and not forced, ESC should leave
408 // fullscreen. If this code is being called for ESC, that means that the
409 // KeyEvent's default behavior was not prevented by the content.
410 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
411 !IsForcedFullscreen()) {
412 Restore();
413 return;
416 native_app_window_->HandleKeyboardEvent(event);
419 void AppWindow::RequestToLockMouse(WebContents* web_contents,
420 bool user_gesture,
421 bool last_unlocked_by_target) {
422 DCHECK_EQ(AppWindow::web_contents(), web_contents);
423 helper_->RequestToLockMouse();
426 bool AppWindow::PreHandleGestureEvent(WebContents* source,
427 const blink::WebGestureEvent& event) {
428 return AppWebContentsHelper::ShouldSuppressGestureEvent(event);
431 void AppWindow::RenderViewCreated(content::RenderViewHost* render_view_host) {
432 app_delegate_->RenderViewCreated(render_view_host);
435 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
436 first_paint_complete_ = true;
437 if (show_on_first_paint_) {
438 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
439 delayed_show_type_ == SHOW_INACTIVE);
440 Show(delayed_show_type_);
444 void AppWindow::OnNativeClose() {
445 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
446 if (app_window_contents_) {
447 WebContentsModalDialogManager* modal_dialog_manager =
448 WebContentsModalDialogManager::FromWebContents(web_contents());
449 if (modal_dialog_manager) // May be null in unit tests.
450 modal_dialog_manager->SetDelegate(nullptr);
451 app_window_contents_->NativeWindowClosed();
453 delete this;
456 void AppWindow::OnNativeWindowChanged() {
457 SaveWindowPosition();
459 #if defined(OS_WIN)
460 if (native_app_window_ && cached_always_on_top_ && !IsFullscreen() &&
461 !native_app_window_->IsMaximized() &&
462 !native_app_window_->IsMinimized()) {
463 UpdateNativeAlwaysOnTop();
465 #endif
467 if (app_window_contents_ && native_app_window_)
468 app_window_contents_->NativeWindowChanged(native_app_window_.get());
471 void AppWindow::OnNativeWindowActivated() {
472 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
475 content::WebContents* AppWindow::web_contents() const {
476 return app_window_contents_->GetWebContents();
479 const Extension* AppWindow::GetExtension() const {
480 return ExtensionRegistry::Get(browser_context_)
481 ->enabled_extensions()
482 .GetByID(extension_id_);
485 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
487 gfx::NativeWindow AppWindow::GetNativeWindow() {
488 return GetBaseWindow()->GetNativeWindow();
491 gfx::Rect AppWindow::GetClientBounds() const {
492 gfx::Rect bounds = native_app_window_->GetBounds();
493 bounds.Inset(native_app_window_->GetFrameInsets());
494 return bounds;
497 base::string16 AppWindow::GetTitle() const {
498 const Extension* extension = GetExtension();
499 if (!extension)
500 return base::string16();
502 // WebContents::GetTitle() will return the page's URL if there's no <title>
503 // specified. However, we'd prefer to show the name of the extension in that
504 // case, so we directly inspect the NavigationEntry's title.
505 base::string16 title;
506 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
507 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
508 title = base::UTF8ToUTF16(extension->name());
509 } else {
510 title = web_contents()->GetTitle();
512 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
513 return title;
516 void AppWindow::SetAppIconUrl(const GURL& url) {
517 // Avoid using any previous icons that were being downloaded.
518 image_loader_ptr_factory_.InvalidateWeakPtrs();
520 // Reset |app_icon_image_| to abort pending image load (if any).
521 app_icon_image_.reset();
523 app_icon_url_ = url;
524 web_contents()->DownloadImage(
525 url,
526 true, // is a favicon
527 0, // no maximum size
528 false, // normal cache policy
529 base::Bind(&AppWindow::DidDownloadFavicon,
530 image_loader_ptr_factory_.GetWeakPtr()));
533 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
534 native_app_window_->UpdateShape(region.Pass());
537 void AppWindow::UpdateDraggableRegions(
538 const std::vector<DraggableRegion>& regions) {
539 native_app_window_->UpdateDraggableRegions(regions);
542 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
543 if (image.IsEmpty())
544 return;
545 app_icon_ = image;
546 native_app_window_->UpdateWindowIcon();
547 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
550 void AppWindow::SetFullscreen(FullscreenType type, bool enable) {
551 DCHECK_NE(FULLSCREEN_TYPE_NONE, type);
553 if (enable) {
554 #if !defined(OS_MACOSX)
555 // Do not enter fullscreen mode if disallowed by pref.
556 // TODO(bartfab): Add a test once it becomes possible to simulate a user
557 // gesture. http://crbug.com/174178
558 if (type != FULLSCREEN_TYPE_FORCED) {
559 PrefService* prefs =
560 ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
561 browser_context());
562 if (!prefs->GetBoolean(pref_names::kAppFullscreenAllowed))
563 return;
565 #endif
566 fullscreen_types_ |= type;
567 } else {
568 fullscreen_types_ &= ~type;
570 SetNativeWindowFullscreen();
573 bool AppWindow::IsFullscreen() const {
574 return fullscreen_types_ != FULLSCREEN_TYPE_NONE;
577 bool AppWindow::IsForcedFullscreen() const {
578 return (fullscreen_types_ & FULLSCREEN_TYPE_FORCED) != 0;
581 bool AppWindow::IsHtmlApiFullscreen() const {
582 return (fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0;
585 void AppWindow::Fullscreen() {
586 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API, true);
589 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
591 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
593 void AppWindow::Restore() {
594 if (IsFullscreen()) {
595 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
596 SetNativeWindowFullscreen();
597 } else {
598 GetBaseWindow()->Restore();
602 void AppWindow::OSFullscreen() {
603 SetFullscreen(FULLSCREEN_TYPE_OS, true);
606 void AppWindow::ForcedFullscreen() {
607 SetFullscreen(FULLSCREEN_TYPE_FORCED, true);
610 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
611 const gfx::Size& max_size) {
612 SizeConstraints constraints(min_size, max_size);
613 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
614 constraints.GetMaximumSize());
616 gfx::Rect bounds = GetClientBounds();
617 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
618 if (bounds.size() != constrained_size) {
619 bounds.set_size(constrained_size);
620 bounds.Inset(-native_app_window_->GetFrameInsets());
621 native_app_window_->SetBounds(bounds);
623 OnNativeWindowChanged();
626 void AppWindow::Show(ShowType show_type) {
627 app_delegate_->OnShow();
628 bool was_hidden = is_hidden_ || !has_been_shown_;
629 is_hidden_ = false;
631 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
632 switches::kEnableAppsShowOnFirstPaint)) {
633 show_on_first_paint_ = true;
635 if (!first_paint_complete_) {
636 delayed_show_type_ = show_type;
637 return;
641 switch (show_type) {
642 case SHOW_ACTIVE:
643 GetBaseWindow()->Show();
644 break;
645 case SHOW_INACTIVE:
646 GetBaseWindow()->ShowInactive();
647 break;
649 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this, was_hidden);
651 has_been_shown_ = true;
652 SendOnWindowShownIfShown();
655 void AppWindow::Hide() {
656 // This is there to prevent race conditions with Hide() being called before
657 // there was a non-empty paint. It should have no effect in a non-racy
658 // scenario where the application is hiding then showing a window: the second
659 // show will not be delayed.
660 is_hidden_ = true;
661 show_on_first_paint_ = false;
662 GetBaseWindow()->Hide();
663 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
664 app_delegate_->OnHide();
667 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
668 if (cached_always_on_top_ == always_on_top)
669 return;
671 cached_always_on_top_ = always_on_top;
673 // As a security measure, do not allow fullscreen windows or windows that
674 // overlap the taskbar to be on top. The property will be applied when the
675 // window exits fullscreen and moves away from the taskbar.
676 if (!IsFullscreen() && !IntersectsWithTaskbar())
677 native_app_window_->SetAlwaysOnTop(always_on_top);
679 OnNativeWindowChanged();
682 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
684 void AppWindow::SetInterceptAllKeys(bool want_all_keys) {
685 native_app_window_->SetInterceptAllKeys(want_all_keys);
688 void AppWindow::WindowEventsReady() {
689 can_send_events_ = true;
690 SendOnWindowShownIfShown();
693 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
694 DCHECK(properties);
696 properties->SetBoolean("fullscreen",
697 native_app_window_->IsFullscreenOrPending());
698 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
699 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
700 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
701 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
702 properties->SetBoolean(
703 "alphaEnabled",
704 requested_alpha_enabled_ && native_app_window_->CanHaveAlphaEnabled());
706 // These properties are undocumented and are to enable testing. Alpha is
707 // removed to
708 // make the values easier to check.
709 SkColor transparent_white = ~SK_ColorBLACK;
710 properties->SetInteger(
711 "activeFrameColor",
712 native_app_window_->ActiveFrameColor() & transparent_white);
713 properties->SetInteger(
714 "inactiveFrameColor",
715 native_app_window_->InactiveFrameColor() & transparent_white);
717 gfx::Rect content_bounds = GetClientBounds();
718 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
719 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
720 SetBoundsProperties(content_bounds,
721 content_min_size,
722 content_max_size,
723 "innerBounds",
724 properties);
726 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
727 gfx::Rect frame_bounds = native_app_window_->GetBounds();
728 gfx::Size frame_min_size = SizeConstraints::AddFrameToConstraints(
729 content_min_size, frame_insets);
730 gfx::Size frame_max_size = SizeConstraints::AddFrameToConstraints(
731 content_max_size, frame_insets);
732 SetBoundsProperties(frame_bounds,
733 frame_min_size,
734 frame_max_size,
735 "outerBounds",
736 properties);
739 //------------------------------------------------------------------------------
740 // Private methods
742 void AppWindow::DidDownloadFavicon(
743 int id,
744 int http_status_code,
745 const GURL& image_url,
746 const std::vector<SkBitmap>& bitmaps,
747 const std::vector<gfx::Size>& original_bitmap_sizes) {
748 if (image_url != app_icon_url_ || bitmaps.empty())
749 return;
751 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
752 // whose height >= the preferred size.
753 int largest_index = 0;
754 for (size_t i = 1; i < bitmaps.size(); ++i) {
755 if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
756 break;
757 largest_index = i;
759 const SkBitmap& largest = bitmaps[largest_index];
760 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
763 void AppWindow::OnExtensionIconImageChanged(IconImage* image) {
764 DCHECK_EQ(app_icon_image_.get(), image);
766 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
769 void AppWindow::UpdateExtensionAppIcon() {
770 // Avoid using any previous app icons were being downloaded.
771 image_loader_ptr_factory_.InvalidateWeakPtrs();
773 const Extension* extension = GetExtension();
774 if (!extension)
775 return;
777 gfx::ImageSkia app_default_icon =
778 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
779 IDR_APP_DEFAULT_ICON);
781 app_icon_image_.reset(new IconImage(browser_context(),
782 extension,
783 IconsInfo::GetIcons(extension),
784 app_delegate_->PreferredIconSize(),
785 app_default_icon,
786 this));
788 // Triggers actual image loading with 1x resources. The 2x resource will
789 // be handled by IconImage class when requested.
790 app_icon_image_->image_skia().GetRepresentation(1.0f);
793 void AppWindow::SetNativeWindowFullscreen() {
794 native_app_window_->SetFullscreen(fullscreen_types_);
796 if (cached_always_on_top_)
797 UpdateNativeAlwaysOnTop();
800 bool AppWindow::IntersectsWithTaskbar() const {
801 #if defined(OS_WIN)
802 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
803 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
804 std::vector<gfx::Display> displays = screen->GetAllDisplays();
806 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
807 it != displays.end();
808 ++it) {
809 gfx::Rect taskbar_bounds = it->bounds();
810 taskbar_bounds.Subtract(it->work_area());
811 if (taskbar_bounds.IsEmpty())
812 continue;
814 if (window_bounds.Intersects(taskbar_bounds))
815 return true;
817 #endif
819 return false;
822 void AppWindow::UpdateNativeAlwaysOnTop() {
823 DCHECK(cached_always_on_top_);
824 bool is_on_top = native_app_window_->IsAlwaysOnTop();
825 bool fullscreen = IsFullscreen();
826 bool intersects_taskbar = IntersectsWithTaskbar();
828 if (is_on_top && (fullscreen || intersects_taskbar)) {
829 // When entering fullscreen or overlapping the taskbar, ensure windows are
830 // not always-on-top.
831 native_app_window_->SetAlwaysOnTop(false);
832 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
833 // When exiting fullscreen and moving away from the taskbar, reinstate
834 // always-on-top.
835 native_app_window_->SetAlwaysOnTop(true);
839 void AppWindow::SendOnWindowShownIfShown() {
840 if (!can_send_events_ || !has_been_shown_)
841 return;
843 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
844 ::switches::kTestType)) {
845 app_window_contents_->DispatchWindowShownForTests();
849 void AppWindow::CloseContents(WebContents* contents) {
850 native_app_window_->Close();
853 bool AppWindow::ShouldSuppressDialogs(WebContents* source) {
854 return true;
857 content::ColorChooser* AppWindow::OpenColorChooser(
858 WebContents* web_contents,
859 SkColor initial_color,
860 const std::vector<content::ColorSuggestion>& suggestions) {
861 return app_delegate_->ShowColorChooser(web_contents, initial_color);
864 void AppWindow::RunFileChooser(WebContents* tab,
865 const content::FileChooserParams& params) {
866 if (window_type_is_panel()) {
867 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
868 // dialogs to be unhosted but still close with the owning web contents.
869 // crbug.com/172502.
870 LOG(WARNING) << "File dialog opened by panel.";
871 return;
874 app_delegate_->RunFileChooser(tab, params);
877 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
879 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
880 native_app_window_->SetBounds(pos);
883 void AppWindow::NavigationStateChanged(content::WebContents* source,
884 content::InvalidateTypes changed_flags) {
885 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
886 native_app_window_->UpdateWindowTitle();
887 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
888 native_app_window_->UpdateWindowIcon();
891 void AppWindow::EnterFullscreenModeForTab(content::WebContents* source,
892 const GURL& origin) {
893 ToggleFullscreenModeForTab(source, true);
896 void AppWindow::ExitFullscreenModeForTab(content::WebContents* source) {
897 ToggleFullscreenModeForTab(source, false);
900 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
901 bool enter_fullscreen) {
902 const Extension* extension = GetExtension();
903 if (!extension)
904 return;
906 if (!IsExtensionWithPermissionOrSuggestInConsole(
907 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
908 return;
911 SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
914 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
915 const {
916 return IsHtmlApiFullscreen();
919 blink::WebDisplayMode AppWindow::GetDisplayMode(
920 const content::WebContents* source) const {
921 return IsFullscreen() ? blink::WebDisplayModeFullscreen
922 : blink::WebDisplayModeStandalone;
925 void AppWindow::OnExtensionUnloaded(BrowserContext* browser_context,
926 const Extension* extension,
927 UnloadedExtensionInfo::Reason reason) {
928 if (extension_id_ == extension->id())
929 native_app_window_->Close();
932 void AppWindow::OnExtensionWillBeInstalled(
933 BrowserContext* browser_context,
934 const Extension* extension,
935 bool is_update,
936 bool from_ephemeral,
937 const std::string& old_name) {
938 if (extension->id() == extension_id())
939 native_app_window_->UpdateShelfMenu();
941 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
942 bool blocked) {
943 app_delegate_->SetWebContentsBlocked(web_contents, blocked);
946 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
947 return app_delegate_->IsWebContentsVisible(web_contents);
950 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
951 return native_app_window_.get();
954 void AppWindow::SaveWindowPosition() {
955 if (window_key_.empty())
956 return;
957 if (!native_app_window_)
958 return;
960 AppWindowGeometryCache* cache =
961 AppWindowGeometryCache::Get(browser_context());
963 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
964 gfx::Rect screen_bounds =
965 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
966 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
967 cache->SaveGeometry(
968 extension_id(), window_key_, bounds, screen_bounds, window_state);
971 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
972 const gfx::Rect& cached_bounds,
973 const gfx::Rect& cached_screen_bounds,
974 const gfx::Rect& current_screen_bounds,
975 const gfx::Size& minimum_size,
976 gfx::Rect* bounds) const {
977 *bounds = cached_bounds;
979 // Reposition and resize the bounds if the cached_screen_bounds is different
980 // from the current screen bounds and the current screen bounds doesn't
981 // completely contain the bounds.
982 if (cached_screen_bounds != current_screen_bounds &&
983 !current_screen_bounds.Contains(cached_bounds)) {
984 bounds->set_width(
985 std::max(minimum_size.width(),
986 std::min(bounds->width(), current_screen_bounds.width())));
987 bounds->set_height(
988 std::max(minimum_size.height(),
989 std::min(bounds->height(), current_screen_bounds.height())));
990 bounds->set_x(
991 std::max(current_screen_bounds.x(),
992 std::min(bounds->x(),
993 current_screen_bounds.right() - bounds->width())));
994 bounds->set_y(
995 std::max(current_screen_bounds.y(),
996 std::min(bounds->y(),
997 current_screen_bounds.bottom() - bounds->height())));
1001 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1002 const {
1003 // Ensure width and height are specified.
1004 if (params.content_spec.bounds.width() == 0 &&
1005 params.window_spec.bounds.width() == 0) {
1006 params.content_spec.bounds.set_width(kDefaultWidth);
1008 if (params.content_spec.bounds.height() == 0 &&
1009 params.window_spec.bounds.height() == 0) {
1010 params.content_spec.bounds.set_height(kDefaultHeight);
1013 // If left and top are left undefined, the native app window will center
1014 // the window on the main screen in a platform-defined manner.
1016 // Load cached state if it exists.
1017 if (!params.window_key.empty()) {
1018 AppWindowGeometryCache* cache =
1019 AppWindowGeometryCache::Get(browser_context());
1021 gfx::Rect cached_bounds;
1022 gfx::Rect cached_screen_bounds;
1023 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1024 if (cache->GetGeometry(extension_id(),
1025 params.window_key,
1026 &cached_bounds,
1027 &cached_screen_bounds,
1028 &cached_state)) {
1029 // App window has cached screen bounds, make sure it fits on screen in
1030 // case the screen resolution changed.
1031 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1032 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1033 gfx::Rect current_screen_bounds = display.work_area();
1034 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1035 params.GetWindowMaximumSize(gfx::Insets()));
1036 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1037 cached_screen_bounds,
1038 current_screen_bounds,
1039 constraints.GetMinimumSize(),
1040 &params.window_spec.bounds);
1041 params.state = cached_state;
1043 // Since we are restoring a cached state, reset the content bounds spec to
1044 // ensure it is not used.
1045 params.content_spec.ResetBounds();
1049 return params;
1052 // static
1053 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1054 const std::vector<DraggableRegion>& regions) {
1055 SkRegion* sk_region = new SkRegion;
1056 for (std::vector<DraggableRegion>::const_iterator iter = regions.begin();
1057 iter != regions.end();
1058 ++iter) {
1059 const DraggableRegion& region = *iter;
1060 sk_region->op(
1061 region.bounds.x(),
1062 region.bounds.y(),
1063 region.bounds.right(),
1064 region.bounds.bottom(),
1065 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1067 return sk_region;
1070 } // namespace extensions