Added the |findupdate| event to the <webview> find API as described in: https://docs...
[chromium-blink-merge.git] / apps / app_window.cc
blob57047b2819cc534ac9068f3b6899f2c1eea90779
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 "apps/app_window_geometry_cache.h"
8 #include "apps/app_window_registry.h"
9 #include "apps/apps_client.h"
10 #include "apps/size_constraints.h"
11 #include "apps/ui/native_app_window.h"
12 #include "base/command_line.h"
13 #include "base/strings/string_util.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/values.h"
16 #include "chrome/browser/chrome_notification_types.h"
17 #include "chrome/browser/extensions/extension_web_contents_observer.h"
18 #include "chrome/browser/extensions/suggest_permission_util.h"
19 #include "chrome/common/chrome_switches.h"
20 #include "chrome/common/extensions/extension_messages.h"
21 #include "chrome/common/extensions/manifest_handlers/icons_handler.h"
22 #include "components/web_modal/web_contents_modal_dialog_manager.h"
23 #include "content/public/browser/browser_context.h"
24 #include "content/public/browser/invalidate_type.h"
25 #include "content/public/browser/navigation_entry.h"
26 #include "content/public/browser/notification_details.h"
27 #include "content/public/browser/notification_service.h"
28 #include "content/public/browser/notification_source.h"
29 #include "content/public/browser/notification_types.h"
30 #include "content/public/browser/render_view_host.h"
31 #include "content/public/browser/resource_dispatcher_host.h"
32 #include "content/public/browser/web_contents.h"
33 #include "content/public/browser/web_contents_view.h"
34 #include "content/public/common/media_stream_request.h"
35 #include "extensions/browser/extension_system.h"
36 #include "extensions/browser/extensions_browser_client.h"
37 #include "extensions/browser/process_manager.h"
38 #include "extensions/browser/view_type_utils.h"
39 #include "extensions/common/extension.h"
40 #include "third_party/skia/include/core/SkRegion.h"
41 #include "ui/gfx/screen.h"
43 #if !defined(OS_MACOSX)
44 #include "apps/pref_names.h"
45 #include "base/prefs/pref_service.h"
46 #endif
48 using content::BrowserContext;
49 using content::ConsoleMessageLevel;
50 using content::WebContents;
51 using extensions::APIPermission;
52 using web_modal::WebContentsModalDialogHost;
53 using web_modal::WebContentsModalDialogManager;
55 namespace apps {
57 namespace {
59 const int kDefaultWidth = 512;
60 const int kDefaultHeight = 384;
62 bool IsFullscreen(int fullscreen_types) {
63 return fullscreen_types != apps::AppWindow::FULLSCREEN_TYPE_NONE;
66 void SetConstraintProperty(const std::string& name,
67 int value,
68 base::DictionaryValue* bounds_properties) {
69 if (value != SizeConstraints::kUnboundedSize)
70 bounds_properties->SetInteger(name, value);
71 else
72 bounds_properties->Set(name, base::Value::CreateNullValue());
75 void SetBoundsProperties(const gfx::Rect& bounds,
76 const gfx::Size& min_size,
77 const gfx::Size& max_size,
78 const std::string& bounds_name,
79 base::DictionaryValue* window_properties) {
80 scoped_ptr<base::DictionaryValue> bounds_properties(
81 new base::DictionaryValue());
83 bounds_properties->SetInteger("left", bounds.x());
84 bounds_properties->SetInteger("top", bounds.y());
85 bounds_properties->SetInteger("width", bounds.width());
86 bounds_properties->SetInteger("height", bounds.height());
88 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
89 SetConstraintProperty(
90 "minHeight", min_size.height(), bounds_properties.get());
91 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
92 SetConstraintProperty(
93 "maxHeight", max_size.height(), bounds_properties.get());
95 window_properties->Set(bounds_name, bounds_properties.release());
98 } // namespace
100 AppWindow::CreateParams::CreateParams()
101 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
102 frame(AppWindow::FRAME_CHROME),
103 has_frame_color(false),
104 transparent_background(false),
105 bounds(INT_MIN, INT_MIN, 0, 0),
106 creator_process_id(0),
107 state(ui::SHOW_STATE_DEFAULT),
108 hidden(false),
109 resizable(true),
110 focused(true),
111 always_on_top(false) {}
113 AppWindow::CreateParams::~CreateParams() {}
115 AppWindow::Delegate::~Delegate() {}
117 AppWindow::AppWindow(BrowserContext* context,
118 Delegate* delegate,
119 const extensions::Extension* extension)
120 : browser_context_(context),
121 extension_(extension),
122 extension_id_(extension->id()),
123 window_type_(WINDOW_TYPE_DEFAULT),
124 delegate_(delegate),
125 image_loader_ptr_factory_(this),
126 fullscreen_types_(FULLSCREEN_TYPE_NONE),
127 show_on_first_paint_(false),
128 first_paint_complete_(false),
129 cached_always_on_top_(false) {
130 extensions::ExtensionsBrowserClient* client =
131 extensions::ExtensionsBrowserClient::Get();
132 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
133 << "Only off the record window may be opened in the guest mode.";
136 void AppWindow::Init(const GURL& url,
137 AppWindowContents* app_window_contents,
138 const CreateParams& params) {
139 // Initialize the render interface and web contents
140 app_window_contents_.reset(app_window_contents);
141 app_window_contents_->Initialize(browser_context(), url);
142 WebContents* web_contents = app_window_contents_->GetWebContents();
143 if (CommandLine::ForCurrentProcess()->HasSwitch(
144 switches::kEnableAppsShowOnFirstPaint)) {
145 content::WebContentsObserver::Observe(web_contents);
147 delegate_->InitWebContents(web_contents);
148 WebContentsModalDialogManager::CreateForWebContents(web_contents);
149 extensions::ExtensionWebContentsObserver::CreateForWebContents(web_contents);
151 web_contents->SetDelegate(this);
152 WebContentsModalDialogManager::FromWebContents(web_contents)
153 ->SetDelegate(this);
154 extensions::SetViewType(web_contents, extensions::VIEW_TYPE_APP_WINDOW);
156 // Initialize the window
157 CreateParams new_params = LoadDefaultsAndConstrain(params);
158 window_type_ = new_params.window_type;
159 window_key_ = new_params.window_key;
161 // Windows cannot be always-on-top in fullscreen mode for security reasons.
162 cached_always_on_top_ = new_params.always_on_top;
163 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
164 new_params.always_on_top = false;
166 native_app_window_.reset(delegate_->CreateNativeAppWindow(this, new_params));
168 if (!new_params.hidden) {
169 // Panels are not activated by default.
170 Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
171 : SHOW_ACTIVE);
174 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
175 Fullscreen();
176 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
177 Maximize();
178 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
179 Minimize();
181 OnNativeWindowChanged();
183 // When the render view host is changed, the native window needs to know
184 // about it in case it has any setup to do to make the renderer appear
185 // properly. In particular, on Windows, the view's clickthrough region needs
186 // to be set.
187 extensions::ExtensionsBrowserClient* client =
188 extensions::ExtensionsBrowserClient::Get();
189 registrar_.Add(this,
190 chrome::NOTIFICATION_EXTENSION_UNLOADED,
191 content::Source<content::BrowserContext>(
192 client->GetOriginalContext(browser_context_)));
193 // Close when the browser process is exiting.
194 registrar_.Add(this,
195 chrome::NOTIFICATION_APP_TERMINATING,
196 content::NotificationService::AllSources());
197 // Update the app menu if an ephemeral app becomes installed.
198 registrar_.Add(this,
199 chrome::NOTIFICATION_EXTENSION_INSTALLED,
200 content::Source<content::BrowserContext>(
201 client->GetOriginalContext(browser_context_)));
203 app_window_contents_->LoadContents(new_params.creator_process_id);
205 if (CommandLine::ForCurrentProcess()->HasSwitch(
206 switches::kEnableAppsShowOnFirstPaint)) {
207 // We want to show the window only when the content has been painted. For
208 // that to happen, we need to define a size for the content, otherwise the
209 // layout will happen in a 0x0 area.
210 // Note: WebContents::GetView() is guaranteed to be non-null.
211 web_contents->GetView()->SizeContents(new_params.bounds.size());
214 // Prevent the browser process from shutting down while this window is open.
215 AppsClient::Get()->IncrementKeepAliveCount();
217 UpdateExtensionAppIcon();
219 AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
222 AppWindow::~AppWindow() {
223 // Unregister now to prevent getting NOTIFICATION_APP_TERMINATING if we're the
224 // last window open.
225 registrar_.RemoveAll();
227 // Remove shutdown prevention.
228 AppsClient::Get()->DecrementKeepAliveCount();
231 void AppWindow::RequestMediaAccessPermission(
232 content::WebContents* web_contents,
233 const content::MediaStreamRequest& request,
234 const content::MediaResponseCallback& callback) {
235 delegate_->RequestMediaAccessPermission(
236 web_contents, request, callback, extension());
239 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
240 const content::OpenURLParams& params) {
241 // Don't allow the current tab to be navigated. It would be nice to map all
242 // anchor tags (even those without target="_blank") to new tabs, but right
243 // now we can't distinguish between those and <meta> refreshes or window.href
244 // navigations, which we don't want to allow.
245 // TOOD(mihaip): Can we check for user gestures instead?
246 WindowOpenDisposition disposition = params.disposition;
247 if (disposition == CURRENT_TAB) {
248 AddMessageToDevToolsConsole(
249 content::CONSOLE_MESSAGE_LEVEL_ERROR,
250 base::StringPrintf(
251 "Can't open same-window link to \"%s\"; try target=\"_blank\".",
252 params.url.spec().c_str()));
253 return NULL;
256 // These dispositions aren't really navigations.
257 if (disposition == SUPPRESS_OPEN || disposition == SAVE_TO_DISK ||
258 disposition == IGNORE_ACTION) {
259 return NULL;
262 WebContents* contents =
263 delegate_->OpenURLFromTab(browser_context_, source, params);
264 if (!contents) {
265 AddMessageToDevToolsConsole(
266 content::CONSOLE_MESSAGE_LEVEL_ERROR,
267 base::StringPrintf(
268 "Can't navigate to \"%s\"; apps do not support navigation.",
269 params.url.spec().c_str()));
272 return contents;
275 void AppWindow::AddNewContents(WebContents* source,
276 WebContents* new_contents,
277 WindowOpenDisposition disposition,
278 const gfx::Rect& initial_pos,
279 bool user_gesture,
280 bool* was_blocked) {
281 DCHECK(new_contents->GetBrowserContext() == browser_context_);
282 delegate_->AddNewContents(browser_context_,
283 new_contents,
284 disposition,
285 initial_pos,
286 user_gesture,
287 was_blocked);
290 bool AppWindow::PreHandleKeyboardEvent(
291 content::WebContents* source,
292 const content::NativeWebKeyboardEvent& event,
293 bool* is_keyboard_shortcut) {
294 // Here, we can handle a key event before the content gets it. When we are
295 // fullscreen and it is not forced, we want to allow the user to leave
296 // when ESC is pressed.
297 // However, if the application has the "overrideEscFullscreen" permission, we
298 // should let it override that behavior.
299 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
300 // action is not prevented.
301 // Thus, we should handle the KeyEvent here only if the permission is not set.
302 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
303 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
304 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0) &&
305 !extension_->HasAPIPermission(APIPermission::kOverrideEscFullscreen)) {
306 Restore();
307 return true;
310 return false;
313 void AppWindow::HandleKeyboardEvent(
314 WebContents* source,
315 const content::NativeWebKeyboardEvent& event) {
316 // If the window is currently fullscreen and not forced, ESC should leave
317 // fullscreen. If this code is being called for ESC, that means that the
318 // KeyEvent's default behavior was not prevented by the content.
319 if (event.windowsKeyCode == ui::VKEY_ESCAPE &&
320 (fullscreen_types_ != FULLSCREEN_TYPE_NONE) &&
321 ((fullscreen_types_ & FULLSCREEN_TYPE_FORCED) == 0)) {
322 Restore();
323 return;
326 native_app_window_->HandleKeyboardEvent(event);
329 void AppWindow::RequestToLockMouse(WebContents* web_contents,
330 bool user_gesture,
331 bool last_unlocked_by_target) {
332 bool has_permission = IsExtensionWithPermissionOrSuggestInConsole(
333 APIPermission::kPointerLock,
334 extension_,
335 web_contents->GetRenderViewHost());
337 web_contents->GotResponseToLockMouseRequest(has_permission);
340 bool AppWindow::PreHandleGestureEvent(WebContents* source,
341 const blink::WebGestureEvent& event) {
342 // Disable pinch zooming in app windows.
343 return event.type == blink::WebGestureEvent::GesturePinchBegin ||
344 event.type == blink::WebGestureEvent::GesturePinchUpdate ||
345 event.type == blink::WebGestureEvent::GesturePinchEnd;
348 void AppWindow::DidFirstVisuallyNonEmptyPaint(int32 page_id) {
349 first_paint_complete_ = true;
350 if (show_on_first_paint_) {
351 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
352 delayed_show_type_ == SHOW_INACTIVE);
353 Show(delayed_show_type_);
357 void AppWindow::OnNativeClose() {
358 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
359 if (app_window_contents_) {
360 WebContents* web_contents = app_window_contents_->GetWebContents();
361 WebContentsModalDialogManager::FromWebContents(web_contents)
362 ->SetDelegate(NULL);
363 app_window_contents_->NativeWindowClosed();
365 delete this;
368 void AppWindow::OnNativeWindowChanged() {
369 SaveWindowPosition();
371 #if defined(OS_WIN)
372 if (native_app_window_ && cached_always_on_top_ &&
373 !IsFullscreen(fullscreen_types_) && !native_app_window_->IsMaximized() &&
374 !native_app_window_->IsMinimized()) {
375 UpdateNativeAlwaysOnTop();
377 #endif
379 if (app_window_contents_ && native_app_window_)
380 app_window_contents_->NativeWindowChanged(native_app_window_.get());
383 void AppWindow::OnNativeWindowActivated() {
384 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
387 content::WebContents* AppWindow::web_contents() const {
388 return app_window_contents_->GetWebContents();
391 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
393 gfx::NativeWindow AppWindow::GetNativeWindow() {
394 return GetBaseWindow()->GetNativeWindow();
397 gfx::Rect AppWindow::GetClientBounds() const {
398 gfx::Rect bounds = native_app_window_->GetBounds();
399 bounds.Inset(native_app_window_->GetFrameInsets());
400 return bounds;
403 base::string16 AppWindow::GetTitle() const {
404 // WebContents::GetTitle() will return the page's URL if there's no <title>
405 // specified. However, we'd prefer to show the name of the extension in that
406 // case, so we directly inspect the NavigationEntry's title.
407 base::string16 title;
408 if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
409 web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
410 title = base::UTF8ToUTF16(extension()->name());
411 } else {
412 title = web_contents()->GetTitle();
414 const base::char16 kBadChars[] = {'\n', 0};
415 base::RemoveChars(title, kBadChars, &title);
416 return title;
419 void AppWindow::SetAppIconUrl(const GURL& url) {
420 // If the same url is being used for the badge, ignore it.
421 if (url == badge_icon_url_)
422 return;
424 // Avoid using any previous icons that were being downloaded.
425 image_loader_ptr_factory_.InvalidateWeakPtrs();
427 // Reset |app_icon_image_| to abort pending image load (if any).
428 app_icon_image_.reset();
430 app_icon_url_ = url;
431 web_contents()->DownloadImage(
432 url,
433 true, // is a favicon
434 0, // no maximum size
435 base::Bind(&AppWindow::DidDownloadFavicon,
436 image_loader_ptr_factory_.GetWeakPtr()));
439 void AppWindow::SetBadgeIconUrl(const GURL& url) {
440 // Avoid using any previous icons that were being downloaded.
441 image_loader_ptr_factory_.InvalidateWeakPtrs();
443 // Reset |app_icon_image_| to abort pending image load (if any).
444 badge_icon_image_.reset();
446 badge_icon_url_ = url;
447 web_contents()->DownloadImage(
448 url,
449 true, // is a favicon
450 0, // no maximum size
451 base::Bind(&AppWindow::DidDownloadFavicon,
452 image_loader_ptr_factory_.GetWeakPtr()));
455 void AppWindow::ClearBadge() {
456 badge_icon_image_.reset();
457 badge_icon_url_ = GURL();
458 UpdateBadgeIcon(gfx::Image());
461 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
462 native_app_window_->UpdateShape(region.Pass());
465 void AppWindow::UpdateDraggableRegions(
466 const std::vector<extensions::DraggableRegion>& regions) {
467 native_app_window_->UpdateDraggableRegions(regions);
470 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
471 if (image.IsEmpty())
472 return;
473 app_icon_ = image;
474 native_app_window_->UpdateWindowIcon();
475 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
478 void AppWindow::Fullscreen() {
479 #if !defined(OS_MACOSX)
480 // Do not enter fullscreen mode if disallowed by pref.
481 PrefService* prefs =
482 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
483 browser_context());
484 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
485 return;
486 #endif
487 fullscreen_types_ |= FULLSCREEN_TYPE_WINDOW_API;
488 SetNativeWindowFullscreen();
491 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
493 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
495 void AppWindow::Restore() {
496 if (IsFullscreen(fullscreen_types_)) {
497 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
498 SetNativeWindowFullscreen();
499 } else {
500 GetBaseWindow()->Restore();
504 void AppWindow::OSFullscreen() {
505 #if !defined(OS_MACOSX)
506 // Do not enter fullscreen mode if disallowed by pref.
507 PrefService* prefs =
508 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
509 browser_context());
510 if (!prefs->GetBoolean(prefs::kAppFullscreenAllowed))
511 return;
512 #endif
513 fullscreen_types_ |= FULLSCREEN_TYPE_OS;
514 SetNativeWindowFullscreen();
517 void AppWindow::ForcedFullscreen() {
518 fullscreen_types_ |= FULLSCREEN_TYPE_FORCED;
519 SetNativeWindowFullscreen();
522 void AppWindow::SetMinimumSize(const gfx::Size& min_size) {
523 native_app_window_->SetMinimumSize(min_size);
524 OnSizeConstraintsChanged();
527 void AppWindow::SetMaximumSize(const gfx::Size& max_size) {
528 native_app_window_->SetMaximumSize(max_size);
529 OnSizeConstraintsChanged();
532 void AppWindow::Show(ShowType show_type) {
533 if (CommandLine::ForCurrentProcess()->HasSwitch(
534 switches::kEnableAppsShowOnFirstPaint)) {
535 show_on_first_paint_ = true;
537 if (!first_paint_complete_) {
538 delayed_show_type_ = show_type;
539 return;
543 switch (show_type) {
544 case SHOW_ACTIVE:
545 GetBaseWindow()->Show();
546 break;
547 case SHOW_INACTIVE:
548 GetBaseWindow()->ShowInactive();
549 break;
553 void AppWindow::Hide() {
554 // This is there to prevent race conditions with Hide() being called before
555 // there was a non-empty paint. It should have no effect in a non-racy
556 // scenario where the application is hiding then showing a window: the second
557 // show will not be delayed.
558 show_on_first_paint_ = false;
559 GetBaseWindow()->Hide();
562 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
563 if (cached_always_on_top_ == always_on_top)
564 return;
566 cached_always_on_top_ = always_on_top;
568 // As a security measure, do not allow fullscreen windows or windows that
569 // overlap the taskbar to be on top. The property will be applied when the
570 // window exits fullscreen and moves away from the taskbar.
571 if (!IsFullscreen(fullscreen_types_) && !IntersectsWithTaskbar())
572 native_app_window_->SetAlwaysOnTop(always_on_top);
574 OnNativeWindowChanged();
577 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
579 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
580 DCHECK(properties);
582 properties->SetBoolean("fullscreen",
583 native_app_window_->IsFullscreenOrPending());
584 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
585 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
586 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
587 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
588 properties->SetInteger("frameColor", native_app_window_->FrameColor());
590 gfx::Rect content_bounds = GetClientBounds();
591 SetBoundsProperties(content_bounds,
592 native_app_window_->GetMinimumSize(),
593 native_app_window_->GetMaximumSize(),
594 "innerBounds",
595 properties);
597 // TODO(tmdiep): Frame constraints will be implemented in a future patch.
598 gfx::Rect frame_bounds = native_app_window_->GetBounds();
599 SetBoundsProperties(frame_bounds,
600 gfx::Size(),
601 gfx::Size(),
602 "outerBounds",
603 properties);
606 //------------------------------------------------------------------------------
607 // Private methods
609 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
610 badge_icon_ = image;
611 native_app_window_->UpdateBadgeIcon();
614 void AppWindow::DidDownloadFavicon(
615 int id,
616 int http_status_code,
617 const GURL& image_url,
618 const std::vector<SkBitmap>& bitmaps,
619 const std::vector<gfx::Size>& original_bitmap_sizes) {
620 if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
621 bitmaps.empty()) {
622 return;
625 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
626 // whose height >= the preferred size.
627 int largest_index = 0;
628 for (size_t i = 1; i < bitmaps.size(); ++i) {
629 if (bitmaps[i].height() < delegate_->PreferredIconSize())
630 break;
631 largest_index = i;
633 const SkBitmap& largest = bitmaps[largest_index];
634 if (image_url == app_icon_url_) {
635 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
636 return;
639 UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
642 void AppWindow::OnExtensionIconImageChanged(extensions::IconImage* image) {
643 DCHECK_EQ(app_icon_image_.get(), image);
645 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
648 void AppWindow::UpdateExtensionAppIcon() {
649 // Avoid using any previous app icons were being downloaded.
650 image_loader_ptr_factory_.InvalidateWeakPtrs();
652 app_icon_image_.reset(
653 new extensions::IconImage(browser_context(),
654 extension(),
655 extensions::IconsInfo::GetIcons(extension()),
656 delegate_->PreferredIconSize(),
657 extensions::IconsInfo::GetDefaultAppIcon(),
658 this));
660 // Triggers actual image loading with 1x resources. The 2x resource will
661 // be handled by IconImage class when requested.
662 app_icon_image_->image_skia().GetRepresentation(1.0f);
665 void AppWindow::OnSizeConstraintsChanged() {
666 SizeConstraints size_constraints(native_app_window_->GetMinimumSize(),
667 native_app_window_->GetMaximumSize());
668 gfx::Rect bounds = GetClientBounds();
669 gfx::Size constrained_size = size_constraints.ClampSize(bounds.size());
670 if (bounds.size() != constrained_size) {
671 bounds.set_size(constrained_size);
672 native_app_window_->SetBounds(bounds);
674 OnNativeWindowChanged();
677 void AppWindow::SetNativeWindowFullscreen() {
678 native_app_window_->SetFullscreen(fullscreen_types_);
680 if (cached_always_on_top_)
681 UpdateNativeAlwaysOnTop();
684 bool AppWindow::IntersectsWithTaskbar() const {
685 #if defined(OS_WIN)
686 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
687 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
688 std::vector<gfx::Display> displays = screen->GetAllDisplays();
690 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
691 it != displays.end();
692 ++it) {
693 gfx::Rect taskbar_bounds = it->bounds();
694 taskbar_bounds.Subtract(it->work_area());
695 if (taskbar_bounds.IsEmpty())
696 continue;
698 if (window_bounds.Intersects(taskbar_bounds))
699 return true;
701 #endif
703 return false;
706 void AppWindow::UpdateNativeAlwaysOnTop() {
707 DCHECK(cached_always_on_top_);
708 bool is_on_top = native_app_window_->IsAlwaysOnTop();
709 bool fullscreen = IsFullscreen(fullscreen_types_);
710 bool intersects_taskbar = IntersectsWithTaskbar();
712 if (is_on_top && (fullscreen || intersects_taskbar)) {
713 // When entering fullscreen or overlapping the taskbar, ensure windows are
714 // not always-on-top.
715 native_app_window_->SetAlwaysOnTop(false);
716 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
717 // When exiting fullscreen and moving away from the taskbar, reinstate
718 // always-on-top.
719 native_app_window_->SetAlwaysOnTop(true);
723 void AppWindow::CloseContents(WebContents* contents) {
724 native_app_window_->Close();
727 bool AppWindow::ShouldSuppressDialogs() { return true; }
729 content::ColorChooser* AppWindow::OpenColorChooser(
730 WebContents* web_contents,
731 SkColor initial_color,
732 const std::vector<content::ColorSuggestion>& suggestionss) {
733 return delegate_->ShowColorChooser(web_contents, initial_color);
736 void AppWindow::RunFileChooser(WebContents* tab,
737 const content::FileChooserParams& params) {
738 if (window_type_is_panel()) {
739 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
740 // dialogs to be unhosted but still close with the owning web contents.
741 // crbug.com/172502.
742 LOG(WARNING) << "File dialog opened by panel.";
743 return;
746 delegate_->RunFileChooser(tab, params);
749 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
751 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
752 native_app_window_->SetBounds(pos);
755 void AppWindow::NavigationStateChanged(const content::WebContents* source,
756 unsigned changed_flags) {
757 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
758 native_app_window_->UpdateWindowTitle();
759 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
760 native_app_window_->UpdateWindowIcon();
763 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
764 bool enter_fullscreen) {
765 #if !defined(OS_MACOSX)
766 // Do not enter fullscreen mode if disallowed by pref.
767 // TODO(bartfab): Add a test once it becomes possible to simulate a user
768 // gesture. http://crbug.com/174178
769 PrefService* prefs =
770 extensions::ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
771 browser_context());
772 if (enter_fullscreen && !prefs->GetBoolean(prefs::kAppFullscreenAllowed)) {
773 return;
775 #endif
777 if (!IsExtensionWithPermissionOrSuggestInConsole(
778 APIPermission::kFullscreen,
779 extension_,
780 source->GetRenderViewHost())) {
781 return;
784 if (enter_fullscreen)
785 fullscreen_types_ |= FULLSCREEN_TYPE_HTML_API;
786 else
787 fullscreen_types_ &= ~FULLSCREEN_TYPE_HTML_API;
788 SetNativeWindowFullscreen();
791 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
792 const {
793 return ((fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0);
796 void AppWindow::Observe(int type,
797 const content::NotificationSource& source,
798 const content::NotificationDetails& details) {
799 switch (type) {
800 case chrome::NOTIFICATION_EXTENSION_UNLOADED: {
801 const extensions::Extension* unloaded_extension =
802 content::Details<extensions::UnloadedExtensionInfo>(details)
803 ->extension;
804 if (extension_ == unloaded_extension)
805 native_app_window_->Close();
806 break;
808 case chrome::NOTIFICATION_EXTENSION_INSTALLED: {
809 const extensions::Extension* installed_extension =
810 content::Details<const extensions::InstalledExtensionInfo>(details)
811 ->extension;
812 DCHECK(installed_extension);
813 if (installed_extension->id() == extension_->id())
814 native_app_window_->UpdateShelfMenu();
815 break;
817 case chrome::NOTIFICATION_APP_TERMINATING:
818 native_app_window_->Close();
819 break;
820 default:
821 NOTREACHED() << "Received unexpected notification";
825 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
826 bool blocked) {
827 delegate_->SetWebContentsBlocked(web_contents, blocked);
830 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
831 return delegate_->IsWebContentsVisible(web_contents);
834 extensions::ActiveTabPermissionGranter*
835 AppWindow::GetActiveTabPermissionGranter() {
836 // App windows don't support the activeTab permission.
837 return NULL;
840 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
841 return native_app_window_.get();
844 void AppWindow::AddMessageToDevToolsConsole(ConsoleMessageLevel level,
845 const std::string& message) {
846 content::RenderViewHost* rvh = web_contents()->GetRenderViewHost();
847 rvh->Send(new ExtensionMsg_AddMessageToConsole(
848 rvh->GetRoutingID(), level, message));
851 void AppWindow::SaveWindowPosition() {
852 if (window_key_.empty())
853 return;
854 if (!native_app_window_)
855 return;
857 AppWindowGeometryCache* cache =
858 AppWindowGeometryCache::Get(browser_context());
860 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
861 bounds.Inset(native_app_window_->GetFrameInsets());
862 gfx::Rect screen_bounds =
863 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
864 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
865 cache->SaveGeometry(
866 extension()->id(), window_key_, bounds, screen_bounds, window_state);
869 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
870 const gfx::Rect& cached_bounds,
871 const gfx::Rect& cached_screen_bounds,
872 const gfx::Rect& current_screen_bounds,
873 const gfx::Size& minimum_size,
874 gfx::Rect* bounds) const {
875 *bounds = cached_bounds;
877 // Reposition and resize the bounds if the cached_screen_bounds is different
878 // from the current screen bounds and the current screen bounds doesn't
879 // completely contain the bounds.
880 if (cached_screen_bounds != current_screen_bounds &&
881 !current_screen_bounds.Contains(cached_bounds)) {
882 bounds->set_width(
883 std::max(minimum_size.width(),
884 std::min(bounds->width(), current_screen_bounds.width())));
885 bounds->set_height(
886 std::max(minimum_size.height(),
887 std::min(bounds->height(), current_screen_bounds.height())));
888 bounds->set_x(
889 std::max(current_screen_bounds.x(),
890 std::min(bounds->x(),
891 current_screen_bounds.right() - bounds->width())));
892 bounds->set_y(
893 std::max(current_screen_bounds.y(),
894 std::min(bounds->y(),
895 current_screen_bounds.bottom() - bounds->height())));
899 AppWindow::CreateParams AppWindow::LoadDefaultsAndConstrain(CreateParams params)
900 const {
901 if (params.bounds.width() == 0)
902 params.bounds.set_width(kDefaultWidth);
903 if (params.bounds.height() == 0)
904 params.bounds.set_height(kDefaultHeight);
906 // If left and top are left undefined, the native app window will center
907 // the window on the main screen in a platform-defined manner.
909 // Load cached state if it exists.
910 if (!params.window_key.empty()) {
911 AppWindowGeometryCache* cache =
912 AppWindowGeometryCache::Get(browser_context());
914 gfx::Rect cached_bounds;
915 gfx::Rect cached_screen_bounds;
916 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
917 if (cache->GetGeometry(extension()->id(),
918 params.window_key,
919 &cached_bounds,
920 &cached_screen_bounds,
921 &cached_state)) {
922 // App window has cached screen bounds, make sure it fits on screen in
923 // case the screen resolution changed.
924 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
925 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
926 gfx::Rect current_screen_bounds = display.work_area();
927 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
928 cached_screen_bounds,
929 current_screen_bounds,
930 params.minimum_size,
931 &params.bounds);
932 params.state = cached_state;
936 SizeConstraints size_constraints(params.minimum_size, params.maximum_size);
937 params.bounds.set_size(size_constraints.ClampSize(params.bounds.size()));
938 params.minimum_size = size_constraints.GetMinimumSize();
939 params.maximum_size = size_constraints.GetMaximumSize();
941 return params;
944 // static
945 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
946 const std::vector<extensions::DraggableRegion>& regions) {
947 SkRegion* sk_region = new SkRegion;
948 for (std::vector<extensions::DraggableRegion>::const_iterator iter =
949 regions.begin();
950 iter != regions.end();
951 ++iter) {
952 const extensions::DraggableRegion& region = *iter;
953 sk_region->op(
954 region.bounds.x(),
955 region.bounds.y(),
956 region.bounds.right(),
957 region.bounds.bottom(),
958 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
960 return sk_region;
963 } // namespace apps