Add a command line flag to specify the scope to use for the permission request API.
[chromium-blink-merge.git] / apps / app_window.cc
blobeb4f81a2fd7e42a57786a1902ebb162f9f370d46
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "apps/app_window.h"
7 #include <algorithm>
8 #include <string>
9 #include <vector>
11 #include "apps/app_delegate.h"
12 #include "apps/app_web_contents_helper.h"
13 #include "apps/app_window_geometry_cache.h"
14 #include "apps/app_window_registry.h"
15 #include "apps/size_constraints.h"
16 #include "apps/ui/apps_client.h"
17 #include "apps/ui/native_app_window.h"
18 #include "apps/ui/web_contents_sizer.h"
19 #include "base/command_line.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/values.h"
23 #include "chrome/browser/chrome_notification_types.h"
24 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
25 #include "chrome/browser/extensions/suggest_permission_util.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "components/web_modal/web_contents_modal_dialog_manager.h"
28 #include "content/public/browser/browser_context.h"
29 #include "content/public/browser/invalidate_type.h"
30 #include "content/public/browser/navigation_entry.h"
31 #include "content/public/browser/notification_details.h"
32 #include "content/public/browser/notification_service.h"
33 #include "content/public/browser/notification_source.h"
34 #include "content/public/browser/notification_types.h"
35 #include "content/public/browser/render_view_host.h"
36 #include "content/public/browser/resource_dispatcher_host.h"
37 #include "content/public/browser/web_contents.h"
38 #include "content/public/common/content_switches.h"
39 #include "content/public/common/media_stream_request.h"
40 #include "extensions/browser/extension_registry.h"
41 #include "extensions/browser/extension_system.h"
42 #include "extensions/browser/extensions_browser_client.h"
43 #include "extensions/browser/notification_types.h"
44 #include "extensions/browser/process_manager.h"
45 #include "extensions/browser/view_type_utils.h"
46 #include "extensions/common/draggable_region.h"
47 #include "extensions/common/extension.h"
48 #include "extensions/common/manifest_handlers/icons_handler.h"
49 #include "extensions/common/permissions/permissions_data.h"
50 #include "grit/theme_resources.h"
51 #include "third_party/skia/include/core/SkRegion.h"
52 #include "ui/base/resource/resource_bundle.h"
53 #include "ui/gfx/screen.h"
55 #if !defined(OS_MACOSX)
56 #include "apps/pref_names.h"
57 #include "base/prefs/pref_service.h"
58 #endif
60 using content::BrowserContext;
61 using content::ConsoleMessageLevel;
62 using content::WebContents;
63 using extensions::APIPermission;
64 using web_modal::WebContentsModalDialogHost;
65 using web_modal::WebContentsModalDialogManager;
67 namespace apps {
69 namespace {
71 const int kDefaultWidth = 512;
72 const int kDefaultHeight = 384;
74 void SetConstraintProperty(const std::string& name,
75 int value,
76 base::DictionaryValue* bounds_properties) {
77 if (value != SizeConstraints::kUnboundedSize)
78 bounds_properties->SetInteger(name, value);
79 else
80 bounds_properties->Set(name, base::Value::CreateNullValue());
83 void SetBoundsProperties(const gfx::Rect& bounds,
84 const gfx::Size& min_size,
85 const gfx::Size& max_size,
86 const std::string& bounds_name,
87 base::DictionaryValue* window_properties) {
88 scoped_ptr<base::DictionaryValue> bounds_properties(
89 new base::DictionaryValue());
91 bounds_properties->SetInteger("left", bounds.x());
92 bounds_properties->SetInteger("top", bounds.y());
93 bounds_properties->SetInteger("width", bounds.width());
94 bounds_properties->SetInteger("height", bounds.height());
96 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
97 SetConstraintProperty(
98 "minHeight", min_size.height(), bounds_properties.get());
99 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
100 SetConstraintProperty(
101 "maxHeight", max_size.height(), bounds_properties.get());
103 window_properties->Set(bounds_name, bounds_properties.release());
106 // Combines the constraints of the content and window, and returns constraints
107 // for the window.
108 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
109 const gfx::Size& content_constraints,
110 const gfx::Insets& frame_insets) {
111 gfx::Size combined_constraints(window_constraints);
112 if (content_constraints.width() > 0) {
113 combined_constraints.set_width(
114 content_constraints.width() + frame_insets.width());
116 if (content_constraints.height() > 0) {
117 combined_constraints.set_height(
118 content_constraints.height() + frame_insets.height());
120 return combined_constraints;
123 // Combines the constraints of the content and window, and returns constraints
124 // for the content.
125 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
126 const gfx::Size& content_constraints,
127 const gfx::Insets& frame_insets) {
128 gfx::Size combined_constraints(content_constraints);
129 if (window_constraints.width() > 0) {
130 combined_constraints.set_width(
131 std::max(0, window_constraints.width() - frame_insets.width()));
133 if (window_constraints.height() > 0) {
134 combined_constraints.set_height(
135 std::max(0, window_constraints.height() - frame_insets.height()));
137 return combined_constraints;
140 } // namespace
142 // AppWindow::BoundsSpecification
144 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
146 AppWindow::BoundsSpecification::BoundsSpecification()
147 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
149 AppWindow::BoundsSpecification::~BoundsSpecification() {}
151 void AppWindow::BoundsSpecification::ResetBounds() {
152 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
155 // AppWindow::CreateParams
157 AppWindow::CreateParams::CreateParams()
158 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
159 frame(AppWindow::FRAME_CHROME),
160 has_frame_color(false),
161 active_frame_color(SK_ColorBLACK),
162 inactive_frame_color(SK_ColorBLACK),
163 alpha_enabled(false),
164 creator_process_id(0),
165 state(ui::SHOW_STATE_DEFAULT),
166 hidden(false),
167 resizable(true),
168 focused(true),
169 always_on_top(false) {
172 AppWindow::CreateParams::~CreateParams() {}
174 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
175 const gfx::Insets& frame_insets) const {
176 // Combine into a single window bounds.
177 gfx::Rect combined_bounds(window_spec.bounds);
178 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
179 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
180 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
181 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
182 if (content_spec.bounds.width() > 0) {
183 combined_bounds.set_width(
184 content_spec.bounds.width() + frame_insets.width());
186 if (content_spec.bounds.height() > 0) {
187 combined_bounds.set_height(
188 content_spec.bounds.height() + frame_insets.height());
191 // Constrain the bounds.
192 SizeConstraints constraints(
193 GetCombinedWindowConstraints(
194 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
195 GetCombinedWindowConstraints(
196 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
197 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
199 return combined_bounds;
202 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
203 const gfx::Insets& frame_insets) const {
204 return GetCombinedContentConstraints(window_spec.minimum_size,
205 content_spec.minimum_size,
206 frame_insets);
209 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
210 const gfx::Insets& frame_insets) const {
211 return GetCombinedContentConstraints(window_spec.maximum_size,
212 content_spec.maximum_size,
213 frame_insets);
216 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
217 const gfx::Insets& frame_insets) const {
218 return GetCombinedWindowConstraints(window_spec.minimum_size,
219 content_spec.minimum_size,
220 frame_insets);
223 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
224 const gfx::Insets& frame_insets) const {
225 return GetCombinedWindowConstraints(window_spec.maximum_size,
226 content_spec.maximum_size,
227 frame_insets);
230 // AppWindow
232 AppWindow::AppWindow(BrowserContext* context,
233 AppDelegate* app_delegate,
234 const extensions::Extension* extension)
235 : browser_context_(context),
236 extension_id_(extension->id()),
237 window_type_(WINDOW_TYPE_DEFAULT),
238 app_delegate_(app_delegate),
239 image_loader_ptr_factory_(this),
240 fullscreen_types_(FULLSCREEN_TYPE_NONE),
241 show_on_first_paint_(false),
242 first_paint_complete_(false),
243 has_been_shown_(false),
244 can_send_events_(false),
245 is_hidden_(false),
246 cached_always_on_top_(false),
247 requested_alpha_enabled_(false) {
248 extensions::ExtensionsBrowserClient* client =
249 extensions::ExtensionsBrowserClient::Get();
250 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
251 << "Only off the record window may be opened in the guest mode.";
254 void AppWindow::Init(const GURL& url,
255 AppWindowContents* app_window_contents,
256 const CreateParams& params) {
257 // Initialize the render interface and web contents
258 app_window_contents_.reset(app_window_contents);
259 app_window_contents_->Initialize(browser_context(), url);
260 WebContents* web_contents = app_window_contents_->GetWebContents();
261 if (CommandLine::ForCurrentProcess()->HasSwitch(
262 switches::kEnableAppsShowOnFirstPaint)) {
263 content::WebContentsObserver::Observe(web_contents);
265 app_delegate_->InitWebContents(web_contents);
267 WebContentsModalDialogManager::CreateForWebContents(web_contents);
268 // TODO(jamescook): Delegate out this creation.
269 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
270 web_contents);
272 web_contents->SetDelegate(this);
273 WebContentsModalDialogManager::FromWebContents(web_contents)
274 ->SetDelegate(this);
275 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_WINDOW);
277 // Initialize the window
278 CreateParams new_params = LoadDefaults(params);
279 window_type_ = new_params.window_type;
280 window_key_ = new_params.window_key;
282 // Windows cannot be always-on-top in fullscreen mode for security reasons.
283 cached_always_on_top_ = new_params.always_on_top;
284 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
285 new_params.always_on_top = false;
287 requested_alpha_enabled_ = new_params.alpha_enabled;
289 AppsClient* apps_client = AppsClient::Get();
290 native_app_window_.reset(
291 apps_client->CreateNativeAppWindow(this, new_params));
293 helper_.reset(new AppWebContentsHelper(
294 browser_context_, extension_id_, web_contents, app_delegate_.get()));
296 popup_manager_.reset(
297 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
298 popup_manager_->RegisterWith(web_contents);
300 // Prevent the browser process from shutting down while this window exists.
301 apps_client->IncrementKeepAliveCount();
302 UpdateExtensionAppIcon();
303 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
305 if (new_params.hidden) {
306 // Although the window starts hidden by default, calling Hide() here
307 // notifies observers of the window being hidden.
308 Hide();
309 } else {
310 // Panels are not activated by default.
311 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
312 : SHOW_ACTIVE);
315 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
316 Fullscreen();
317 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
318 Maximize();
319 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
320 Minimize();
322 OnNativeWindowChanged();
324 // When the render view host is changed, the native window needs to know
325 // about it in case it has any setup to do to make the renderer appear
326 // properly. In particular, on Windows, the view's clickthrough region needs
327 // to be set.
328 extensions::ExtensionsBrowserClient* client =
329 extensions::ExtensionsBrowserClient::Get();
330 registrar_.Add(this,
331 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
332 content::Source<content::BrowserContext>(
333 client->GetOriginalContext(browser_context_)));
334 // Close when the browser process is exiting.
335 registrar_.Add(this,
336 chrome::NOTIFICATION_APP_TERMINATING,
337 content::NotificationService::AllSources());
338 // Update the app menu if an ephemeral app becomes installed.
339 registrar_.Add(
340 this,
341 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
342 content::Source<content::BrowserContext>(
343 client->GetOriginalContext(browser_context_)));
345 app_window_contents_->LoadContents(new_params.creator_process_id);
347 if (CommandLine::ForCurrentProcess()->HasSwitch(
348 switches::kEnableAppsShowOnFirstPaint)) {
349 // We want to show the window only when the content has been painted. For
350 // that to happen, we need to define a size for the content, otherwise the
351 // layout will happen in a 0x0 area.
352 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
353 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
354 initial_bounds.Inset(frame_insets);
355 apps::ResizeWebContents(web_contents, initial_bounds.size());
359 AppWindow::~AppWindow() {
360 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
361 // last window open.
362 registrar_.RemoveAll();
364 // Remove shutdown prevention.
365 AppsClient::Get()->DecrementKeepAliveCount();
368 void AppWindow::RequestMediaAccessPermission(
369 content::WebContents* web_contents,
370 const content::MediaStreamRequest& request,
371 const content::MediaResponseCallback& callback) {
372 DCHECK_EQ(AppWindow::web_contents(), web_contents);
373 helper_->RequestMediaAccessPermission(request, callback);
376 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
377 const content::OpenURLParams& params) {
378 DCHECK_EQ(web_contents(), source);
379 return helper_->OpenURLFromTab(params);
382 void AppWindow::AddNewContents(WebContents* source,
383 WebContents* new_contents,
384 WindowOpenDisposition disposition,
385 const gfx::Rect& initial_pos,
386 bool user_gesture,
387 bool* was_blocked) {
388 DCHECK(new_contents->GetBrowserContext() == browser_context_);
389 app_delegate_->AddNewContents(browser_context_,
390 new_contents,
391 disposition,
392 initial_pos,
393 user_gesture,
394 was_blocked);
397 bool AppWindow::PreHandleKeyboardEvent(
398 content::WebContents* source,
399 const content::NativeWebKeyboardEvent& event,
400 bool* is_keyboard_shortcut) {
401 const extensions::Extension* extension = GetExtension();
402 if (!extension)
403 return false;
405 // Here, we can handle a key event before the content gets it. When we are
406 // fullscreen and it is not forced, we want to allow the user to leave
407 // when ESC is pressed.
408 // However, if the application has the "overrideEscFullscreen" permission, we
409 // should let it override that behavior.
410 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
411 // action is not prevented.
412 // Thus, we should handle the KeyEvent here only if the permission is not set.
413 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
414 !IsForcedFullscreen() &&
415 !extension->permissions_data()->HasAPIPermission(
416 APIPermission::kOverrideEscFullscreen)) {
417 Restore();
418 return true;
421 return false;
424 void AppWindow::HandleKeyboardEvent(
425 WebContents* source,
426 const content::NativeWebKeyboardEvent& event) {
427 // If the window is currently fullscreen and not forced, ESC should leave
428 // fullscreen. If this code is being called for ESC, that means that the
429 // KeyEvent's default behavior was not prevented by the content.
430 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
431 !IsForcedFullscreen()) {
432 Restore();
433 return;
436 native_app_window_->HandleKeyboardEvent(event);
439 void AppWindow::RequestToLockMouse(WebContents* web_contents,
440 bool user_gesture,
441 bool last_unlocked_by_target) {
442 DCHECK_EQ(AppWindow::web_contents(), web_contents);
443 helper_->RequestToLockMouse();
446 bool AppWindow::PreHandleGestureEvent(WebContents* source,
447 const blink::WebGestureEvent& event) {
448 return AppWebContentsHelper::ShouldSuppressGestureEvent(event);
451 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
452 first_paint_complete_ = true;
453 if (show_on_first_paint_) {
454 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
455 delayed_show_type_ == SHOW_INACTIVE);
456 Show(delayed_show_type_);
460 void AppWindow::OnNativeClose() {
461 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
462 if (app_window_contents_) {
463 WebContents* web_contents = app_window_contents_->GetWebContents();
464 WebContentsModalDialogManager::FromWebContents(web_contents)
465 ->SetDelegate(NULL);
466 app_window_contents_->NativeWindowClosed();
468 delete this;
471 void AppWindow::OnNativeWindowChanged() {
472 SaveWindowPosition();
474 #if defined(OS_WIN)
475 if (native_app_window_ && cached_always_on_top_ && !IsFullscreen() &&
476 !native_app_window_->IsMaximized() &&
477 !native_app_window_->IsMinimized()) {
478 UpdateNativeAlwaysOnTop();
480 #endif
482 if (app_window_contents_ && native_app_window_)
483 app_window_contents_->NativeWindowChanged(native_app_window_.get());
486 void AppWindow::OnNativeWindowActivated() {
487 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
490 content::WebContents* AppWindow::web_contents() const {
491 return app_window_contents_->GetWebContents();
494 const extensions::Extension* AppWindow::GetExtension() const {
495 return extensions::ExtensionRegistry::Get(browser_context_)
496 ->enabled_extensions()
497 .GetByID(extension_id_);
500 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
502 gfx::NativeWindow AppWindow::GetNativeWindow() {
503 return GetBaseWindow()->GetNativeWindow();
506 gfx::Rect AppWindow::GetClientBounds() const {
507 gfx::Rect bounds = native_app_window_->GetBounds();
508 bounds.Inset(native_app_window_->GetFrameInsets());
509 return bounds;
512 base::string16 AppWindow::GetTitle() const {
513 const extensions::Extension* extension = GetExtension();
514 if (!extension)
515 return base::string16();
517 // WebContents::GetTitle() will return the page's URL if there's no <title>
518 // specified. However, we'd prefer to show the name of the extension in that
519 // case, so we directly inspect the NavigationEntry's title.
520 base::string16 title;
521 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
522 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
523 title = base::UTF8ToUTF16(extension->name());
524 } else {
525 title = web_contents()->GetTitle();
527 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
528 return title;
531 void AppWindow::SetAppIconUrl(const GURL& url) {
532 // If the same url is being used for the badge, ignore it.
533 if (url == badge_icon_url_)
534 return;
536 // Avoid using any previous icons that were being downloaded.
537 image_loader_ptr_factory_.InvalidateWeakPtrs();
539 // Reset |app_icon_image_| to abort pending image load (if any).
540 app_icon_image_.reset();
542 app_icon_url_ = url;
543 web_contents()->DownloadImage(
544 url,
545 true, // is a favicon
546 0, // no maximum size
547 base::Bind(&AppWindow::DidDownloadFavicon,
548 image_loader_ptr_factory_.GetWeakPtr()));
551 void AppWindow::SetBadgeIconUrl(const GURL& url) {
552 // Avoid using any previous icons that were being downloaded.
553 image_loader_ptr_factory_.InvalidateWeakPtrs();
555 // Reset |app_icon_image_| to abort pending image load (if any).
556 badge_icon_image_.reset();
558 badge_icon_url_ = url;
559 web_contents()->DownloadImage(
560 url,
561 true, // is a favicon
562 0, // no maximum size
563 base::Bind(&AppWindow::DidDownloadFavicon,
564 image_loader_ptr_factory_.GetWeakPtr()));
567 void AppWindow::ClearBadge() {
568 badge_icon_image_.reset();
569 badge_icon_url_ = GURL();
570 UpdateBadgeIcon(gfx::Image());
573 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
574 native_app_window_->UpdateShape(region.Pass());
577 void AppWindow::UpdateDraggableRegions(
578 const std::vector<extensions::DraggableRegion>& regions) {
579 native_app_window_->UpdateDraggableRegions(regions);
582 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
583 if (image.IsEmpty())
584 return;
585 app_icon_ = image;
586 native_app_window_->UpdateWindowIcon();
587 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
590 void AppWindow::SetFullscreen(FullscreenType type, bool enable) {
591 DCHECK_NE(FULLSCREEN_TYPE_NONE, type);
593 if (enable) {
594 #if !defined(OS_MACOSX)
595 // Do not enter fullscreen mode if disallowed by pref.
596 // TODO(bartfab): Add a test once it becomes possible to simulate a user
597 // gesture. http://crbug.com/174178
598 if (type != FULLSCREEN_TYPE_FORCED) {
599 PrefService* prefs =
600 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
601 browser_context());
602 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
603 return;
605 #endif
606 fullscreen_types_ |= type;
607 } else {
608 fullscreen_types_ &= ~type;
610 SetNativeWindowFullscreen();
613 bool AppWindow::IsFullscreen() const {
614 return fullscreen_types_ != FULLSCREEN_TYPE_NONE;
617 bool AppWindow::IsForcedFullscreen() const {
618 return (fullscreen_types_ & FULLSCREEN_TYPE_FORCED) != 0;
621 bool AppWindow::IsHtmlApiFullscreen() const {
622 return (fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0;
625 void AppWindow::Fullscreen() {
626 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API, true);
629 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
631 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
633 void AppWindow::Restore() {
634 if (IsFullscreen()) {
635 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
636 SetNativeWindowFullscreen();
637 } else {
638 GetBaseWindow()->Restore();
642 void AppWindow::OSFullscreen() {
643 SetFullscreen(FULLSCREEN_TYPE_OS, true);
646 void AppWindow::ForcedFullscreen() {
647 SetFullscreen(FULLSCREEN_TYPE_FORCED, true);
650 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
651 const gfx::Size& max_size) {
652 SizeConstraints constraints(min_size, max_size);
653 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
654 constraints.GetMaximumSize());
656 gfx::Rect bounds = GetClientBounds();
657 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
658 if (bounds.size() != constrained_size) {
659 bounds.set_size(constrained_size);
660 bounds.Inset(-native_app_window_->GetFrameInsets());
661 native_app_window_->SetBounds(bounds);
663 OnNativeWindowChanged();
666 void AppWindow::Show(ShowType show_type) {
667 is_hidden_ = false;
669 if (CommandLine::ForCurrentProcess()->HasSwitch(
670 switches::kEnableAppsShowOnFirstPaint)) {
671 show_on_first_paint_ = true;
673 if (!first_paint_complete_) {
674 delayed_show_type_ = show_type;
675 return;
679 switch (show_type) {
680 case SHOW_ACTIVE:
681 GetBaseWindow()->Show();
682 break;
683 case SHOW_INACTIVE:
684 GetBaseWindow()->ShowInactive();
685 break;
687 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this);
689 has_been_shown_ = true;
690 SendOnWindowShownIfShown();
693 void AppWindow::Hide() {
694 // This is there to prevent race conditions with Hide() being called before
695 // there was a non-empty paint. It should have no effect in a non-racy
696 // scenario where the application is hiding then showing a window: the second
697 // show will not be delayed.
698 is_hidden_ = true;
699 show_on_first_paint_ = false;
700 GetBaseWindow()->Hide();
701 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
704 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
705 if (cached_always_on_top_ == always_on_top)
706 return;
708 cached_always_on_top_ = always_on_top;
710 // As a security measure, do not allow fullscreen windows or windows that
711 // overlap the taskbar to be on top. The property will be applied when the
712 // window exits fullscreen and moves away from the taskbar.
713 if (!IsFullscreen() && !IntersectsWithTaskbar())
714 native_app_window_->SetAlwaysOnTop(always_on_top);
716 OnNativeWindowChanged();
719 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
721 void AppWindow::WindowEventsReady() {
722 can_send_events_ = true;
723 SendOnWindowShownIfShown();
726 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
727 DCHECK(properties);
729 properties->SetBoolean("fullscreen",
730 native_app_window_->IsFullscreenOrPending());
731 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
732 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
733 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
734 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
735 properties->SetBoolean(
736 "alphaEnabled",
737 requested_alpha_enabled_ && native_app_window_->CanHaveAlphaEnabled());
739 // These properties are undocumented and are to enable testing. Alpha is
740 // removed to
741 // make the values easier to check.
742 SkColor transparent_white = ~SK_ColorBLACK;
743 properties->SetInteger(
744 "activeFrameColor",
745 native_app_window_->ActiveFrameColor() & transparent_white);
746 properties->SetInteger(
747 "inactiveFrameColor",
748 native_app_window_->InactiveFrameColor() & transparent_white);
750 gfx::Rect content_bounds = GetClientBounds();
751 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
752 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
753 SetBoundsProperties(content_bounds,
754 content_min_size,
755 content_max_size,
756 "innerBounds",
757 properties);
759 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
760 gfx::Rect frame_bounds = native_app_window_->GetBounds();
761 gfx::Size frame_min_size =
762 SizeConstraints::AddFrameToConstraints(content_min_size, frame_insets);
763 gfx::Size frame_max_size =
764 SizeConstraints::AddFrameToConstraints(content_max_size, frame_insets);
765 SetBoundsProperties(frame_bounds,
766 frame_min_size,
767 frame_max_size,
768 "outerBounds",
769 properties);
772 //------------------------------------------------------------------------------
773 // Private methods
775 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
776 badge_icon_ = image;
777 native_app_window_->UpdateBadgeIcon();
780 void AppWindow::DidDownloadFavicon(
781 int id,
782 int http_status_code,
783 const GURL& image_url,
784 const std::vector<SkBitmap>& bitmaps,
785 const std::vector<gfx::Size>& original_bitmap_sizes) {
786 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
787 bitmaps.empty()) {
788 return;
791 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
792 // whose height >= the preferred size.
793 int largest_index = 0;
794 for (size_t i = 1; i < bitmaps.size(); ++i) {
795 if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
796 break;
797 largest_index = i;
799 const SkBitmap& largest = bitmaps[largest_index];
800 if (image_url == app_icon_url_) {
801 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
802 return;
805 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
808 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
809 DCHECK_EQ(app_icon_image_.get(), image);
811 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
814 void AppWindow::UpdateExtensionAppIcon() {
815 // Avoid using any previous app icons were being downloaded.
816 image_loader_ptr_factory_.InvalidateWeakPtrs();
818 const gfx::ImageSkia& default_icon =
819 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
820 IDR_APP_DEFAULT_ICON);
822 const extensions::Extension* extension = GetExtension();
823 if (!extension)
824 return;
826 app_icon_image_.reset(
827 new extensions::IconImage(browser_context(),
828 extension,
829 extensions::IconsInfo::GetIcons(extension),
830 app_delegate_->PreferredIconSize(),
831 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 (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType)) {
890 app_window_contents_->DispatchWindowShownForTests();
894 void AppWindow::CloseContents(WebContents* contents) {
895 native_app_window_->Close();
898 bool AppWindow::ShouldSuppressDialogs() { return true; }
900 content::ColorChooser* AppWindow::OpenColorChooser(
901 WebContents* web_contents,
902 SkColor initial_color,
903 const std::vector<content::ColorSuggestion>& suggestions) {
904 return app_delegate_->ShowColorChooser(web_contents, initial_color);
907 void AppWindow::RunFileChooser(WebContents* tab,
908 const content::FileChooserParams& params) {
909 if (window_type_is_panel()) {
910 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
911 // dialogs to be unhosted but still close with the owning web contents.
912 // crbug.com/172502.
913 LOG(WARNING) << "File dialog opened by panel.";
914 return;
917 app_delegate_->RunFileChooser(tab, params);
920 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
922 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
923 native_app_window_->SetBounds(pos);
926 void AppWindow::NavigationStateChanged(const content::WebContents* source,
927 content::InvalidateTypes changed_flags) {
928 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
929 native_app_window_->UpdateWindowTitle();
930 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
931 native_app_window_->UpdateWindowIcon();
934 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
935 bool enter_fullscreen) {
936 const extensions::Extension* extension = GetExtension();
937 if (!extension)
938 return;
940 if (!IsExtensionWithPermissionOrSuggestInConsole(
941 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
942 return;
945 SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
948 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
949 const {
950 return IsHtmlApiFullscreen();
953 void AppWindow::Observe(int type,
954 const content::NotificationSource& source,
955 const content::NotificationDetails& details) {
956 switch (type) {
957 case extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
958 const extensions::Extension* unloaded_extension =
959 content::Details<extensions::UnloadedExtensionInfo>(details)
960 ->extension;
961 if (extension_id_ == unloaded_extension->id())
962 native_app_window_->Close();
963 break;
965 case extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
966 const extensions::Extension* installed_extension =
967 content::Details<const extensions::InstalledExtensionInfo>(details)
968 ->extension;
969 DCHECK(installed_extension);
970 if (installed_extension->id() == extension_id())
971 native_app_window_->UpdateShelfMenu();
972 break;
974 case chrome::NOTIFICATION_APP_TERMINATING:
975 native_app_window_->Close();
976 break;
977 default:
978 NOTREACHED() << "Received unexpected notification";
982 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
983 bool blocked) {
984 app_delegate_->SetWebContentsBlocked(web_contents, blocked);
987 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
988 return app_delegate_->IsWebContentsVisible(web_contents);
991 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
992 return native_app_window_.get();
995 void AppWindow::SaveWindowPosition() {
996 if (window_key_.empty())
997 return;
998 if (!native_app_window_)
999 return;
1001 AppWindowGeometryCache* cache =
1002 AppWindowGeometryCache::Get(browser_context());
1004 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
1005 gfx::Rect screen_bounds =
1006 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
1007 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1008 cache->SaveGeometry(
1009 extension_id(), window_key_, bounds, screen_bounds, window_state);
1012 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1013 const gfx::Rect& cached_bounds,
1014 const gfx::Rect& cached_screen_bounds,
1015 const gfx::Rect& current_screen_bounds,
1016 const gfx::Size& minimum_size,
1017 gfx::Rect* bounds) const {
1018 *bounds = cached_bounds;
1020 // Reposition and resize the bounds if the cached_screen_bounds is different
1021 // from the current screen bounds and the current screen bounds doesn't
1022 // completely contain the bounds.
1023 if (cached_screen_bounds != current_screen_bounds &&
1024 !current_screen_bounds.Contains(cached_bounds)) {
1025 bounds->set_width(
1026 std::max(minimum_size.width(),
1027 std::min(bounds->width(), current_screen_bounds.width())));
1028 bounds->set_height(
1029 std::max(minimum_size.height(),
1030 std::min(bounds->height(), current_screen_bounds.height())));
1031 bounds->set_x(
1032 std::max(current_screen_bounds.x(),
1033 std::min(bounds->x(),
1034 current_screen_bounds.right() - bounds->width())));
1035 bounds->set_y(
1036 std::max(current_screen_bounds.y(),
1037 std::min(bounds->y(),
1038 current_screen_bounds.bottom() - bounds->height())));
1042 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1043 const {
1044 // Ensure width and height are specified.
1045 if (params.content_spec.bounds.width() == 0 &&
1046 params.window_spec.bounds.width() == 0) {
1047 params.content_spec.bounds.set_width(kDefaultWidth);
1049 if (params.content_spec.bounds.height() == 0 &&
1050 params.window_spec.bounds.height() == 0) {
1051 params.content_spec.bounds.set_height(kDefaultHeight);
1054 // If left and top are left undefined, the native app window will center
1055 // the window on the main screen in a platform-defined manner.
1057 // Load cached state if it exists.
1058 if (!params.window_key.empty()) {
1059 AppWindowGeometryCache* cache =
1060 AppWindowGeometryCache::Get(browser_context());
1062 gfx::Rect cached_bounds;
1063 gfx::Rect cached_screen_bounds;
1064 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1065 if (cache->GetGeometry(extension_id(),
1066 params.window_key,
1067 &cached_bounds,
1068 &cached_screen_bounds,
1069 &cached_state)) {
1070 // App window has cached screen bounds, make sure it fits on screen in
1071 // case the screen resolution changed.
1072 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1073 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1074 gfx::Rect current_screen_bounds = display.work_area();
1075 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1076 params.GetWindowMaximumSize(gfx::Insets()));
1077 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1078 cached_screen_bounds,
1079 current_screen_bounds,
1080 constraints.GetMinimumSize(),
1081 &params.window_spec.bounds);
1082 params.state = cached_state;
1084 // Since we are restoring a cached state, reset the content bounds spec to
1085 // ensure it is not used.
1086 params.content_spec.ResetBounds();
1090 return params;
1093 // static
1094 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1095 const std::vector<extensions::DraggableRegion>& regions) {
1096 SkRegion* sk_region = new SkRegion;
1097 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
1098 regions.begin();
1099 iter != regions.end();
1100 ++iter) {
1101 const extensions::DraggableRegion& region = *iter;
1102 sk_region->op(
1103 region.bounds.x(),
1104 region.bounds.y(),
1105 region.bounds.right(),
1106 region.bounds.bottom(),
1107 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1109 return sk_region;
1112 } // namespace apps