[SyncFS] Build indexes from FileTracker entries on disk.
[chromium-blink-merge.git] / apps / app_window.cc
blobdb1f54399664886a0bbc753be79565fe9b04cfbc
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>
9 #include "apps/app_window_geometry_cache.h"
10 #include "apps/app_window_registry.h"
11 #include "apps/apps_client.h"
12 #include "apps/size_constraints.h"
13 #include "apps/ui/native_app_window.h"
14 #include "apps/ui/web_contents_sizer.h"
15 #include "base/command_line.h"
16 #include "base/strings/string_util.h"
17 #include "base/strings/utf_string_conversions.h"
18 #include "base/values.h"
19 #include "chrome/browser/chrome_notification_types.h"
20 #include "chrome/browser/extensions/chrome_extension_web_contents_observer.h"
21 #include "chrome/browser/extensions/suggest_permission_util.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "components/web_modal/web_contents_modal_dialog_manager.h"
24 #include "content/public/browser/browser_context.h"
25 #include "content/public/browser/invalidate_type.h"
26 #include "content/public/browser/navigation_entry.h"
27 #include "content/public/browser/notification_details.h"
28 #include "content/public/browser/notification_service.h"
29 #include "content/public/browser/notification_source.h"
30 #include "content/public/browser/notification_types.h"
31 #include "content/public/browser/render_view_host.h"
32 #include "content/public/browser/resource_dispatcher_host.h"
33 #include "content/public/browser/web_contents.h"
34 #include "content/public/common/content_switches.h"
35 #include "content/public/common/media_stream_request.h"
36 #include "extensions/browser/extension_registry.h"
37 #include "extensions/browser/extension_system.h"
38 #include "extensions/browser/extensions_browser_client.h"
39 #include "extensions/browser/process_manager.h"
40 #include "extensions/browser/view_type_utils.h"
41 #include "extensions/common/extension.h"
42 #include "extensions/common/extension_messages.h"
43 #include "extensions/common/manifest_handlers/icons_handler.h"
44 #include "extensions/common/permissions/permissions_data.h"
45 #include "grit/theme_resources.h"
46 #include "third_party/skia/include/core/SkRegion.h"
47 #include "ui/base/resource/resource_bundle.h"
48 #include "ui/gfx/screen.h"
50 #if !defined(OS_MACOSX)
51 #include "apps/pref_names.h"
52 #include "base/prefs/pref_service.h"
53 #endif
55 using content::BrowserContext;
56 using content::ConsoleMessageLevel;
57 using content::WebContents;
58 using extensions::APIPermission;
59 using web_modal::WebContentsModalDialogHost;
60 using web_modal::WebContentsModalDialogManager;
62 namespace apps {
64 namespace {
66 const int kDefaultWidth = 512;
67 const int kDefaultHeight = 384;
69 bool IsFullscreen(int fullscreen_types) {
70 return fullscreen_types != apps::AppWindow::FULLSCREEN_TYPE_NONE;
73 void SetConstraintProperty(const std::string& name,
74 int value,
75 base::DictionaryValue* bounds_properties) {
76 if (value != SizeConstraints::kUnboundedSize)
77 bounds_properties->SetInteger(name, value);
78 else
79 bounds_properties->Set(name, base::Value::CreateNullValue());
82 void SetBoundsProperties(const gfx::Rect& bounds,
83 const gfx::Size& min_size,
84 const gfx::Size& max_size,
85 const std::string& bounds_name,
86 base::DictionaryValue* window_properties) {
87 scoped_ptr<base::DictionaryValue> bounds_properties(
88 new base::DictionaryValue());
90 bounds_properties->SetInteger("left", bounds.x());
91 bounds_properties->SetInteger("top", bounds.y());
92 bounds_properties->SetInteger("width", bounds.width());
93 bounds_properties->SetInteger("height", bounds.height());
95 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
96 SetConstraintProperty(
97 "minHeight", min_size.height(), bounds_properties.get());
98 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
99 SetConstraintProperty(
100 "maxHeight", max_size.height(), bounds_properties.get());
102 window_properties->Set(bounds_name, bounds_properties.release());
105 // Combines the constraints of the content and window, and returns constraints
106 // for the window.
107 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
108 const gfx::Size& content_constraints,
109 const gfx::Insets& frame_insets) {
110 gfx::Size combined_constraints(window_constraints);
111 if (content_constraints.width() > 0) {
112 combined_constraints.set_width(
113 content_constraints.width() + frame_insets.width());
115 if (content_constraints.height() > 0) {
116 combined_constraints.set_height(
117 content_constraints.height() + frame_insets.height());
119 return combined_constraints;
122 // Combines the constraints of the content and window, and returns constraints
123 // for the content.
124 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
125 const gfx::Size& content_constraints,
126 const gfx::Insets& frame_insets) {
127 gfx::Size combined_constraints(content_constraints);
128 if (window_constraints.width() > 0) {
129 combined_constraints.set_width(
130 std::max(0, window_constraints.width() - frame_insets.width()));
132 if (window_constraints.height() > 0) {
133 combined_constraints.set_height(
134 std::max(0, window_constraints.height() - frame_insets.height()));
136 return combined_constraints;
139 } // namespace
141 // AppWindow::BoundsSpecification
143 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
145 AppWindow::BoundsSpecification::BoundsSpecification()
146 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
148 AppWindow::BoundsSpecification::~BoundsSpecification() {}
150 void AppWindow::BoundsSpecification::ResetBounds() {
151 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
154 // AppWindow::CreateParams
156 AppWindow::CreateParams::CreateParams()
157 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
158 frame(AppWindow::FRAME_CHROME),
159 has_frame_color(false),
160 active_frame_color(SK_ColorBLACK),
161 inactive_frame_color(SK_ColorBLACK),
162 transparent_background(false),
163 creator_process_id(0),
164 state(ui::SHOW_STATE_DEFAULT),
165 hidden(false),
166 resizable(true),
167 focused(true),
168 always_on_top(false) {}
170 AppWindow::CreateParams::~CreateParams() {}
172 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
173 const gfx::Insets& frame_insets) const {
174 // Combine into a single window bounds.
175 gfx::Rect combined_bounds(window_spec.bounds);
176 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
177 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
178 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
179 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
180 if (content_spec.bounds.width() > 0) {
181 combined_bounds.set_width(
182 content_spec.bounds.width() + frame_insets.width());
184 if (content_spec.bounds.height() > 0) {
185 combined_bounds.set_height(
186 content_spec.bounds.height() + frame_insets.height());
189 // Constrain the bounds.
190 SizeConstraints constraints(
191 GetCombinedWindowConstraints(
192 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
193 GetCombinedWindowConstraints(
194 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
195 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
197 return combined_bounds;
200 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
201 const gfx::Insets& frame_insets) const {
202 return GetCombinedContentConstraints(window_spec.minimum_size,
203 content_spec.minimum_size,
204 frame_insets);
207 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
208 const gfx::Insets& frame_insets) const {
209 return GetCombinedContentConstraints(window_spec.maximum_size,
210 content_spec.maximum_size,
211 frame_insets);
214 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
215 const gfx::Insets& frame_insets) const {
216 return GetCombinedWindowConstraints(window_spec.minimum_size,
217 content_spec.minimum_size,
218 frame_insets);
221 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
222 const gfx::Insets& frame_insets) const {
223 return GetCombinedWindowConstraints(window_spec.maximum_size,
224 content_spec.maximum_size,
225 frame_insets);
228 // AppWindow::Delegate
230 AppWindow::Delegate::~Delegate() {}
232 // AppWindow
234 AppWindow::AppWindow(BrowserContext* context,
235 Delegate* delegate,
236 const extensions::Extension* extension)
237 : browser_context_(context),
238 extension_id_(extension->id()),
239 window_type_(WINDOW_TYPE_DEFAULT),
240 delegate_(delegate),
241 image_loader_ptr_factory_(this),
242 fullscreen_types_(FULLSCREEN_TYPE_NONE),
243 show_on_first_paint_(false),
244 first_paint_complete_(false),
245 has_been_shown_(false),
246 can_send_events_(false),
247 is_hidden_(false),
248 cached_always_on_top_(false) {
249 extensions::ExtensionsBrowserClient* client =
250 extensions::ExtensionsBrowserClient::Get();
251 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
252 << "Only off the record window may be opened in the guest mode.";
255 void AppWindow::Init(const GURL& url,
256 AppWindowContents* app_window_contents,
257 const CreateParams& params) {
258 // Initialize the render interface and web contents
259 app_window_contents_.reset(app_window_contents);
260 app_window_contents_->Initialize(browser_context(), url);
261 WebContents* web_contents = app_window_contents_->GetWebContents();
262 if (CommandLine::ForCurrentProcess()->HasSwitch(
263 switches::kEnableAppsShowOnFirstPaint)) {
264 content::WebContentsObserver::Observe(web_contents);
266 delegate_->InitWebContents(web_contents);
268 WebContentsModalDialogManager::CreateForWebContents(web_contents);
269 // TODO(jamescook): Delegate out this creation.
270 extensions::ChromeExtensionWebContentsObserver::CreateForWebContents(
271 web_contents);
273 web_contents->SetDelegate(this);
274 WebContentsModalDialogManager::FromWebContents(web_contents)
275 ->SetDelegate(this);
276 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_WINDOW);
278 // Initialize the window
279 CreateParams new_params = LoadDefaults(params);
280 window_type_ = new_params.window_type;
281 window_key_ = new_params.window_key;
283 // Windows cannot be always-on-top in fullscreen mode for security reasons.
284 cached_always_on_top_ = new_params.always_on_top;
285 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
286 new_params.always_on_top = false;
288 native_app_window_.reset(delegate_->CreateNativeAppWindow(this, new_params));
290 popup_manager_.reset(
291 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
292 popup_manager_->RegisterWith(web_contents);
294 // Prevent the browser process from shutting down while this window exists.
295 AppsClient::Get()->IncrementKeepAliveCount();
296 UpdateExtensionAppIcon();
297 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
299 if (new_params.hidden) {
300 // Although the window starts hidden by default, calling Hide() here
301 // notifies observers of the window being hidden.
302 Hide();
303 } else {
304 // Panels are not activated by default.
305 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
306 : SHOW_ACTIVE);
309 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
310 Fullscreen();
311 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
312 Maximize();
313 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
314 Minimize();
316 OnNativeWindowChanged();
318 // When the render view host is changed, the native window needs to know
319 // about it in case it has any setup to do to make the renderer appear
320 // properly. In particular, on Windows, the view's clickthrough region needs
321 // to be set.
322 extensions::ExtensionsBrowserClient* client =
323 extensions::ExtensionsBrowserClient::Get();
324 registrar_.Add(this,
325 chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
326 content::Source<content::BrowserContext>(
327 client->GetOriginalContext(browser_context_)));
328 // Close when the browser process is exiting.
329 registrar_.Add(this,
330 chrome::NOTIFICATION_APP_TERMINATING,
331 content::NotificationService::AllSources());
332 // Update the app menu if an ephemeral app becomes installed.
333 registrar_.Add(this,
334 chrome::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
335 content::Source<content::BrowserContext>(
336 client->GetOriginalContext(browser_context_)));
338 app_window_contents_->LoadContents(new_params.creator_process_id);
340 if (CommandLine::ForCurrentProcess()->HasSwitch(
341 switches::kEnableAppsShowOnFirstPaint)) {
342 // We want to show the window only when the content has been painted. For
343 // that to happen, we need to define a size for the content, otherwise the
344 // layout will happen in a 0x0 area.
345 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
346 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
347 initial_bounds.Inset(frame_insets);
348 apps::ResizeWebContents(web_contents, initial_bounds.size());
352 AppWindow::~AppWindow() {
353 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
354 // last window open.
355 registrar_.RemoveAll();
357 // Remove shutdown prevention.
358 AppsClient::Get()->DecrementKeepAliveCount();
361 void AppWindow::RequestMediaAccessPermission(
362 content::WebContents* web_contents,
363 const content::MediaStreamRequest& request,
364 const content::MediaResponseCallback& callback) {
365 const extensions::Extension* extension = GetExtension();
366 if (!extension)
367 return;
369 delegate_->RequestMediaAccessPermission(
370 web_contents, request, callback, extension);
373 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
374 const content::OpenURLParams& params) {
375 // Don't allow the current tab to be navigated. It would be nice to map all
376 // anchor tags (even those without target="_blank") to new tabs, but right
377 // now we can't distinguish between those and <meta> refreshes or window.href
378 // navigations, which we don't want to allow.
379 // TOOD(mihaip): Can we check for user gestures instead?
380 WindowOpenDisposition disposition = params.disposition;
381 if (disposition == CURRENT_TAB) {
382 AddMessageToDevToolsConsole(
383 content::CONSOLE_MESSAGE_LEVEL_ERROR,
384 base::StringPrintf(
385 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
386 params.url.spec().c_str()));
387 return NULL;
390 // These dispositions aren't really navigations.
391 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
392 disposition == IGNORE_ACTION) {
393 return NULL;
396 WebContents* contents =
397 delegate_->OpenURLFromTab(browser_context_, source, params);
398 if (!contents) {
399 AddMessageToDevToolsConsole(
400 content::CONSOLE_MESSAGE_LEVEL_ERROR,
401 base::StringPrintf(
402 "Can't navigate to \"%s\"; apps do not support navigation.",
403 params.url.spec().c_str()));
406 return contents;
409 void AppWindow::AddNewContents(WebContents* source,
410 WebContents* new_contents,
411 WindowOpenDisposition disposition,
412 const gfx::Rect& initial_pos,
413 bool user_gesture,
414 bool* was_blocked) {
415 DCHECK(new_contents->GetBrowserContext() == browser_context_);
416 delegate_->AddNewContents(browser_context_,
417 new_contents,
418 disposition,
419 initial_pos,
420 user_gesture,
421 was_blocked);
424 bool AppWindow::PreHandleKeyboardEvent(
425 content::WebContents* source,
426 const content::NativeWebKeyboardEvent& event,
427 bool* is_keyboard_shortcut) {
428 const extensions::Extension* extension = GetExtension();
429 if (!extension)
430 return false;
432 // Here, we can handle a key event before the content gets it. When we are
433 // fullscreen and it is not forced, we want to allow the user to leave
434 // when ESC is pressed.
435 // However, if the application has the "overrideEscFullscreen" permission, we
436 // should let it override that behavior.
437 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
438 // action is not prevented.
439 // Thus, we should handle the KeyEvent here only if the permission is not set.
440 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
441 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
442 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0) &&
443 !extension->permissions_data()->HasAPIPermission(
444 APIPermission::kOverrideEscFullscreen)) {
445 Restore();
446 return true;
449 return false;
452 void AppWindow::HandleKeyboardEvent(
453 WebContents* source,
454 const content::NativeWebKeyboardEvent& event) {
455 // If the window is currently fullscreen and not forced, ESC should leave
456 // fullscreen. If this code is being called for ESC, that means that the
457 // KeyEvent's default behavior was not prevented by the content.
458 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
459 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
460 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0)) {
461 Restore();
462 return;
465 native_app_window_->HandleKeyboardEvent(event);
468 void AppWindow::RequestToLockMouse(WebContents* web_contents,
469 bool user_gesture,
470 bool last_unlocked_by_target) {
471 const extensions::Extension* extension = GetExtension();
472 if (!extension)
473 return;
475 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
476 APIPermission::kPointerLock,
477 extension,
478 web_contents->GetRenderViewHost());
480 web_contents->GotResponseToLockMouseRequest(has_permission);
483 bool AppWindow::PreHandleGestureEvent(WebContents* source,
484 const blink::WebGestureEvent& event) {
485 // Disable pinch zooming in app windows.
486 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
487 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
488 event.type == blink::WebGestureEvent::GesturePinchEnd;
491 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
492 first_paint_complete_ = true;
493 if (show_on_first_paint_) {
494 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
495 delayed_show_type_ == SHOW_INACTIVE);
496 Show(delayed_show_type_);
500 void AppWindow::OnNativeClose() {
501 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
502 if (app_window_contents_) {
503 WebContents* web_contents = app_window_contents_->GetWebContents();
504 WebContentsModalDialogManager::FromWebContents(web_contents)
505 ->SetDelegate(NULL);
506 app_window_contents_->NativeWindowClosed();
508 delete this;
511 void AppWindow::OnNativeWindowChanged() {
512 SaveWindowPosition();
514 #if defined(OS_WIN)
515 if (native_app_window_ && cached_always_on_top_ &&
516 !IsFullscreen(fullscreen_types_) && !native_app_window_->IsMaximized() &&
517 !native_app_window_->IsMinimized()) {
518 UpdateNativeAlwaysOnTop();
520 #endif
522 if (app_window_contents_ && native_app_window_)
523 app_window_contents_->NativeWindowChanged(native_app_window_.get());
526 void AppWindow::OnNativeWindowActivated() {
527 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
530 content::WebContents* AppWindow::web_contents() const {
531 return app_window_contents_->GetWebContents();
534 const extensions::Extension* AppWindow::GetExtension() const {
535 return extensions::ExtensionRegistry::Get(browser_context_)
536 ->enabled_extensions()
537 .GetByID(extension_id_);
540 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
542 gfx::NativeWindow AppWindow::GetNativeWindow() {
543 return GetBaseWindow()->GetNativeWindow();
546 gfx::Rect AppWindow::GetClientBounds() const {
547 gfx::Rect bounds = native_app_window_->GetBounds();
548 bounds.Inset(native_app_window_->GetFrameInsets());
549 return bounds;
552 base::string16 AppWindow::GetTitle() const {
553 const extensions::Extension* extension = GetExtension();
554 if (!extension)
555 return base::string16();
557 // WebContents::GetTitle() will return the page's URL if there's no <title>
558 // specified. However, we'd prefer to show the name of the extension in that
559 // case, so we directly inspect the NavigationEntry's title.
560 base::string16 title;
561 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
562 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
563 title = base::UTF8ToUTF16(extension->name());
564 } else {
565 title = web_contents()->GetTitle();
567 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
568 return title;
571 void AppWindow::SetAppIconUrl(const GURL& url) {
572 // If the same url is being used for the badge, ignore it.
573 if (url == badge_icon_url_)
574 return;
576 // Avoid using any previous icons that were being downloaded.
577 image_loader_ptr_factory_.InvalidateWeakPtrs();
579 // Reset |app_icon_image_| to abort pending image load (if any).
580 app_icon_image_.reset();
582 app_icon_url_ = url;
583 web_contents()->DownloadImage(
584 url,
585 true, // is a favicon
586 0, // no maximum size
587 base::Bind(&AppWindow::DidDownloadFavicon,
588 image_loader_ptr_factory_.GetWeakPtr()));
591 void AppWindow::SetBadgeIconUrl(const GURL& url) {
592 // Avoid using any previous icons that were being downloaded.
593 image_loader_ptr_factory_.InvalidateWeakPtrs();
595 // Reset |app_icon_image_| to abort pending image load (if any).
596 badge_icon_image_.reset();
598 badge_icon_url_ = url;
599 web_contents()->DownloadImage(
600 url,
601 true, // is a favicon
602 0, // no maximum size
603 base::Bind(&AppWindow::DidDownloadFavicon,
604 image_loader_ptr_factory_.GetWeakPtr()));
607 void AppWindow::ClearBadge() {
608 badge_icon_image_.reset();
609 badge_icon_url_ = GURL();
610 UpdateBadgeIcon(gfx::Image());
613 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
614 native_app_window_->UpdateShape(region.Pass());
617 void AppWindow::UpdateDraggableRegions(
618 const std::vector<extensions::DraggableRegion>& regions) {
619 native_app_window_->UpdateDraggableRegions(regions);
622 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
623 if (image.IsEmpty())
624 return;
625 app_icon_ = image;
626 native_app_window_->UpdateWindowIcon();
627 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
630 void AppWindow::Fullscreen() {
631 #if !defined(OS_MACOSX)
632 // Do not enter fullscreen mode if disallowed by pref.
633 PrefService* prefs =
634 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
635 browser_context());
636 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
637 return;
638 #endif
639 fullscreen_types_ |= FULLSCREEN_TYPE_WINDOW_API;
640 SetNativeWindowFullscreen();
643 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
645 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
647 void AppWindow::Restore() {
648 if (IsFullscreen(fullscreen_types_)) {
649 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
650 SetNativeWindowFullscreen();
651 } else {
652 GetBaseWindow()->Restore();
656 void AppWindow::OSFullscreen() {
657 #if !defined(OS_MACOSX)
658 // Do not enter fullscreen mode if disallowed by pref.
659 PrefService* prefs =
660 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
661 browser_context());
662 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
663 return;
664 #endif
665 fullscreen_types_ |= FULLSCREEN_TYPE_OS;
666 SetNativeWindowFullscreen();
669 void AppWindow::ForcedFullscreen() {
670 fullscreen_types_ |= FULLSCREEN_TYPE_FORCED;
671 SetNativeWindowFullscreen();
674 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
675 const gfx::Size& max_size) {
676 SizeConstraints constraints(min_size, max_size);
677 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
678 constraints.GetMaximumSize());
680 gfx::Rect bounds = GetClientBounds();
681 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
682 if (bounds.size() != constrained_size) {
683 bounds.set_size(constrained_size);
684 bounds.Inset(-native_app_window_->GetFrameInsets());
685 native_app_window_->SetBounds(bounds);
687 OnNativeWindowChanged();
690 void AppWindow::Show(ShowType show_type) {
691 is_hidden_ = false;
693 if (CommandLine::ForCurrentProcess()->HasSwitch(
694 switches::kEnableAppsShowOnFirstPaint)) {
695 show_on_first_paint_ = true;
697 if (!first_paint_complete_) {
698 delayed_show_type_ = show_type;
699 return;
703 switch (show_type) {
704 case SHOW_ACTIVE:
705 GetBaseWindow()->Show();
706 break;
707 case SHOW_INACTIVE:
708 GetBaseWindow()->ShowInactive();
709 break;
711 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this);
713 has_been_shown_ = true;
714 SendOnWindowShownIfShown();
717 void AppWindow::Hide() {
718 // This is there to prevent race conditions with Hide() being called before
719 // there was a non-empty paint. It should have no effect in a non-racy
720 // scenario where the application is hiding then showing a window: the second
721 // show will not be delayed.
722 is_hidden_ = true;
723 show_on_first_paint_ = false;
724 GetBaseWindow()->Hide();
725 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
728 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
729 if (cached_always_on_top_ == always_on_top)
730 return;
732 cached_always_on_top_ = always_on_top;
734 // As a security measure, do not allow fullscreen windows or windows that
735 // overlap the taskbar to be on top. The property will be applied when the
736 // window exits fullscreen and moves away from the taskbar.
737 if (!IsFullscreen(fullscreen_types_) && !IntersectsWithTaskbar())
738 native_app_window_->SetAlwaysOnTop(always_on_top);
740 OnNativeWindowChanged();
743 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
745 void AppWindow::WindowEventsReady() {
746 can_send_events_ = true;
747 SendOnWindowShownIfShown();
750 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
751 DCHECK(properties);
753 properties->SetBoolean("fullscreen",
754 native_app_window_->IsFullscreenOrPending());
755 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
756 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
757 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
758 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
760 // These properties are undocumented and are to enable testing. Alpha is
761 // removed to
762 // make the values easier to check.
763 SkColor transparent_white = ~SK_ColorBLACK;
764 properties->SetInteger(
765 "activeFrameColor",
766 native_app_window_->ActiveFrameColor() & transparent_white);
767 properties->SetInteger(
768 "inactiveFrameColor",
769 native_app_window_->InactiveFrameColor() & transparent_white);
771 gfx::Rect content_bounds = GetClientBounds();
772 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
773 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
774 SetBoundsProperties(content_bounds,
775 content_min_size,
776 content_max_size,
777 "innerBounds",
778 properties);
780 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
781 gfx::Rect frame_bounds = native_app_window_->GetBounds();
782 gfx::Size frame_min_size =
783 SizeConstraints::AddFrameToConstraints(content_min_size, frame_insets);
784 gfx::Size frame_max_size =
785 SizeConstraints::AddFrameToConstraints(content_max_size, frame_insets);
786 SetBoundsProperties(frame_bounds,
787 frame_min_size,
788 frame_max_size,
789 "outerBounds",
790 properties);
793 //------------------------------------------------------------------------------
794 // Private methods
796 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
797 badge_icon_ = image;
798 native_app_window_->UpdateBadgeIcon();
801 void AppWindow::DidDownloadFavicon(
802 int id,
803 int http_status_code,
804 const GURL& image_url,
805 const std::vector<SkBitmap>& bitmaps,
806 const std::vector<gfx::Size>& original_bitmap_sizes) {
807 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
808 bitmaps.empty()) {
809 return;
812 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
813 // whose height >= the preferred size.
814 int largest_index = 0;
815 for (size_t i = 1; i < bitmaps.size(); ++i) {
816 if (bitmaps[i].height() < delegate_->PreferredIconSize())
817 break;
818 largest_index = i;
820 const SkBitmap& largest = bitmaps[largest_index];
821 if (image_url == app_icon_url_) {
822 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
823 return;
826 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
829 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
830 DCHECK_EQ(app_icon_image_.get(), image);
832 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
835 void AppWindow::UpdateExtensionAppIcon() {
836 // Avoid using any previous app icons were being downloaded.
837 image_loader_ptr_factory_.InvalidateWeakPtrs();
839 const gfx::ImageSkia& default_icon =
840 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
841 IDR_APP_DEFAULT_ICON);
843 const extensions::Extension* extension = GetExtension();
844 if (!extension)
845 return;
847 app_icon_image_.reset(
848 new extensions::IconImage(browser_context(),
849 extension,
850 extensions::IconsInfo::GetIcons(extension),
851 delegate_->PreferredIconSize(),
852 default_icon,
853 this));
855 // Triggers actual image loading with 1x resources. The 2x resource will
856 // be handled by IconImage class when requested.
857 app_icon_image_->image_skia().GetRepresentation(1.0f);
860 void AppWindow::SetNativeWindowFullscreen() {
861 native_app_window_->SetFullscreen(fullscreen_types_);
863 if (cached_always_on_top_)
864 UpdateNativeAlwaysOnTop();
867 bool AppWindow::IntersectsWithTaskbar() const {
868 #if defined(OS_WIN)
869 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
870 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
871 std::vector<gfx::Display> displays = screen->GetAllDisplays();
873 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
874 it != displays.end();
875 ++it) {
876 gfx::Rect taskbar_bounds = it->bounds();
877 taskbar_bounds.Subtract(it->work_area());
878 if (taskbar_bounds.IsEmpty())
879 continue;
881 if (window_bounds.Intersects(taskbar_bounds))
882 return true;
884 #endif
886 return false;
889 void AppWindow::UpdateNativeAlwaysOnTop() {
890 DCHECK(cached_always_on_top_);
891 bool is_on_top = native_app_window_->IsAlwaysOnTop();
892 bool fullscreen = IsFullscreen(fullscreen_types_);
893 bool intersects_taskbar = IntersectsWithTaskbar();
895 if (is_on_top && (fullscreen || intersects_taskbar)) {
896 // When entering fullscreen or overlapping the taskbar, ensure windows are
897 // not always-on-top.
898 native_app_window_->SetAlwaysOnTop(false);
899 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
900 // When exiting fullscreen and moving away from the taskbar, reinstate
901 // always-on-top.
902 native_app_window_->SetAlwaysOnTop(true);
906 void AppWindow::SendOnWindowShownIfShown() {
907 if (!can_send_events_ || !has_been_shown_)
908 return;
910 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kTestType)) {
911 app_window_contents_->DispatchWindowShownForTests();
915 void AppWindow::CloseContents(WebContents* contents) {
916 native_app_window_->Close();
919 bool AppWindow::ShouldSuppressDialogs() { return true; }
921 content::ColorChooser* AppWindow::OpenColorChooser(
922 WebContents* web_contents,
923 SkColor initial_color,
924 const std::vector<content::ColorSuggestion>& suggestionss) {
925 return delegate_->ShowColorChooser(web_contents, initial_color);
928 void AppWindow::RunFileChooser(WebContents* tab,
929 const content::FileChooserParams& params) {
930 if (window_type_is_panel()) {
931 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
932 // dialogs to be unhosted but still close with the owning web contents.
933 // crbug.com/172502.
934 LOG(WARNING) << "File dialog opened by panel.";
935 return;
938 delegate_->RunFileChooser(tab, params);
941 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
943 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
944 native_app_window_->SetBounds(pos);
947 void AppWindow::NavigationStateChanged(const content::WebContents* source,
948 unsigned changed_flags) {
949 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
950 native_app_window_->UpdateWindowTitle();
951 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
952 native_app_window_->UpdateWindowIcon();
955 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
956 bool enter_fullscreen) {
957 #if !defined(OS_MACOSX)
958 // Do not enter fullscreen mode if disallowed by pref.
959 // TODO(bartfab): Add a test once it becomes possible to simulate a user
960 // gesture. http://crbug.com/174178
961 PrefService* prefs =
962 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
963 browser_context());
964 if (enter_fullscreen && !prefs->GetBoolean(prefs::kAppFullscreenAllowed)) {
965 return;
967 #endif
969 const extensions::Extension* extension = GetExtension();
970 if (!extension)
971 return;
973 if (!IsExtensionWithPermissionOrSuggestInConsole(
974 APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
975 return;
978 if (enter_fullscreen)
979 fullscreen_types_ |= FULLSCREEN_TYPE_HTML_API;
980 else
981 fullscreen_types_ &= ~FULLSCREEN_TYPE_HTML_API;
982 SetNativeWindowFullscreen();
985 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
986 const {
987 return ((fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0);
990 void AppWindow::Observe(int type,
991 const content::NotificationSource& source,
992 const content::NotificationDetails& details) {
993 switch (type) {
994 case chrome::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
995 const extensions::Extension* unloaded_extension =
996 content::Details<extensions::UnloadedExtensionInfo>(details)
997 ->extension;
998 if (extension_id_ == unloaded_extension->id())
999 native_app_window_->Close();
1000 break;
1002 case chrome::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
1003 const extensions::Extension* installed_extension =
1004 content::Details<const extensions::InstalledExtensionInfo>(details)
1005 ->extension;
1006 DCHECK(installed_extension);
1007 if (installed_extension->id() == extension_id())
1008 native_app_window_->UpdateShelfMenu();
1009 break;
1011 case chrome::NOTIFICATION_APP_TERMINATING:
1012 native_app_window_->Close();
1013 break;
1014 default:
1015 NOTREACHED() << "Received unexpected notification";
1019 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
1020 bool blocked) {
1021 delegate_->SetWebContentsBlocked(web_contents, blocked);
1024 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
1025 return delegate_->IsWebContentsVisible(web_contents);
1028 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
1029 return native_app_window_.get();
1032 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
1033 const std::string& message) {
1034 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
1035 rvh->Send(new ExtensionMsg_AddMessageToConsole(
1036 rvh->GetRoutingID(), level, message));
1039 void AppWindow::SaveWindowPosition() {
1040 if (window_key_.empty())
1041 return;
1042 if (!native_app_window_)
1043 return;
1045 AppWindowGeometryCache* cache =
1046 AppWindowGeometryCache::Get(browser_context());
1048 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
1049 gfx::Rect screen_bounds =
1050 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
1051 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1052 cache->SaveGeometry(
1053 extension_id(), window_key_, bounds, screen_bounds, window_state);
1056 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1057 const gfx::Rect& cached_bounds,
1058 const gfx::Rect& cached_screen_bounds,
1059 const gfx::Rect& current_screen_bounds,
1060 const gfx::Size& minimum_size,
1061 gfx::Rect* bounds) const {
1062 *bounds = cached_bounds;
1064 // Reposition and resize the bounds if the cached_screen_bounds is different
1065 // from the current screen bounds and the current screen bounds doesn't
1066 // completely contain the bounds.
1067 if (cached_screen_bounds != current_screen_bounds &&
1068 !current_screen_bounds.Contains(cached_bounds)) {
1069 bounds->set_width(
1070 std::max(minimum_size.width(),
1071 std::min(bounds->width(), current_screen_bounds.width())));
1072 bounds->set_height(
1073 std::max(minimum_size.height(),
1074 std::min(bounds->height(), current_screen_bounds.height())));
1075 bounds->set_x(
1076 std::max(current_screen_bounds.x(),
1077 std::min(bounds->x(),
1078 current_screen_bounds.right() - bounds->width())));
1079 bounds->set_y(
1080 std::max(current_screen_bounds.y(),
1081 std::min(bounds->y(),
1082 current_screen_bounds.bottom() - bounds->height())));
1086 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1087 const {
1088 // Ensure width and height are specified.
1089 if (params.content_spec.bounds.width() == 0 &&
1090 params.window_spec.bounds.width() == 0) {
1091 params.content_spec.bounds.set_width(kDefaultWidth);
1093 if (params.content_spec.bounds.height() == 0 &&
1094 params.window_spec.bounds.height() == 0) {
1095 params.content_spec.bounds.set_height(kDefaultHeight);
1098 // If left and top are left undefined, the native app window will center
1099 // the window on the main screen in a platform-defined manner.
1101 // Load cached state if it exists.
1102 if (!params.window_key.empty()) {
1103 AppWindowGeometryCache* cache =
1104 AppWindowGeometryCache::Get(browser_context());
1106 gfx::Rect cached_bounds;
1107 gfx::Rect cached_screen_bounds;
1108 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1109 if (cache->GetGeometry(extension_id(),
1110 params.window_key,
1111 &cached_bounds,
1112 &cached_screen_bounds,
1113 &cached_state)) {
1114 // App window has cached screen bounds, make sure it fits on screen in
1115 // case the screen resolution changed.
1116 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1117 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1118 gfx::Rect current_screen_bounds = display.work_area();
1119 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1120 params.GetWindowMaximumSize(gfx::Insets()));
1121 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1122 cached_screen_bounds,
1123 current_screen_bounds,
1124 constraints.GetMinimumSize(),
1125 &params.window_spec.bounds);
1126 params.state = cached_state;
1128 // Since we are restoring a cached state, reset the content bounds spec to
1129 // ensure it is not used.
1130 params.content_spec.ResetBounds();
1134 return params;
1137 // static
1138 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1139 const std::vector<extensions::DraggableRegion>& regions) {
1140 SkRegion* sk_region = new SkRegion;
1141 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
1142 regions.begin();
1143 iter != regions.end();
1144 ++iter) {
1145 const extensions::DraggableRegion& region = *iter;
1146 sk_region->op(
1147 region.bounds.x(),
1148 region.bounds.y(),
1149 region.bounds.right(),
1150 region.bounds.bottom(),
1151 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1153 return sk_region;
1156 } // namespace apps