Roll src/third_party/WebKit a3b4a2e:7441784 (svn 202551:202552)
[chromium-blink-merge.git] / extensions / browser / app_window / app_window.cc
blob0f2484750816c3e4949b56df57b3d39d99a13815
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/browser/app_window/app_window.h"
7 #include <algorithm>
8 #include <string>
9 #include <vector>
11 #include "base/callback_helpers.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/task_runner.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/values.h"
18 #include "components/web_modal/web_contents_modal_dialog_manager.h"
19 #include "content/public/browser/browser_context.h"
20 #include "content/public/browser/invalidate_type.h"
21 #include "content/public/browser/navigation_entry.h"
22 #include "content/public/browser/render_view_host.h"
23 #include "content/public/browser/resource_dispatcher_host.h"
24 #include "content/public/browser/web_contents.h"
25 #include "content/public/common/content_switches.h"
26 #include "content/public/common/media_stream_request.h"
27 #include "extensions/browser/app_window/app_delegate.h"
28 #include "extensions/browser/app_window/app_web_contents_helper.h"
29 #include "extensions/browser/app_window/app_window_client.h"
30 #include "extensions/browser/app_window/app_window_geometry_cache.h"
31 #include "extensions/browser/app_window/app_window_registry.h"
32 #include "extensions/browser/app_window/native_app_window.h"
33 #include "extensions/browser/app_window/size_constraints.h"
34 #include "extensions/browser/extension_registry.h"
35 #include "extensions/browser/extension_system.h"
36 #include "extensions/browser/extension_web_contents_observer.h"
37 #include "extensions/browser/extensions_browser_client.h"
38 #include "extensions/browser/notification_types.h"
39 #include "extensions/browser/process_manager.h"
40 #include "extensions/browser/suggest_permission_util.h"
41 #include "extensions/browser/view_type_utils.h"
42 #include "extensions/common/draggable_region.h"
43 #include "extensions/common/extension.h"
44 #include "extensions/common/manifest_handlers/icons_handler.h"
45 #include "extensions/common/permissions/permissions_data.h"
46 #include "extensions/common/switches.h"
47 #include "extensions/grit/extensions_browser_resources.h"
48 #include "third_party/skia/include/core/SkRegion.h"
49 #include "ui/base/resource/resource_bundle.h"
50 #include "ui/gfx/screen.h"
52 #if !defined(OS_MACOSX)
53 #include "base/prefs/pref_service.h"
54 #include "extensions/browser/pref_names.h"
55 #endif
57 using content::BrowserContext;
58 using content::ConsoleMessageLevel;
59 using content::WebContents;
60 using web_modal::WebContentsModalDialogHost;
61 using web_modal::WebContentsModalDialogManager;
63 namespace extensions {
65 namespace {
67 const int kDefaultWidth = 512;
68 const int kDefaultHeight = 384;
70 void SetConstraintProperty(const std::string& name,
71 int value,
72 base::DictionaryValue* bounds_properties) {
73 if (value != SizeConstraints::kUnboundedSize)
74 bounds_properties->SetInteger(name, value);
75 else
76 bounds_properties->Set(name, base::Value::CreateNullValue());
79 void SetBoundsProperties(const gfx::Rect& bounds,
80 const gfx::Size& min_size,
81 const gfx::Size& max_size,
82 const std::string& bounds_name,
83 base::DictionaryValue* window_properties) {
84 scoped_ptr<base::DictionaryValue> bounds_properties(
85 new base::DictionaryValue());
87 bounds_properties->SetInteger("left", bounds.x());
88 bounds_properties->SetInteger("top", bounds.y());
89 bounds_properties->SetInteger("width", bounds.width());
90 bounds_properties->SetInteger("height", bounds.height());
92 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
93 SetConstraintProperty(
94 "minHeight", min_size.height(), bounds_properties.get());
95 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
96 SetConstraintProperty(
97 "maxHeight", max_size.height(), bounds_properties.get());
99 window_properties->Set(bounds_name, bounds_properties.release());
102 // Combines the constraints of the content and window, and returns constraints
103 // for the window.
104 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
105 const gfx::Size& content_constraints,
106 const gfx::Insets& frame_insets) {
107 gfx::Size combined_constraints(window_constraints);
108 if (content_constraints.width() > 0) {
109 combined_constraints.set_width(
110 content_constraints.width() + frame_insets.width());
112 if (content_constraints.height() > 0) {
113 combined_constraints.set_height(
114 content_constraints.height() + frame_insets.height());
116 return combined_constraints;
119 // Combines the constraints of the content and window, and returns constraints
120 // for the content.
121 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
122 const gfx::Size& content_constraints,
123 const gfx::Insets& frame_insets) {
124 gfx::Size combined_constraints(content_constraints);
125 if (window_constraints.width() > 0) {
126 combined_constraints.set_width(
127 std::max(0, window_constraints.width() - frame_insets.width()));
129 if (window_constraints.height() > 0) {
130 combined_constraints.set_height(
131 std::max(0, window_constraints.height() - frame_insets.height()));
133 return combined_constraints;
136 } // namespace
138 // AppWindow::BoundsSpecification
140 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
142 AppWindow::BoundsSpecification::BoundsSpecification()
143 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
145 AppWindow::BoundsSpecification::~BoundsSpecification() {}
147 void AppWindow::BoundsSpecification::ResetBounds() {
148 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
151 // AppWindow::CreateParams
153 AppWindow::CreateParams::CreateParams()
154 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
155 frame(AppWindow::FRAME_CHROME),
156 has_frame_color(false),
157 active_frame_color(SK_ColorBLACK),
158 inactive_frame_color(SK_ColorBLACK),
159 alpha_enabled(false),
160 is_ime_window(false),
161 creator_process_id(0),
162 state(ui::SHOW_STATE_DEFAULT),
163 hidden(false),
164 resizable(true),
165 focused(true),
166 always_on_top(false),
167 visible_on_all_workspaces(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
230 AppWindow::AppWindow(BrowserContext* context,
231 AppDelegate* app_delegate,
232 const Extension* extension)
233 : browser_context_(context),
234 extension_id_(extension->id()),
235 window_type_(WINDOW_TYPE_DEFAULT),
236 app_delegate_(app_delegate),
237 fullscreen_types_(FULLSCREEN_TYPE_NONE),
238 show_on_first_paint_(false),
239 first_paint_complete_(false),
240 has_been_shown_(false),
241 can_send_events_(false),
242 is_hidden_(false),
243 delayed_show_type_(SHOW_ACTIVE),
244 cached_always_on_top_(false),
245 requested_alpha_enabled_(false),
246 is_ime_window_(false),
247 image_loader_ptr_factory_(this) {
248 ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
249 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
250 << "Only off the record window may be opened in the guest mode.";
253 void AppWindow::Init(const GURL& url,
254 AppWindowContents* app_window_contents,
255 const CreateParams& params) {
256 // Initialize the render interface and web contents
257 app_window_contents_.reset(app_window_contents);
258 app_window_contents_->Initialize(browser_context(), url);
260 initial_url_ = url;
262 content::WebContentsObserver::Observe(web_contents());
263 SetViewType(web_contents(), VIEW_TYPE_APP_WINDOW);
264 app_delegate_->InitWebContents(web_contents());
266 ExtensionWebContentsObserver::GetForWebContents(web_contents())->
267 dispatcher()->set_delegate(this);
269 WebContentsModalDialogManager::CreateForWebContents(web_contents());
271 web_contents()->SetDelegate(this);
272 WebContentsModalDialogManager::FromWebContents(web_contents())
273 ->SetDelegate(this);
275 // Initialize the window
276 CreateParams new_params = LoadDefaults(params);
277 window_type_ = new_params.window_type;
278 window_key_ = new_params.window_key;
280 // Windows cannot be always-on-top in fullscreen mode for security reasons.
281 cached_always_on_top_ = new_params.always_on_top;
282 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
283 new_params.always_on_top = false;
285 requested_alpha_enabled_ = new_params.alpha_enabled;
287 is_ime_window_ = params.is_ime_window;
289 AppWindowClient* app_window_client = AppWindowClient::Get();
290 native_app_window_.reset(
291 app_window_client->CreateNativeAppWindow(this, &new_params));
293 helper_.reset(new AppWebContentsHelper(
294 browser_context_, extension_id_, web_contents(), app_delegate_.get()));
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);
308 // These states may cause the window to show, so they are ignored if the
309 // window is initially hidden.
310 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
311 Fullscreen();
312 else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
313 Maximize();
314 else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
315 Minimize();
318 OnNativeWindowChanged();
320 ExtensionRegistry::Get(browser_context_)->AddObserver(this);
322 // Close when the browser process is exiting.
323 app_delegate_->SetTerminatingCallback(
324 base::Bind(&NativeAppWindow::Close,
325 base::Unretained(native_app_window_.get())));
327 app_window_contents_->LoadContents(new_params.creator_process_id);
329 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
330 extensions::switches::kEnableAppsShowOnFirstPaint)) {
331 // We want to show the window only when the content has been painted. For
332 // that to happen, we need to define a size for the content, otherwise the
333 // layout will happen in a 0x0 area.
334 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
335 gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
336 initial_bounds.Inset(frame_insets);
337 app_delegate_->ResizeWebContents(web_contents(), initial_bounds.size());
341 AppWindow::~AppWindow() {
342 ExtensionRegistry::Get(browser_context_)->RemoveObserver(this);
345 void AppWindow::RequestMediaAccessPermission(
346 content::WebContents* web_contents,
347 const content::MediaStreamRequest& request,
348 const content::MediaResponseCallback& callback) {
349 DCHECK_EQ(AppWindow::web_contents(), web_contents);
350 helper_->RequestMediaAccessPermission(request, callback);
353 bool AppWindow::CheckMediaAccessPermission(content::WebContents* web_contents,
354 const GURL& security_origin,
355 content::MediaStreamType type) {
356 DCHECK_EQ(AppWindow::web_contents(), web_contents);
357 return helper_->CheckMediaAccessPermission(security_origin, type);
360 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
361 const content::OpenURLParams& params) {
362 DCHECK_EQ(web_contents(), source);
363 return helper_->OpenURLFromTab(params);
366 void AppWindow::AddNewContents(WebContents* source,
367 WebContents* new_contents,
368 WindowOpenDisposition disposition,
369 const gfx::Rect& initial_rect,
370 bool user_gesture,
371 bool* was_blocked) {
372 DCHECK(new_contents->GetBrowserContext() == browser_context_);
373 app_delegate_->AddNewContents(browser_context_,
374 new_contents,
375 disposition,
376 initial_rect,
377 user_gesture,
378 was_blocked);
381 bool AppWindow::PreHandleKeyboardEvent(
382 content::WebContents* source,
383 const content::NativeWebKeyboardEvent& event,
384 bool* is_keyboard_shortcut) {
385 const Extension* extension = GetExtension();
386 if (!extension)
387 return false;
389 // Here, we can handle a key event before the content gets it. When we are
390 // fullscreen and it is not forced, we want to allow the user to leave
391 // when ESC is pressed.
392 // However, if the application has the "overrideEscFullscreen" permission, we
393 // should let it override that behavior.
394 // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
395 // action is not prevented.
396 // Thus, we should handle the KeyEvent here only if the permission is not set.
397 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
398 !IsForcedFullscreen() &&
399 !extension->permissions_data()->HasAPIPermission(
400 APIPermission::kOverrideEscFullscreen)) {
401 Restore();
402 return true;
405 return false;
408 void AppWindow::HandleKeyboardEvent(
409 WebContents* source,
410 const content::NativeWebKeyboardEvent& event) {
411 // If the window is currently fullscreen and not forced, ESC should leave
412 // fullscreen. If this code is being called for ESC, that means that the
413 // KeyEvent's default behavior was not prevented by the content.
414 if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
415 !IsForcedFullscreen()) {
416 Restore();
417 return;
420 native_app_window_->HandleKeyboardEvent(event);
423 void AppWindow::RequestToLockMouse(WebContents* web_contents,
424 bool user_gesture,
425 bool last_unlocked_by_target) {
426 DCHECK_EQ(AppWindow::web_contents(), web_contents);
427 helper_->RequestToLockMouse();
430 bool AppWindow::PreHandleGestureEvent(WebContents* source,
431 const blink::WebGestureEvent& event) {
432 return AppWebContentsHelper::ShouldSuppressGestureEvent(event);
435 void AppWindow::RenderViewCreated(content::RenderViewHost* render_view_host) {
436 app_delegate_->RenderViewCreated(render_view_host);
439 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
440 first_paint_complete_ = true;
441 if (show_on_first_paint_) {
442 DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
443 delayed_show_type_ == SHOW_INACTIVE);
444 Show(delayed_show_type_);
448 void AppWindow::SetOnFirstCommitCallback(const base::Closure& callback) {
449 DCHECK(on_first_commit_callback_.is_null());
450 on_first_commit_callback_ = callback;
453 void AppWindow::OnReadyToCommitFirstNavigation() {
454 CHECK(base::CommandLine::ForCurrentProcess()->HasSwitch(
455 ::switches::kEnableBrowserSideNavigation));
456 WindowEventsReady();
457 if (on_first_commit_callback_.is_null())
458 return;
459 // It is important that the callback executes after the calls to
460 // WebContentsObserver::ReadyToCommitNavigation have been processed. The
461 // CommitNavigation IPC that will properly set up the renderer will only be
462 // sent after these, and it must be sent before the callback gets to run,
463 // hence the use of PostTask.
464 base::ThreadTaskRunnerHandle::Get()->PostTask(
465 FROM_HERE, base::ResetAndReturn(&on_first_commit_callback_));
468 void AppWindow::OnNativeClose() {
469 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
470 if (app_window_contents_) {
471 WebContentsModalDialogManager* modal_dialog_manager =
472 WebContentsModalDialogManager::FromWebContents(web_contents());
473 if (modal_dialog_manager) // May be null in unit tests.
474 modal_dialog_manager->SetDelegate(nullptr);
475 app_window_contents_->NativeWindowClosed();
477 delete this;
480 void AppWindow::OnNativeWindowChanged() {
481 // This may be called during Init before |native_app_window_| is set.
482 if (!native_app_window_)
483 return;
485 #if defined(OS_MACOSX)
486 // On Mac the user can change the window's fullscreen state. If that has
487 // happened, update AppWindow's internal state.
488 if (native_app_window_->IsFullscreen()) {
489 if (!IsFullscreen())
490 fullscreen_types_ = FULLSCREEN_TYPE_OS;
491 } else {
492 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
495 RestoreAlwaysOnTop(); // Same as in SetNativeWindowFullscreen.
496 #endif
498 SaveWindowPosition();
500 #if defined(OS_WIN)
501 if (cached_always_on_top_ && !IsFullscreen() &&
502 !native_app_window_->IsMaximized() &&
503 !native_app_window_->IsMinimized()) {
504 UpdateNativeAlwaysOnTop();
506 #endif
508 if (app_window_contents_)
509 app_window_contents_->NativeWindowChanged(native_app_window_.get());
512 void AppWindow::OnNativeWindowActivated() {
513 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
516 content::WebContents* AppWindow::web_contents() const {
517 return app_window_contents_->GetWebContents();
520 const Extension* AppWindow::GetExtension() const {
521 return ExtensionRegistry::Get(browser_context_)
522 ->enabled_extensions()
523 .GetByID(extension_id_);
526 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
528 gfx::NativeWindow AppWindow::GetNativeWindow() {
529 return GetBaseWindow()->GetNativeWindow();
532 gfx::Rect AppWindow::GetClientBounds() const {
533 gfx::Rect bounds = native_app_window_->GetBounds();
534 bounds.Inset(native_app_window_->GetFrameInsets());
535 return bounds;
538 base::string16 AppWindow::GetTitle() const {
539 const Extension* extension = GetExtension();
540 if (!extension)
541 return base::string16();
543 // WebContents::GetTitle() will return the page's URL if there's no <title>
544 // specified. However, we'd prefer to show the name of the extension in that
545 // case, so we directly inspect the NavigationEntry's title.
546 base::string16 title;
547 content::NavigationEntry* entry = web_contents() ?
548 web_contents()->GetController().GetLastCommittedEntry() : nullptr;
549 if (!entry || entry->GetTitle().empty()) {
550 title = base::UTF8ToUTF16(extension->name());
551 } else {
552 title = web_contents()->GetTitle();
554 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
555 return title;
558 void AppWindow::SetAppIconUrl(const GURL& url) {
559 // Avoid using any previous icons that were being downloaded.
560 image_loader_ptr_factory_.InvalidateWeakPtrs();
562 // Reset |app_icon_image_| to abort pending image load (if any).
563 app_icon_image_.reset();
565 app_icon_url_ = url;
566 web_contents()->DownloadImage(
567 url,
568 true, // is a favicon
569 0, // no maximum size
570 false, // normal cache policy
571 base::Bind(&AppWindow::DidDownloadFavicon,
572 image_loader_ptr_factory_.GetWeakPtr()));
575 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
576 native_app_window_->UpdateShape(region.Pass());
579 void AppWindow::UpdateDraggableRegions(
580 const std::vector<DraggableRegion>& regions) {
581 native_app_window_->UpdateDraggableRegions(regions);
584 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
585 if (image.IsEmpty())
586 return;
587 app_icon_ = image;
588 native_app_window_->UpdateWindowIcon();
589 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
592 void AppWindow::SetFullscreen(FullscreenType type, bool enable) {
593 DCHECK_NE(FULLSCREEN_TYPE_NONE, type);
595 if (enable) {
596 #if !defined(OS_MACOSX)
597 // Do not enter fullscreen mode if disallowed by pref.
598 // TODO(bartfab): Add a test once it becomes possible to simulate a user
599 // gesture. http://crbug.com/174178
600 if (type != FULLSCREEN_TYPE_FORCED) {
601 PrefService* prefs =
602 ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
603 browser_context());
604 if (!prefs->GetBoolean(pref_names::kAppFullscreenAllowed))
605 return;
607 #endif
608 fullscreen_types_ |= type;
609 } else {
610 fullscreen_types_ &= ~type;
612 SetNativeWindowFullscreen();
615 bool AppWindow::IsFullscreen() const {
616 return fullscreen_types_ != FULLSCREEN_TYPE_NONE;
619 bool AppWindow::IsForcedFullscreen() const {
620 return (fullscreen_types_ & FULLSCREEN_TYPE_FORCED) != 0;
623 bool AppWindow::IsHtmlApiFullscreen() const {
624 return (fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0;
627 void AppWindow::Fullscreen() {
628 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API, true);
631 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
633 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
635 void AppWindow::Restore() {
636 if (IsFullscreen()) {
637 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
638 SetNativeWindowFullscreen();
639 } else {
640 GetBaseWindow()->Restore();
644 void AppWindow::OSFullscreen() {
645 SetFullscreen(FULLSCREEN_TYPE_OS, true);
648 void AppWindow::ForcedFullscreen() {
649 SetFullscreen(FULLSCREEN_TYPE_FORCED, true);
652 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
653 const gfx::Size& max_size) {
654 SizeConstraints constraints(min_size, max_size);
655 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
656 constraints.GetMaximumSize());
658 gfx::Rect bounds = GetClientBounds();
659 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
660 if (bounds.size() != constrained_size) {
661 bounds.set_size(constrained_size);
662 bounds.Inset(-native_app_window_->GetFrameInsets());
663 native_app_window_->SetBounds(bounds);
665 OnNativeWindowChanged();
668 void AppWindow::Show(ShowType show_type) {
669 app_delegate_->OnShow();
670 bool was_hidden = is_hidden_ || !has_been_shown_;
671 is_hidden_ = false;
673 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
674 switches::kEnableAppsShowOnFirstPaint)) {
675 show_on_first_paint_ = true;
677 if (!first_paint_complete_) {
678 delayed_show_type_ = show_type;
679 return;
683 switch (show_type) {
684 case SHOW_ACTIVE:
685 GetBaseWindow()->Show();
686 break;
687 case SHOW_INACTIVE:
688 GetBaseWindow()->ShowInactive();
689 break;
691 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this, was_hidden);
693 has_been_shown_ = true;
694 SendOnWindowShownIfShown();
697 void AppWindow::Hide() {
698 // This is there to prevent race conditions with Hide() being called before
699 // there was a non-empty paint. It should have no effect in a non-racy
700 // scenario where the application is hiding then showing a window: the second
701 // show will not be delayed.
702 is_hidden_ = true;
703 show_on_first_paint_ = false;
704 GetBaseWindow()->Hide();
705 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
706 app_delegate_->OnHide();
709 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
710 if (cached_always_on_top_ == always_on_top)
711 return;
713 cached_always_on_top_ = always_on_top;
715 // As a security measure, do not allow fullscreen windows or windows that
716 // overlap the taskbar to be on top. The property will be applied when the
717 // window exits fullscreen and moves away from the taskbar.
718 if (!IsFullscreen() && !IntersectsWithTaskbar())
719 native_app_window_->SetAlwaysOnTop(always_on_top);
721 OnNativeWindowChanged();
724 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
726 void AppWindow::RestoreAlwaysOnTop() {
727 if (cached_always_on_top_)
728 UpdateNativeAlwaysOnTop();
731 void AppWindow::WindowEventsReady() {
732 can_send_events_ = true;
733 SendOnWindowShownIfShown();
736 void AppWindow::NotifyRenderViewReady() {
737 if (app_window_contents_)
738 app_window_contents_->OnWindowReady();
741 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
742 DCHECK(properties);
744 properties->SetBoolean("fullscreen",
745 native_app_window_->IsFullscreenOrPending());
746 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
747 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
748 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
749 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
750 properties->SetBoolean(
751 "alphaEnabled",
752 requested_alpha_enabled_ && native_app_window_->CanHaveAlphaEnabled());
754 // These properties are undocumented and are to enable testing. Alpha is
755 // removed to
756 // make the values easier to check.
757 SkColor transparent_white = ~SK_ColorBLACK;
758 properties->SetInteger(
759 "activeFrameColor",
760 native_app_window_->ActiveFrameColor() & transparent_white);
761 properties->SetInteger(
762 "inactiveFrameColor",
763 native_app_window_->InactiveFrameColor() & transparent_white);
765 gfx::Rect content_bounds = GetClientBounds();
766 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
767 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
768 SetBoundsProperties(content_bounds,
769 content_min_size,
770 content_max_size,
771 "innerBounds",
772 properties);
774 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
775 gfx::Rect frame_bounds = native_app_window_->GetBounds();
776 gfx::Size frame_min_size = SizeConstraints::AddFrameToConstraints(
777 content_min_size, frame_insets);
778 gfx::Size frame_max_size = SizeConstraints::AddFrameToConstraints(
779 content_max_size, frame_insets);
780 SetBoundsProperties(frame_bounds,
781 frame_min_size,
782 frame_max_size,
783 "outerBounds",
784 properties);
787 //------------------------------------------------------------------------------
788 // Private methods
790 void AppWindow::DidDownloadFavicon(
791 int id,
792 int http_status_code,
793 const GURL& image_url,
794 const std::vector<SkBitmap>& bitmaps,
795 const std::vector<gfx::Size>& original_bitmap_sizes) {
796 if (image_url != app_icon_url_ || bitmaps.empty())
797 return;
799 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
800 // whose height >= the preferred size.
801 int largest_index = 0;
802 for (size_t i = 1; i < bitmaps.size(); ++i) {
803 if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
804 break;
805 largest_index = i;
807 const SkBitmap& largest = bitmaps[largest_index];
808 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
811 void AppWindow::OnExtensionIconImageChanged(IconImage* image) {
812 DCHECK_EQ(app_icon_image_.get(), image);
814 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
817 void AppWindow::UpdateExtensionAppIcon() {
818 // Avoid using any previous app icons were being downloaded.
819 image_loader_ptr_factory_.InvalidateWeakPtrs();
821 const Extension* extension = GetExtension();
822 if (!extension)
823 return;
825 gfx::ImageSkia app_default_icon =
826 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
827 IDR_APP_DEFAULT_ICON);
829 app_icon_image_.reset(new IconImage(browser_context(),
830 extension,
831 IconsInfo::GetIcons(extension),
832 app_delegate_->PreferredIconSize(),
833 app_default_icon,
834 this));
836 // Triggers actual image loading with 1x resources. The 2x resource will
837 // be handled by IconImage class when requested.
838 app_icon_image_->image_skia().GetRepresentation(1.0f);
841 void AppWindow::SetNativeWindowFullscreen() {
842 native_app_window_->SetFullscreen(fullscreen_types_);
844 RestoreAlwaysOnTop();
847 bool AppWindow::IntersectsWithTaskbar() const {
848 #if defined(OS_WIN)
849 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
850 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
851 std::vector<gfx::Display> displays = screen->GetAllDisplays();
853 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
854 it != displays.end();
855 ++it) {
856 gfx::Rect taskbar_bounds = it->bounds();
857 taskbar_bounds.Subtract(it->work_area());
858 if (taskbar_bounds.IsEmpty())
859 continue;
861 if (window_bounds.Intersects(taskbar_bounds))
862 return true;
864 #endif
866 return false;
869 void AppWindow::UpdateNativeAlwaysOnTop() {
870 DCHECK(cached_always_on_top_);
871 bool is_on_top = native_app_window_->IsAlwaysOnTop();
872 bool fullscreen = IsFullscreen();
873 bool intersects_taskbar = IntersectsWithTaskbar();
875 if (is_on_top && (fullscreen || intersects_taskbar)) {
876 // When entering fullscreen or overlapping the taskbar, ensure windows are
877 // not always-on-top.
878 native_app_window_->SetAlwaysOnTop(false);
879 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
880 // When exiting fullscreen and moving away from the taskbar, reinstate
881 // always-on-top.
882 native_app_window_->SetAlwaysOnTop(true);
886 void AppWindow::SendOnWindowShownIfShown() {
887 if (!can_send_events_ || !has_been_shown_)
888 return;
890 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
891 ::switches::kTestType)) {
892 app_window_contents_->DispatchWindowShownForTests();
896 void AppWindow::CloseContents(WebContents* contents) {
897 native_app_window_->Close();
900 bool AppWindow::ShouldSuppressDialogs(WebContents* source) {
901 return true;
904 content::ColorChooser* AppWindow::OpenColorChooser(
905 WebContents* web_contents,
906 SkColor initial_color,
907 const std::vector<content::ColorSuggestion>& suggestions) {
908 return app_delegate_->ShowColorChooser(web_contents, initial_color);
911 void AppWindow::RunFileChooser(WebContents* tab,
912 const content::FileChooserParams& params) {
913 if (window_type_is_panel()) {
914 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
915 // dialogs to be unhosted but still close with the owning web contents.
916 // crbug.com/172502.
917 LOG(WARNING) << "File dialog opened by panel.";
918 return;
921 app_delegate_->RunFileChooser(tab, params);
924 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
926 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
927 native_app_window_->SetBounds(pos);
930 void AppWindow::NavigationStateChanged(content::WebContents* source,
931 content::InvalidateTypes changed_flags) {
932 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
933 native_app_window_->UpdateWindowTitle();
934 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
935 native_app_window_->UpdateWindowIcon();
938 void AppWindow::EnterFullscreenModeForTab(content::WebContents* source,
939 const GURL& origin) {
940 ToggleFullscreenModeForTab(source, true);
943 void AppWindow::ExitFullscreenModeForTab(content::WebContents* source) {
944 ToggleFullscreenModeForTab(source, false);
947 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
948 bool enter_fullscreen) {
949 const Extension* extension = GetExtension();
950 if (!extension)
951 return;
953 if (!IsExtensionWithPermissionOrSuggestInConsole(
954 APIPermission::kFullscreen, extension, source->GetMainFrame())) {
955 return;
958 SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
961 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
962 const {
963 return IsHtmlApiFullscreen();
966 blink::WebDisplayMode AppWindow::GetDisplayMode(
967 const content::WebContents* source) const {
968 return IsFullscreen() ? blink::WebDisplayModeFullscreen
969 : blink::WebDisplayModeStandalone;
972 WindowController* AppWindow::GetExtensionWindowController() const {
973 return app_window_contents_->GetWindowController();
976 content::WebContents* AppWindow::GetAssociatedWebContents() const {
977 return web_contents();
980 void AppWindow::OnExtensionUnloaded(BrowserContext* browser_context,
981 const Extension* extension,
982 UnloadedExtensionInfo::Reason reason) {
983 if (extension_id_ == extension->id())
984 native_app_window_->Close();
987 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
988 bool blocked) {
989 app_delegate_->SetWebContentsBlocked(web_contents, blocked);
992 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
993 return app_delegate_->IsWebContentsVisible(web_contents);
996 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
997 return native_app_window_.get();
1000 void AppWindow::SaveWindowPosition() {
1001 DCHECK(native_app_window_);
1002 if (window_key_.empty())
1003 return;
1005 AppWindowGeometryCache* cache =
1006 AppWindowGeometryCache::Get(browser_context());
1008 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
1009 gfx::Rect screen_bounds =
1010 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
1011 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1012 cache->SaveGeometry(
1013 extension_id(), window_key_, bounds, screen_bounds, window_state);
1016 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1017 const gfx::Rect& cached_bounds,
1018 const gfx::Rect& cached_screen_bounds,
1019 const gfx::Rect& current_screen_bounds,
1020 const gfx::Size& minimum_size,
1021 gfx::Rect* bounds) const {
1022 *bounds = cached_bounds;
1024 // Reposition and resize the bounds if the cached_screen_bounds is different
1025 // from the current screen bounds and the current screen bounds doesn't
1026 // completely contain the bounds.
1027 if (cached_screen_bounds != current_screen_bounds &&
1028 !current_screen_bounds.Contains(cached_bounds)) {
1029 bounds->set_width(
1030 std::max(minimum_size.width(),
1031 std::min(bounds->width(), current_screen_bounds.width())));
1032 bounds->set_height(
1033 std::max(minimum_size.height(),
1034 std::min(bounds->height(), current_screen_bounds.height())));
1035 bounds->set_x(
1036 std::max(current_screen_bounds.x(),
1037 std::min(bounds->x(),
1038 current_screen_bounds.right() - bounds->width())));
1039 bounds->set_y(
1040 std::max(current_screen_bounds.y(),
1041 std::min(bounds->y(),
1042 current_screen_bounds.bottom() - bounds->height())));
1046 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1047 const {
1048 // Ensure width and height are specified.
1049 if (params.content_spec.bounds.width() == 0 &&
1050 params.window_spec.bounds.width() == 0) {
1051 params.content_spec.bounds.set_width(kDefaultWidth);
1053 if (params.content_spec.bounds.height() == 0 &&
1054 params.window_spec.bounds.height() == 0) {
1055 params.content_spec.bounds.set_height(kDefaultHeight);
1058 // If left and top are left undefined, the native app window will center
1059 // the window on the main screen in a platform-defined manner.
1061 // Load cached state if it exists.
1062 if (!params.window_key.empty()) {
1063 AppWindowGeometryCache* cache =
1064 AppWindowGeometryCache::Get(browser_context());
1066 gfx::Rect cached_bounds;
1067 gfx::Rect cached_screen_bounds;
1068 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1069 if (cache->GetGeometry(extension_id(),
1070 params.window_key,
1071 &cached_bounds,
1072 &cached_screen_bounds,
1073 &cached_state)) {
1074 // App window has cached screen bounds, make sure it fits on screen in
1075 // case the screen resolution changed.
1076 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1077 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1078 gfx::Rect current_screen_bounds = display.work_area();
1079 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1080 params.GetWindowMaximumSize(gfx::Insets()));
1081 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1082 cached_screen_bounds,
1083 current_screen_bounds,
1084 constraints.GetMinimumSize(),
1085 &params.window_spec.bounds);
1086 params.state = cached_state;
1088 // Since we are restoring a cached state, reset the content bounds spec to
1089 // ensure it is not used.
1090 params.content_spec.ResetBounds();
1094 return params;
1097 // static
1098 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1099 const std::vector<DraggableRegion>& regions) {
1100 SkRegion* sk_region = new SkRegion;
1101 for (std::vector<DraggableRegion>::const_iterator iter = regions.begin();
1102 iter != regions.end();
1103 ++iter) {
1104 const DraggableRegion& region = *iter;
1105 sk_region->op(
1106 region.bounds.x(),
1107 region.bounds.y(),
1108 region.bounds.right(),
1109 region.bounds.bottom(),
1110 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1112 return sk_region;
1115 } // namespace extensions