Update .DEPS.git
[chromium-blink-merge.git] / apps / app_window.cc
blobd3a752b50a806371af09a9cdc081eb47a6f0372d
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_window_geometry_cache.h"
13 #include "apps/app_window_registry.h"
14 #include "apps/apps_client.h"
15 #include "apps/size_constraints.h"
16 #include "apps/ui/native_app_window.h"
17 #include "apps/ui/web_contents_sizer.h"
18 #include "base/command_line.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/values.h"
22 #include "chrome/browser/chrome_notification_types.h"
23 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
24 #include "chrome/browser/extensions/suggest_permission_util.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "components/web_modal/web_contents_modal_dialog_manager.h"
27 #include "content/public/browser/browser_context.h"
28 #include "content/public/browser/invalidate_type.h"
29 #include "content/public/browser/navigation_entry.h"
30 #include "content/public/browser/notification_details.h"
31 #include "content/public/browser/notification_service.h"
32 #include "content/public/browser/notification_source.h"
33 #include "content/public/browser/notification_types.h"
34 #include "content/public/browser/render_view_host.h"
35 #include "content/public/browser/resource_dispatcher_host.h"
36 #include "content/public/browser/web_contents.h"
37 #include "content/public/common/content_switches.h"
38 #include "content/public/common/media_stream_request.h"
39 #include "extensions/browser/extension_registry.h"
40 #include "extensions/browser/extension_system.h"
41 #include "extensions/browser/extensions_browser_client.h"
42 #include "extensions/browser/process_manager.h"
43 #include "extensions/browser/view_type_utils.h"
44 #include "extensions/common/extension.h"
45 #include "extensions/common/extension_messages.h"
46 #include "extensions/common/manifest_handlers/icons_handler.h"
47 #include "extensions/common/permissions/permissions_data.h"
48 #include "grit/theme_resources.h"
49 #include "third_party/skia/include/core/SkRegion.h"
50 #include "ui/base/resource/resource_bundle.h"
51 #include "ui/gfx/screen.h"
53 #if !defined(OS_MACOSX)
54 #include "apps/pref_names.h"
55 #include "base/prefs/pref_service.h"
56 #endif
58 using content::BrowserContext;
59 using content::ConsoleMessageLevel;
60 using content::WebContents;
61 using extensions::APIPermission;
62 using web_modal::WebContentsModalDialogHost;
63 using web_modal::WebContentsModalDialogManager;
65 namespace apps {
67 namespace {
69 const int kDefaultWidth = 512;
70 const int kDefaultHeight = 384;
72 void SetConstraintProperty(const std::string& name,
73 int value,
74 base::DictionaryValue* bounds_properties) {
75 if (value != SizeConstraints::kUnboundedSize)
76 bounds_properties->SetInteger(name, value);
77 else
78 bounds_properties->Set(name, base::Value::CreateNullValue());
81 void SetBoundsProperties(const gfx::Rect& bounds,
82 const gfx::Size& min_size,
83 const gfx::Size& max_size,
84 const std::string& bounds_name,
85 base::DictionaryValue* window_properties) {
86 scoped_ptr<base::DictionaryValue> bounds_properties(
87 new base::DictionaryValue());
89 bounds_properties->SetInteger("left", bounds.x());
90 bounds_properties->SetInteger("top", bounds.y());
91 bounds_properties->SetInteger("width", bounds.width());
92 bounds_properties->SetInteger("height", bounds.height());
94 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
95 SetConstraintProperty(
96 "minHeight", min_size.height(), bounds_properties.get());
97 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
98 SetConstraintProperty(
99 "maxHeight", max_size.height(), bounds_properties.get());
101 window_properties->Set(bounds_name, bounds_properties.release());
104 // Combines the constraints of the content and window, and returns constraints
105 // for the window.
106 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
107 const gfx::Size& content_constraints,
108 const gfx::Insets& frame_insets) {
109 gfx::Size combined_constraints(window_constraints);
110 if (content_constraints.width() > 0) {
111 combined_constraints.set_width(
112 content_constraints.width() + frame_insets.width());
114 if (content_constraints.height() > 0) {
115 combined_constraints.set_height(
116 content_constraints.height() + frame_insets.height());
118 return combined_constraints;
121 // Combines the constraints of the content and window, and returns constraints
122 // for the content.
123 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
124 const gfx::Size& content_constraints,
125 const gfx::Insets& frame_insets) {
126 gfx::Size combined_constraints(content_constraints);
127 if (window_constraints.width() > 0) {
128 combined_constraints.set_width(
129 std::max(0, window_constraints.width() - frame_insets.width()));
131 if (window_constraints.height() > 0) {
132 combined_constraints.set_height(
133 std::max(0, window_constraints.height() - frame_insets.height()));
135 return combined_constraints;
138 } // namespace
140 // AppWindow::BoundsSpecification
142 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
144 AppWindow::BoundsSpecification::BoundsSpecification()
145 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
147 AppWindow::BoundsSpecification::~BoundsSpecification() {}
149 void AppWindow::BoundsSpecification::ResetBounds() {
150 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
153 // AppWindow::CreateParams
155 AppWindow::CreateParams::CreateParams()
156 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
157 frame(AppWindow::FRAME_CHROME),
158 has_frame_color(false),
159 active_frame_color(SK_ColorBLACK),
160 inactive_frame_color(SK_ColorBLACK),
161 transparent_background(false),
162 creator_process_id(0),
163 state(ui::SHOW_STATE_DEFAULT),
164 hidden(false),
165 resizable(true),
166 focused(true),
167 always_on_top(false) {}
169 AppWindow::CreateParams::~CreateParams() {}
171 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
172 const gfx::Insets& frame_insets) const {
173 // Combine into a single window bounds.
174 gfx::Rect combined_bounds(window_spec.bounds);
175 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
176 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
177 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
178 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
179 if (content_spec.bounds.width() > 0) {
180 combined_bounds.set_width(
181 content_spec.bounds.width() + frame_insets.width());
183 if (content_spec.bounds.height() > 0) {
184 combined_bounds.set_height(
185 content_spec.bounds.height() + frame_insets.height());
188 // Constrain the bounds.
189 SizeConstraints constraints(
190 GetCombinedWindowConstraints(
191 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
192 GetCombinedWindowConstraints(
193 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
194 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
196 return combined_bounds;
199 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
200 const gfx::Insets& frame_insets) const {
201 return GetCombinedContentConstraints(window_spec.minimum_size,
202 content_spec.minimum_size,
203 frame_insets);
206 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
207 const gfx::Insets& frame_insets) const {
208 return GetCombinedContentConstraints(window_spec.maximum_size,
209 content_spec.maximum_size,
210 frame_insets);
213 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
214 const gfx::Insets& frame_insets) const {
215 return GetCombinedWindowConstraints(window_spec.minimum_size,
216 content_spec.minimum_size,
217 frame_insets);
220 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
221 const gfx::Insets& frame_insets) const {
222 return GetCombinedWindowConstraints(window_spec.maximum_size,
223 content_spec.maximum_size,
224 frame_insets);
227 // AppWindow::Delegate
229 AppWindow::Delegate::~Delegate() {}
231 // AppWindow
233 AppWindow::AppWindow(BrowserContext* context,
234 AppDelegate* app_delegate,
235 Delegate* delegate,
236 const extensions::Extension* extension)
237 : browser_context_(context),
238 extension_id_(extension->id()),
239 window_type_(WINDOW_TYPE_DEFAULT),
240 app_delegate_(app_delegate),
241 delegate_(delegate),
242 image_loader_ptr_factory_(this),
243 fullscreen_types_(FULLSCREEN_TYPE_NONE),
244 show_on_first_paint_(false),
245 first_paint_complete_(false),
246 has_been_shown_(false),
247 can_send_events_(false),
248 is_hidden_(false),
249 cached_always_on_top_(false),
250 requested_transparent_background_(false) {
251 extensions::ExtensionsBrowserClient* client =
252 extensions::ExtensionsBrowserClient::Get();
253 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
254 << "Only off the record window may be opened in the guest mode.";
257 void AppWindow::Init(const GURL& url,
258 AppWindowContents* app_window_contents,
259 const CreateParams& params) {
260 // Initialize the render interface and web contents
261 app_window_contents_.reset(app_window_contents);
262 app_window_contents_->Initialize(browser_context(), url);
263 WebContents* web_contents = app_window_contents_->GetWebContents();
264 if (CommandLine::ForCurrentProcess()->HasSwitch(
265 switches::kEnableAppsShowOnFirstPaint)) {
266 content::WebContentsObserver::Observe(web_contents);
268 app_delegate_->InitWebContents(web_contents);
270 WebContentsModalDialogManager::CreateForWebContents(web_contents);
271 // TODO(jamescook): Delegate out this creation.
272 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
273 web_contents);
275 web_contents->SetDelegate(this);
276 WebContentsModalDialogManager::FromWebContents(web_contents)
277 ->SetDelegate(this);
278 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_WINDOW);
280 // Initialize the window
281 CreateParams new_params = LoadDefaults(params);
282 window_type_ = new_params.window_type;
283 window_key_ = new_params.window_key;
285 // Windows cannot be always-on-top in fullscreen mode for security reasons.
286 cached_always_on_top_ = new_params.always_on_top;
287 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
288 new_params.always_on_top = false;
290 requested_transparent_background_ = new_params.transparent_background;
292 native_app_window_.reset(delegate_->CreateNativeAppWindow(this, new_params));
294 popup_manager_.reset(
295 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
296 popup_manager_->RegisterWith(web_contents);
298 // Prevent the browser process from shutting down while this window exists.
299 AppsClient::Get()->IncrementKeepAliveCount();
300 UpdateExtensionAppIcon();
301 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
303 if (new_params.hidden) {
304 // Although the window starts hidden by default, calling Hide() here
305 // notifies observers of the window being hidden.
306 Hide();
307 } else {
308 // Panels are not activated by default.
309 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
310 : SHOW_ACTIVE);
313 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
314 Fullscreen();
315 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
316 Maximize();
317 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
318 Minimize();
320 OnNativeWindowChanged();
322 // When the render view host is changed, the native window needs to know
323 // about it in case it has any setup to do to make the renderer appear
324 // properly. In particular, on Windows, the view's clickthrough region needs
325 // to be set.
326 extensions::ExtensionsBrowserClient* client =
327 extensions::ExtensionsBrowserClient::Get();
328 registrar_.Add(this,
329 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
330 content::Source<content::BrowserContext>(
331 client->GetOriginalContext(browser_context_)));
332 // Close when the browser process is exiting.
333 registrar_.Add(this,
334 chrome::NOTIFICATION_APP_TERMINATING,
335 content::NotificationService::AllSources());
336 // Update the app menu if an ephemeral app becomes installed.
337 registrar_.Add(this,
338 chrome::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
339 content::Source<content::BrowserContext>(
340 client->GetOriginalContext(browser_context_)));
342 app_window_contents_->LoadContents(new_params.creator_process_id);
344 if (CommandLine::ForCurrentProcess()->HasSwitch(
345 switches::kEnableAppsShowOnFirstPaint)) {
346 // We want to show the window only when the content has been painted. For
347 // that to happen, we need to define a size for the content, otherwise the
348 // layout will happen in a 0x0 area.
349 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
350 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
351 initial_bounds.Inset(frame_insets);
352 apps::ResizeWebContents(web_contents, initial_bounds.size());
356 AppWindow::~AppWindow() {
357 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
358 // last window open.
359 registrar_.RemoveAll();
361 // Remove shutdown prevention.
362 AppsClient::Get()->DecrementKeepAliveCount();
365 void AppWindow::RequestMediaAccessPermission(
366 content::WebContents* web_contents,
367 const content::MediaStreamRequest& request,
368 const content::MediaResponseCallback& callback) {
369 const extensions::Extension* extension = GetExtension();
370 if (!extension)
371 return;
373 app_delegate_->RequestMediaAccessPermission(
374 web_contents, request, callback, extension);
377 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
378 const content::OpenURLParams& params) {
379 // Don't allow the current tab to be navigated. It would be nice to map all
380 // anchor tags (even those without target="_blank") to new tabs, but right
381 // now we can't distinguish between those and <meta> refreshes or window.href
382 // navigations, which we don't want to allow.
383 // TOOD(mihaip): Can we check for user gestures instead?
384 WindowOpenDisposition disposition = params.disposition;
385 if (disposition == CURRENT_TAB) {
386 AddMessageToDevToolsConsole(
387 content::CONSOLE_MESSAGE_LEVEL_ERROR,
388 base::StringPrintf(
389 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
390 params.url.spec().c_str()));
391 return NULL;
394 // These dispositions aren't really navigations.
395 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
396 disposition == IGNORE_ACTION) {
397 return NULL;
400 WebContents* contents =
401 app_delegate_->OpenURLFromTab(browser_context_, source, params);
402 if (!contents) {
403 AddMessageToDevToolsConsole(
404 content::CONSOLE_MESSAGE_LEVEL_ERROR,
405 base::StringPrintf(
406 "Can't navigate to \"%s\"; apps do not support navigation.",
407 params.url.spec().c_str()));
410 return contents;
413 void AppWindow::AddNewContents(WebContents* source,
414 WebContents* new_contents,
415 WindowOpenDisposition disposition,
416 const gfx::Rect& initial_pos,
417 bool user_gesture,
418 bool* was_blocked) {
419 DCHECK(new_contents->GetBrowserContext() == browser_context_);
420 app_delegate_->AddNewContents(browser_context_,
421 new_contents,
422 disposition,
423 initial_pos,
424 user_gesture,
425 was_blocked);
428 bool AppWindow::PreHandleKeyboardEvent(
429 content::WebContents* source,
430 const content::NativeWebKeyboardEvent& event,
431 bool* is_keyboard_shortcut) {
432 const extensions::Extension* extension = GetExtension();
433 if (!extension)
434 return false;
436 // Here, we can handle a key event before the content gets it. When we are
437 // fullscreen and it is not forced, we want to allow the user to leave
438 // when ESC is pressed.
439 // However, if the application has the "overrideEscFullscreen" permission, we
440 // should let it override that behavior.
441 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
442 // action is not prevented.
443 // Thus, we should handle the KeyEvent here only if the permission is not set.
444 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
445 !IsForcedFullscreen() &&
446 !extension->permissions_data()->HasAPIPermission(
447 APIPermission::kOverrideEscFullscreen)) {
448 Restore();
449 return true;
452 return false;
455 void AppWindow::HandleKeyboardEvent(
456 WebContents* source,
457 const content::NativeWebKeyboardEvent& event) {
458 // If the window is currently fullscreen and not forced, ESC should leave
459 // fullscreen. If this code is being called for ESC, that means that the
460 // KeyEvent's default behavior was not prevented by the content.
461 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
462 !IsForcedFullscreen()) {
463 Restore();
464 return;
467 native_app_window_->HandleKeyboardEvent(event);
470 void AppWindow::RequestToLockMouse(WebContents* web_contents,
471 bool user_gesture,
472 bool last_unlocked_by_target) {
473 const extensions::Extension* extension = GetExtension();
474 if (!extension)
475 return;
477 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
478 APIPermission::kPointerLock,
479 extension,
480 web_contents->GetRenderViewHost());
482 web_contents->GotResponseToLockMouseRequest(has_permission);
485 bool AppWindow::PreHandleGestureEvent(WebContents* source,
486 const blink::WebGestureEvent& event) {
487 // Disable pinch zooming in app windows.
488 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
489 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
490 event.type == blink::WebGestureEvent::GesturePinchEnd;
493 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
494 first_paint_complete_ = true;
495 if (show_on_first_paint_) {
496 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
497 delayed_show_type_ == SHOW_INACTIVE);
498 Show(delayed_show_type_);
502 void AppWindow::OnNativeClose() {
503 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
504 if (app_window_contents_) {
505 WebContents* web_contents = app_window_contents_->GetWebContents();
506 WebContentsModalDialogManager::FromWebContents(web_contents)
507 ->SetDelegate(NULL);
508 app_window_contents_->NativeWindowClosed();
510 delete this;
513 void AppWindow::OnNativeWindowChanged() {
514 SaveWindowPosition();
516 #if defined(OS_WIN)
517 if (native_app_window_ && cached_always_on_top_ && !IsFullscreen() &&
518 !native_app_window_->IsMaximized() &&
519 !native_app_window_->IsMinimized()) {
520 UpdateNativeAlwaysOnTop();
522 #endif
524 if (app_window_contents_ && native_app_window_)
525 app_window_contents_->NativeWindowChanged(native_app_window_.get());
528 void AppWindow::OnNativeWindowActivated() {
529 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
532 content::WebContents* AppWindow::web_contents() const {
533 return app_window_contents_->GetWebContents();
536 const extensions::Extension* AppWindow::GetExtension() const {
537 return extensions::ExtensionRegistry::Get(browser_context_)
538 ->enabled_extensions()
539 .GetByID(extension_id_);
542 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
544 gfx::NativeWindow AppWindow::GetNativeWindow() {
545 return GetBaseWindow()->GetNativeWindow();
548 gfx::Rect AppWindow::GetClientBounds() const {
549 gfx::Rect bounds = native_app_window_->GetBounds();
550 bounds.Inset(native_app_window_->GetFrameInsets());
551 return bounds;
554 base::string16 AppWindow::GetTitle() const {
555 const extensions::Extension* extension = GetExtension();
556 if (!extension)
557 return base::string16();
559 // WebContents::GetTitle() will return the page's URL if there's no <title>
560 // specified. However, we'd prefer to show the name of the extension in that
561 // case, so we directly inspect the NavigationEntry's title.
562 base::string16 title;
563 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
564 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
565 title = base::UTF8ToUTF16(extension->name());
566 } else {
567 title = web_contents()->GetTitle();
569 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
570 return title;
573 void AppWindow::SetAppIconUrl(const GURL& url) {
574 // If the same url is being used for the badge, ignore it.
575 if (url == badge_icon_url_)
576 return;
578 // Avoid using any previous icons that were being downloaded.
579 image_loader_ptr_factory_.InvalidateWeakPtrs();
581 // Reset |app_icon_image_| to abort pending image load (if any).
582 app_icon_image_.reset();
584 app_icon_url_ = url;
585 web_contents()->DownloadImage(
586 url,
587 true, // is a favicon
588 0, // no maximum size
589 base::Bind(&AppWindow::DidDownloadFavicon,
590 image_loader_ptr_factory_.GetWeakPtr()));
593 void AppWindow::SetBadgeIconUrl(const GURL& url) {
594 // Avoid using any previous icons that were being downloaded.
595 image_loader_ptr_factory_.InvalidateWeakPtrs();
597 // Reset |app_icon_image_| to abort pending image load (if any).
598 badge_icon_image_.reset();
600 badge_icon_url_ = url;
601 web_contents()->DownloadImage(
602 url,
603 true, // is a favicon
604 0, // no maximum size
605 base::Bind(&AppWindow::DidDownloadFavicon,
606 image_loader_ptr_factory_.GetWeakPtr()));
609 void AppWindow::ClearBadge() {
610 badge_icon_image_.reset();
611 badge_icon_url_ = GURL();
612 UpdateBadgeIcon(gfx::Image());
615 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
616 native_app_window_->UpdateShape(region.Pass());
619 void AppWindow::UpdateDraggableRegions(
620 const std::vector<extensions::DraggableRegion>& regions) {
621 native_app_window_->UpdateDraggableRegions(regions);
624 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
625 if (image.IsEmpty())
626 return;
627 app_icon_ = image;
628 native_app_window_->UpdateWindowIcon();
629 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
632 void AppWindow::SetFullscreen(FullscreenType type, bool enable) {
633 DCHECK_NE(FULLSCREEN_TYPE_NONE, type);
635 if (enable) {
636 #if !defined(OS_MACOSX)
637 // Do not enter fullscreen mode if disallowed by pref.
638 // TODO(bartfab): Add a test once it becomes possible to simulate a user
639 // gesture. http://crbug.com/174178
640 if (type != FULLSCREEN_TYPE_FORCED) {
641 PrefService* prefs =
642 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
643 browser_context());
644 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
645 return;
647 #endif
648 fullscreen_types_ |= type;
649 } else {
650 fullscreen_types_ &= ~type;
652 SetNativeWindowFullscreen();
655 bool AppWindow::IsFullscreen() const {
656 return fullscreen_types_ != FULLSCREEN_TYPE_NONE;
659 bool AppWindow::IsForcedFullscreen() const {
660 return (fullscreen_types_ & FULLSCREEN_TYPE_FORCED) != 0;
663 bool AppWindow::IsHtmlApiFullscreen() const {
664 return (fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0;
667 void AppWindow::Fullscreen() {
668 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API, true);
671 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
673 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
675 void AppWindow::Restore() {
676 if (IsFullscreen()) {
677 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
678 SetNativeWindowFullscreen();
679 } else {
680 GetBaseWindow()->Restore();
684 void AppWindow::OSFullscreen() {
685 SetFullscreen(FULLSCREEN_TYPE_OS, true);
688 void AppWindow::ForcedFullscreen() {
689 SetFullscreen(FULLSCREEN_TYPE_FORCED, true);
692 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
693 const gfx::Size& max_size) {
694 SizeConstraints constraints(min_size, max_size);
695 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
696 constraints.GetMaximumSize());
698 gfx::Rect bounds = GetClientBounds();
699 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
700 if (bounds.size() != constrained_size) {
701 bounds.set_size(constrained_size);
702 bounds.Inset(-native_app_window_->GetFrameInsets());
703 native_app_window_->SetBounds(bounds);
705 OnNativeWindowChanged();
708 void AppWindow::Show(ShowType show_type) {
709 is_hidden_ = false;
711 if (CommandLine::ForCurrentProcess()->HasSwitch(
712 switches::kEnableAppsShowOnFirstPaint)) {
713 show_on_first_paint_ = true;
715 if (!first_paint_complete_) {
716 delayed_show_type_ = show_type;
717 return;
721 switch (show_type) {
722 case SHOW_ACTIVE:
723 GetBaseWindow()->Show();
724 break;
725 case SHOW_INACTIVE:
726 GetBaseWindow()->ShowInactive();
727 break;
729 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this);
731 has_been_shown_ = true;
732 SendOnWindowShownIfShown();
735 void AppWindow::Hide() {
736 // This is there to prevent race conditions with Hide() being called before
737 // there was a non-empty paint. It should have no effect in a non-racy
738 // scenario where the application is hiding then showing a window: the second
739 // show will not be delayed.
740 is_hidden_ = true;
741 show_on_first_paint_ = false;
742 GetBaseWindow()->Hide();
743 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
746 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
747 if (cached_always_on_top_ == always_on_top)
748 return;
750 cached_always_on_top_ = always_on_top;
752 // As a security measure, do not allow fullscreen windows or windows that
753 // overlap the taskbar to be on top. The property will be applied when the
754 // window exits fullscreen and moves away from the taskbar.
755 if (!IsFullscreen() && !IntersectsWithTaskbar())
756 native_app_window_->SetAlwaysOnTop(always_on_top);
758 OnNativeWindowChanged();
761 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
763 void AppWindow::WindowEventsReady() {
764 can_send_events_ = true;
765 SendOnWindowShownIfShown();
768 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
769 DCHECK(properties);
771 properties->SetBoolean("fullscreen",
772 native_app_window_->IsFullscreenOrPending());
773 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
774 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
775 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
776 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
777 properties->SetBoolean("alphaEnabled",
778 requested_transparent_background_ &&
779 native_app_window_->CanHaveAlphaEnabled());
781 // These properties are undocumented and are to enable testing. Alpha is
782 // removed to
783 // make the values easier to check.
784 SkColor transparent_white = ~SK_ColorBLACK;
785 properties->SetInteger(
786 "activeFrameColor",
787 native_app_window_->ActiveFrameColor() & transparent_white);
788 properties->SetInteger(
789 "inactiveFrameColor",
790 native_app_window_->InactiveFrameColor() & transparent_white);
792 gfx::Rect content_bounds = GetClientBounds();
793 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
794 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
795 SetBoundsProperties(content_bounds,
796 content_min_size,
797 content_max_size,
798 "innerBounds",
799 properties);
801 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
802 gfx::Rect frame_bounds = native_app_window_->GetBounds();
803 gfx::Size frame_min_size =
804 SizeConstraints::AddFrameToConstraints(content_min_size, frame_insets);
805 gfx::Size frame_max_size =
806 SizeConstraints::AddFrameToConstraints(content_max_size, frame_insets);
807 SetBoundsProperties(frame_bounds,
808 frame_min_size,
809 frame_max_size,
810 "outerBounds",
811 properties);
814 //------------------------------------------------------------------------------
815 // Private methods
817 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
818 badge_icon_ = image;
819 native_app_window_->UpdateBadgeIcon();
822 void AppWindow::DidDownloadFavicon(
823 int id,
824 int http_status_code,
825 const GURL& image_url,
826 const std::vector<SkBitmap>& bitmaps,
827 const std::vector<gfx::Size>& original_bitmap_sizes) {
828 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
829 bitmaps.empty()) {
830 return;
833 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
834 // whose height >= the preferred size.
835 int largest_index = 0;
836 for (size_t i = 1; i < bitmaps.size(); ++i) {
837 if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
838 break;
839 largest_index = i;
841 const SkBitmap& largest = bitmaps[largest_index];
842 if (image_url == app_icon_url_) {
843 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
844 return;
847 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
850 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
851 DCHECK_EQ(app_icon_image_.get(), image);
853 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
856 void AppWindow::UpdateExtensionAppIcon() {
857 // Avoid using any previous app icons were being downloaded.
858 image_loader_ptr_factory_.InvalidateWeakPtrs();
860 const gfx::ImageSkia& default_icon =
861 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
862 IDR_APP_DEFAULT_ICON);
864 const extensions::Extension* extension = GetExtension();
865 if (!extension)
866 return;
868 app_icon_image_.reset(
869 new extensions::IconImage(browser_context(),
870 extension,
871 extensions::IconsInfo::GetIcons(extension),
872 app_delegate_->PreferredIconSize(),
873 default_icon,
874 this));
876 // Triggers actual image loading with 1x resources. The 2x resource will
877 // be handled by IconImage class when requested.
878 app_icon_image_->image_skia().GetRepresentation(1.0f);
881 void AppWindow::SetNativeWindowFullscreen() {
882 native_app_window_->SetFullscreen(fullscreen_types_);
884 if (cached_always_on_top_)
885 UpdateNativeAlwaysOnTop();
888 bool AppWindow::IntersectsWithTaskbar() const {
889 #if defined(OS_WIN)
890 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
891 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
892 std::vector<gfx::Display> displays = screen->GetAllDisplays();
894 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
895 it != displays.end();
896 ++it) {
897 gfx::Rect taskbar_bounds = it->bounds();
898 taskbar_bounds.Subtract(it->work_area());
899 if (taskbar_bounds.IsEmpty())
900 continue;
902 if (window_bounds.Intersects(taskbar_bounds))
903 return true;
905 #endif
907 return false;
910 void AppWindow::UpdateNativeAlwaysOnTop() {
911 DCHECK(cached_always_on_top_);
912 bool is_on_top = native_app_window_->IsAlwaysOnTop();
913 bool fullscreen = IsFullscreen();
914 bool intersects_taskbar = IntersectsWithTaskbar();
916 if (is_on_top && (fullscreen || intersects_taskbar)) {
917 // When entering fullscreen or overlapping the taskbar, ensure windows are
918 // not always-on-top.
919 native_app_window_->SetAlwaysOnTop(false);
920 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
921 // When exiting fullscreen and moving away from the taskbar, reinstate
922 // always-on-top.
923 native_app_window_->SetAlwaysOnTop(true);
927 void AppWindow::SendOnWindowShownIfShown() {
928 if (!can_send_events_ || !has_been_shown_)
929 return;
931 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType)) {
932 app_window_contents_->DispatchWindowShownForTests();
936 void AppWindow::CloseContents(WebContents* contents) {
937 native_app_window_->Close();
940 bool AppWindow::ShouldSuppressDialogs() { return true; }
942 content::ColorChooser* AppWindow::OpenColorChooser(
943 WebContents* web_contents,
944 SkColor initial_color,
945 const std::vector<content::ColorSuggestion>& suggestions) {
946 return app_delegate_->ShowColorChooser(web_contents, initial_color);
949 void AppWindow::RunFileChooser(WebContents* tab,
950 const content::FileChooserParams& params) {
951 if (window_type_is_panel()) {
952 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
953 // dialogs to be unhosted but still close with the owning web contents.
954 // crbug.com/172502.
955 LOG(WARNING) << "File dialog opened by panel.";
956 return;
959 app_delegate_->RunFileChooser(tab, params);
962 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
964 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
965 native_app_window_->SetBounds(pos);
968 void AppWindow::NavigationStateChanged(const content::WebContents* source,
969 unsigned changed_flags) {
970 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
971 native_app_window_->UpdateWindowTitle();
972 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
973 native_app_window_->UpdateWindowIcon();
976 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
977 bool enter_fullscreen) {
978 const extensions::Extension* extension = GetExtension();
979 if (!extension)
980 return;
982 if (!IsExtensionWithPermissionOrSuggestInConsole(
983 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
984 return;
987 SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
990 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
991 const {
992 return IsHtmlApiFullscreen();
995 void AppWindow::Observe(int type,
996 const content::NotificationSource& source,
997 const content::NotificationDetails& details) {
998 switch (type) {
999 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
1000 const extensions::Extension* unloaded_extension =
1001 content::Details<extensions::UnloadedExtensionInfo>(details)
1002 ->extension;
1003 if (extension_id_ == unloaded_extension->id())
1004 native_app_window_->Close();
1005 break;
1007 case chrome::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
1008 const extensions::Extension* installed_extension =
1009 content::Details<const extensions::InstalledExtensionInfo>(details)
1010 ->extension;
1011 DCHECK(installed_extension);
1012 if (installed_extension->id() == extension_id())
1013 native_app_window_->UpdateShelfMenu();
1014 break;
1016 case chrome::NOTIFICATION_APP_TERMINATING:
1017 native_app_window_->Close();
1018 break;
1019 default:
1020 NOTREACHED() << "Received unexpected notification";
1024 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
1025 bool blocked) {
1026 app_delegate_->SetWebContentsBlocked(web_contents, blocked);
1029 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
1030 return app_delegate_->IsWebContentsVisible(web_contents);
1033 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
1034 return native_app_window_.get();
1037 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
1038 const std::string& message) {
1039 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
1040 rvh->Send(new ExtensionMsg_AddMessageToConsole(
1041 rvh->GetRoutingID(), level, message));
1044 void AppWindow::SaveWindowPosition() {
1045 if (window_key_.empty())
1046 return;
1047 if (!native_app_window_)
1048 return;
1050 AppWindowGeometryCache* cache =
1051 AppWindowGeometryCache::Get(browser_context());
1053 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
1054 gfx::Rect screen_bounds =
1055 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
1056 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1057 cache->SaveGeometry(
1058 extension_id(), window_key_, bounds, screen_bounds, window_state);
1061 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1062 const gfx::Rect& cached_bounds,
1063 const gfx::Rect& cached_screen_bounds,
1064 const gfx::Rect& current_screen_bounds,
1065 const gfx::Size& minimum_size,
1066 gfx::Rect* bounds) const {
1067 *bounds = cached_bounds;
1069 // Reposition and resize the bounds if the cached_screen_bounds is different
1070 // from the current screen bounds and the current screen bounds doesn't
1071 // completely contain the bounds.
1072 if (cached_screen_bounds != current_screen_bounds &&
1073 !current_screen_bounds.Contains(cached_bounds)) {
1074 bounds->set_width(
1075 std::max(minimum_size.width(),
1076 std::min(bounds->width(), current_screen_bounds.width())));
1077 bounds->set_height(
1078 std::max(minimum_size.height(),
1079 std::min(bounds->height(), current_screen_bounds.height())));
1080 bounds->set_x(
1081 std::max(current_screen_bounds.x(),
1082 std::min(bounds->x(),
1083 current_screen_bounds.right() - bounds->width())));
1084 bounds->set_y(
1085 std::max(current_screen_bounds.y(),
1086 std::min(bounds->y(),
1087 current_screen_bounds.bottom() - bounds->height())));
1091 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1092 const {
1093 // Ensure width and height are specified.
1094 if (params.content_spec.bounds.width() == 0 &&
1095 params.window_spec.bounds.width() == 0) {
1096 params.content_spec.bounds.set_width(kDefaultWidth);
1098 if (params.content_spec.bounds.height() == 0 &&
1099 params.window_spec.bounds.height() == 0) {
1100 params.content_spec.bounds.set_height(kDefaultHeight);
1103 // If left and top are left undefined, the native app window will center
1104 // the window on the main screen in a platform-defined manner.
1106 // Load cached state if it exists.
1107 if (!params.window_key.empty()) {
1108 AppWindowGeometryCache* cache =
1109 AppWindowGeometryCache::Get(browser_context());
1111 gfx::Rect cached_bounds;
1112 gfx::Rect cached_screen_bounds;
1113 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1114 if (cache->GetGeometry(extension_id(),
1115 params.window_key,
1116 &cached_bounds,
1117 &cached_screen_bounds,
1118 &cached_state)) {
1119 // App window has cached screen bounds, make sure it fits on screen in
1120 // case the screen resolution changed.
1121 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1122 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1123 gfx::Rect current_screen_bounds = display.work_area();
1124 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1125 params.GetWindowMaximumSize(gfx::Insets()));
1126 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1127 cached_screen_bounds,
1128 current_screen_bounds,
1129 constraints.GetMinimumSize(),
1130 &params.window_spec.bounds);
1131 params.state = cached_state;
1133 // Since we are restoring a cached state, reset the content bounds spec to
1134 // ensure it is not used.
1135 params.content_spec.ResetBounds();
1139 return params;
1142 // static
1143 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1144 const std::vector<extensions::DraggableRegion>& regions) {
1145 SkRegion* sk_region = new SkRegion;
1146 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
1147 regions.begin();
1148 iter != regions.end();
1149 ++iter) {
1150 const extensions::DraggableRegion& region = *iter;
1151 sk_region->op(
1152 region.bounds.x(),
1153 region.bounds.y(),
1154 region.bounds.right(),
1155 region.bounds.bottom(),
1156 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1158 return sk_region;
1161 } // namespace apps