Files.app: Dispatch 'drive-connection-changed' event on initialization of VolumeManag...
[chromium-blink-merge.git] / extensions / browser / app_window / app_window.cc
blobfb99b1b055ea89df569172551fc11d00ffb2b819
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/command_line.h"
12 #include "base/strings/string_util.h"
13 #include "base/strings/utf_string_conversions.h"
14 #include "base/values.h"
15 #include "components/web_modal/web_contents_modal_dialog_manager.h"
16 #include "content/public/browser/browser_context.h"
17 #include "content/public/browser/invalidate_type.h"
18 #include "content/public/browser/navigation_entry.h"
19 #include "content/public/browser/render_view_host.h"
20 #include "content/public/browser/resource_dispatcher_host.h"
21 #include "content/public/browser/web_contents.h"
22 #include "content/public/common/content_switches.h"
23 #include "content/public/common/media_stream_request.h"
24 #include "extensions/browser/app_window/app_delegate.h"
25 #include "extensions/browser/app_window/app_web_contents_helper.h"
26 #include "extensions/browser/app_window/app_window_client.h"
27 #include "extensions/browser/app_window/app_window_geometry_cache.h"
28 #include "extensions/browser/app_window/app_window_registry.h"
29 #include "extensions/browser/app_window/native_app_window.h"
30 #include "extensions/browser/app_window/size_constraints.h"
31 #include "extensions/browser/extension_registry.h"
32 #include "extensions/browser/extension_system.h"
33 #include "extensions/browser/extension_web_contents_observer.h"
34 #include "extensions/browser/extensions_browser_client.h"
35 #include "extensions/browser/notification_types.h"
36 #include "extensions/browser/process_manager.h"
37 #include "extensions/browser/suggest_permission_util.h"
38 #include "extensions/browser/view_type_utils.h"
39 #include "extensions/common/draggable_region.h"
40 #include "extensions/common/extension.h"
41 #include "extensions/common/manifest_handlers/icons_handler.h"
42 #include "extensions/common/permissions/permissions_data.h"
43 #include "extensions/common/switches.h"
44 #include "extensions/grit/extensions_browser_resources.h"
45 #include "third_party/skia/include/core/SkRegion.h"
46 #include "ui/base/resource/resource_bundle.h"
47 #include "ui/gfx/screen.h"
49 #if !defined(OS_MACOSX)
50 #include "base/prefs/pref_service.h"
51 #include "extensions/browser/pref_names.h"
52 #endif
54 using content::BrowserContext;
55 using content::ConsoleMessageLevel;
56 using content::WebContents;
57 using web_modal::WebContentsModalDialogHost;
58 using web_modal::WebContentsModalDialogManager;
60 namespace extensions {
62 namespace {
64 const int kDefaultWidth = 512;
65 const int kDefaultHeight = 384;
67 void SetConstraintProperty(const std::string& name,
68 int value,
69 base::DictionaryValue* bounds_properties) {
70 if (value != SizeConstraints::kUnboundedSize)
71 bounds_properties->SetInteger(name, value);
72 else
73 bounds_properties->Set(name, base::Value::CreateNullValue());
76 void SetBoundsProperties(const gfx::Rect& bounds,
77 const gfx::Size& min_size,
78 const gfx::Size& max_size,
79 const std::string& bounds_name,
80 base::DictionaryValue* window_properties) {
81 scoped_ptr<base::DictionaryValue> bounds_properties(
82 new base::DictionaryValue());
84 bounds_properties->SetInteger("left", bounds.x());
85 bounds_properties->SetInteger("top", bounds.y());
86 bounds_properties->SetInteger("width", bounds.width());
87 bounds_properties->SetInteger("height", bounds.height());
89 SetConstraintProperty("minWidth", min_size.width(), bounds_properties.get());
90 SetConstraintProperty(
91 "minHeight", min_size.height(), bounds_properties.get());
92 SetConstraintProperty("maxWidth", max_size.width(), bounds_properties.get());
93 SetConstraintProperty(
94 "maxHeight", max_size.height(), bounds_properties.get());
96 window_properties->Set(bounds_name, bounds_properties.release());
99 // Combines the constraints of the content and window, and returns constraints
100 // for the window.
101 gfx::Size GetCombinedWindowConstraints(const gfx::Size& window_constraints,
102 const gfx::Size& content_constraints,
103 const gfx::Insets& frame_insets) {
104 gfx::Size combined_constraints(window_constraints);
105 if (content_constraints.width() > 0) {
106 combined_constraints.set_width(
107 content_constraints.width() + frame_insets.width());
109 if (content_constraints.height() > 0) {
110 combined_constraints.set_height(
111 content_constraints.height() + frame_insets.height());
113 return combined_constraints;
116 // Combines the constraints of the content and window, and returns constraints
117 // for the content.
118 gfx::Size GetCombinedContentConstraints(const gfx::Size& window_constraints,
119 const gfx::Size& content_constraints,
120 const gfx::Insets& frame_insets) {
121 gfx::Size combined_constraints(content_constraints);
122 if (window_constraints.width() > 0) {
123 combined_constraints.set_width(
124 std::max(0, window_constraints.width() - frame_insets.width()));
126 if (window_constraints.height() > 0) {
127 combined_constraints.set_height(
128 std::max(0, window_constraints.height() - frame_insets.height()));
130 return combined_constraints;
133 } // namespace
135 // AppWindow::BoundsSpecification
137 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
139 AppWindow::BoundsSpecification::BoundsSpecification()
140 : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
142 AppWindow::BoundsSpecification::~BoundsSpecification() {}
144 void AppWindow::BoundsSpecification::ResetBounds() {
145 bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
148 // AppWindow::CreateParams
150 AppWindow::CreateParams::CreateParams()
151 : window_type(AppWindow::WINDOW_TYPE_DEFAULT),
152 frame(AppWindow::FRAME_CHROME),
153 has_frame_color(false),
154 active_frame_color(SK_ColorBLACK),
155 inactive_frame_color(SK_ColorBLACK),
156 alpha_enabled(false),
157 is_ime_window(false),
158 creator_process_id(0),
159 state(ui::SHOW_STATE_DEFAULT),
160 hidden(false),
161 resizable(true),
162 focused(true),
163 always_on_top(false),
164 visible_on_all_workspaces(false) {
167 AppWindow::CreateParams::~CreateParams() {}
169 gfx::Rect AppWindow::CreateParams::GetInitialWindowBounds(
170 const gfx::Insets& frame_insets) const {
171 // Combine into a single window bounds.
172 gfx::Rect combined_bounds(window_spec.bounds);
173 if (content_spec.bounds.x() != BoundsSpecification::kUnspecifiedPosition)
174 combined_bounds.set_x(content_spec.bounds.x() - frame_insets.left());
175 if (content_spec.bounds.y() != BoundsSpecification::kUnspecifiedPosition)
176 combined_bounds.set_y(content_spec.bounds.y() - frame_insets.top());
177 if (content_spec.bounds.width() > 0) {
178 combined_bounds.set_width(
179 content_spec.bounds.width() + frame_insets.width());
181 if (content_spec.bounds.height() > 0) {
182 combined_bounds.set_height(
183 content_spec.bounds.height() + frame_insets.height());
186 // Constrain the bounds.
187 SizeConstraints constraints(
188 GetCombinedWindowConstraints(
189 window_spec.minimum_size, content_spec.minimum_size, frame_insets),
190 GetCombinedWindowConstraints(
191 window_spec.maximum_size, content_spec.maximum_size, frame_insets));
192 combined_bounds.set_size(constraints.ClampSize(combined_bounds.size()));
194 return combined_bounds;
197 gfx::Size AppWindow::CreateParams::GetContentMinimumSize(
198 const gfx::Insets& frame_insets) const {
199 return GetCombinedContentConstraints(window_spec.minimum_size,
200 content_spec.minimum_size,
201 frame_insets);
204 gfx::Size AppWindow::CreateParams::GetContentMaximumSize(
205 const gfx::Insets& frame_insets) const {
206 return GetCombinedContentConstraints(window_spec.maximum_size,
207 content_spec.maximum_size,
208 frame_insets);
211 gfx::Size AppWindow::CreateParams::GetWindowMinimumSize(
212 const gfx::Insets& frame_insets) const {
213 return GetCombinedWindowConstraints(window_spec.minimum_size,
214 content_spec.minimum_size,
215 frame_insets);
218 gfx::Size AppWindow::CreateParams::GetWindowMaximumSize(
219 const gfx::Insets& frame_insets) const {
220 return GetCombinedWindowConstraints(window_spec.maximum_size,
221 content_spec.maximum_size,
222 frame_insets);
225 // AppWindow
227 AppWindow::AppWindow(BrowserContext* context,
228 AppDelegate* app_delegate,
229 const Extension* extension)
230 : browser_context_(context),
231 extension_id_(extension->id()),
232 window_type_(WINDOW_TYPE_DEFAULT),
233 app_delegate_(app_delegate),
234 fullscreen_types_(FULLSCREEN_TYPE_NONE),
235 show_on_first_paint_(false),
236 first_paint_complete_(false),
237 has_been_shown_(false),
238 can_send_events_(false),
239 is_hidden_(false),
240 cached_always_on_top_(false),
241 requested_alpha_enabled_(false),
242 is_ime_window_(false),
243 image_loader_ptr_factory_(this) {
244 ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
245 CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
246 << "Only off the record window may be opened in the guest mode.";
249 void AppWindow::Init(const GURL& url,
250 AppWindowContents* app_window_contents,
251 const CreateParams& params) {
252 // Initialize the render interface and web contents
253 app_window_contents_.reset(app_window_contents);
254 app_window_contents_->Initialize(browser_context(), url);
256 initial_url_ = url;
258 content::WebContentsObserver::Observe(web_contents());
259 SetViewType(web_contents(), VIEW_TYPE_APP_WINDOW);
260 app_delegate_->InitWebContents(web_contents());
262 ExtensionWebContentsObserver::GetForWebContents(web_contents())->
263 dispatcher()->set_delegate(this);
265 WebContentsModalDialogManager::CreateForWebContents(web_contents());
267 web_contents()->SetDelegate(this);
268 WebContentsModalDialogManager::FromWebContents(web_contents())
269 ->SetDelegate(this);
271 // Initialize the window
272 CreateParams new_params = LoadDefaults(params);
273 window_type_ = new_params.window_type;
274 window_key_ = new_params.window_key;
276 // Windows cannot be always-on-top in fullscreen mode for security reasons.
277 cached_always_on_top_ = new_params.always_on_top;
278 if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
279 new_params.always_on_top = false;
281 requested_alpha_enabled_ = new_params.alpha_enabled;
283 is_ime_window_ = params.is_ime_window;
285 AppWindowClient* app_window_client = AppWindowClient::Get();
286 native_app_window_.reset(
287 app_window_client->CreateNativeAppWindow(this, &new_params));
289 helper_.reset(new AppWebContentsHelper(
290 browser_context_, extension_id_, web_contents(), app_delegate_.get()));
292 popup_manager_.reset(
293 new web_modal::PopupManager(GetWebContentsModalDialogHost()));
294 popup_manager_->RegisterWith(web_contents());
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::OnNativeClose() {
449 AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
450 if (app_window_contents_) {
451 WebContentsModalDialogManager* modal_dialog_manager =
452 WebContentsModalDialogManager::FromWebContents(web_contents());
453 if (modal_dialog_manager) // May be null in unit tests.
454 modal_dialog_manager->SetDelegate(nullptr);
455 app_window_contents_->NativeWindowClosed();
457 delete this;
460 void AppWindow::OnNativeWindowChanged() {
461 // This may be called during Init before |native_app_window_| is set.
462 if (!native_app_window_)
463 return;
465 #if defined(OS_MACOSX)
466 // On Mac the user can change the window's fullscreen state. If that has
467 // happened, update AppWindow's internal state.
468 if (native_app_window_->IsFullscreen()) {
469 if (!IsFullscreen())
470 fullscreen_types_ = FULLSCREEN_TYPE_OS;
471 } else {
472 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
475 RestoreAlwaysOnTop(); // Same as in SetNativeWindowFullscreen.
476 #endif
478 SaveWindowPosition();
480 #if defined(OS_WIN)
481 if (cached_always_on_top_ && !IsFullscreen() &&
482 !native_app_window_->IsMaximized() &&
483 !native_app_window_->IsMinimized()) {
484 UpdateNativeAlwaysOnTop();
486 #endif
488 if (app_window_contents_)
489 app_window_contents_->NativeWindowChanged(native_app_window_.get());
492 void AppWindow::OnNativeWindowActivated() {
493 AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
496 content::WebContents* AppWindow::web_contents() const {
497 return app_window_contents_->GetWebContents();
500 const Extension* AppWindow::GetExtension() const {
501 return ExtensionRegistry::Get(browser_context_)
502 ->enabled_extensions()
503 .GetByID(extension_id_);
506 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
508 gfx::NativeWindow AppWindow::GetNativeWindow() {
509 return GetBaseWindow()->GetNativeWindow();
512 gfx::Rect AppWindow::GetClientBounds() const {
513 gfx::Rect bounds = native_app_window_->GetBounds();
514 bounds.Inset(native_app_window_->GetFrameInsets());
515 return bounds;
518 base::string16 AppWindow::GetTitle() const {
519 const Extension* extension = GetExtension();
520 if (!extension)
521 return base::string16();
523 // WebContents::GetTitle() will return the page's URL if there's no <title>
524 // specified. However, we'd prefer to show the name of the extension in that
525 // case, so we directly inspect the NavigationEntry's title.
526 base::string16 title;
527 content::NavigationEntry* entry = web_contents() ?
528 web_contents()->GetController().GetLastCommittedEntry() : nullptr;
529 if (!entry || entry->GetTitle().empty()) {
530 title = base::UTF8ToUTF16(extension->name());
531 } else {
532 title = web_contents()->GetTitle();
534 base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
535 return title;
538 void AppWindow::SetAppIconUrl(const GURL& url) {
539 // Avoid using any previous icons that were being downloaded.
540 image_loader_ptr_factory_.InvalidateWeakPtrs();
542 // Reset |app_icon_image_| to abort pending image load (if any).
543 app_icon_image_.reset();
545 app_icon_url_ = url;
546 web_contents()->DownloadImage(
547 url,
548 true, // is a favicon
549 0, // no maximum size
550 false, // normal cache policy
551 base::Bind(&AppWindow::DidDownloadFavicon,
552 image_loader_ptr_factory_.GetWeakPtr()));
555 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
556 native_app_window_->UpdateShape(region.Pass());
559 void AppWindow::UpdateDraggableRegions(
560 const std::vector<DraggableRegion>& regions) {
561 native_app_window_->UpdateDraggableRegions(regions);
564 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
565 if (image.IsEmpty())
566 return;
567 app_icon_ = image;
568 native_app_window_->UpdateWindowIcon();
569 AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
572 void AppWindow::SetFullscreen(FullscreenType type, bool enable) {
573 DCHECK_NE(FULLSCREEN_TYPE_NONE, type);
575 if (enable) {
576 #if !defined(OS_MACOSX)
577 // Do not enter fullscreen mode if disallowed by pref.
578 // TODO(bartfab): Add a test once it becomes possible to simulate a user
579 // gesture. http://crbug.com/174178
580 if (type != FULLSCREEN_TYPE_FORCED) {
581 PrefService* prefs =
582 ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
583 browser_context());
584 if (!prefs->GetBoolean(pref_names::kAppFullscreenAllowed))
585 return;
587 #endif
588 fullscreen_types_ |= type;
589 } else {
590 fullscreen_types_ &= ~type;
592 SetNativeWindowFullscreen();
595 bool AppWindow::IsFullscreen() const {
596 return fullscreen_types_ != FULLSCREEN_TYPE_NONE;
599 bool AppWindow::IsForcedFullscreen() const {
600 return (fullscreen_types_ & FULLSCREEN_TYPE_FORCED) != 0;
603 bool AppWindow::IsHtmlApiFullscreen() const {
604 return (fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0;
607 void AppWindow::Fullscreen() {
608 SetFullscreen(FULLSCREEN_TYPE_WINDOW_API, true);
611 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
613 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
615 void AppWindow::Restore() {
616 if (IsFullscreen()) {
617 fullscreen_types_ = FULLSCREEN_TYPE_NONE;
618 SetNativeWindowFullscreen();
619 } else {
620 GetBaseWindow()->Restore();
624 void AppWindow::OSFullscreen() {
625 SetFullscreen(FULLSCREEN_TYPE_OS, true);
628 void AppWindow::ForcedFullscreen() {
629 SetFullscreen(FULLSCREEN_TYPE_FORCED, true);
632 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
633 const gfx::Size& max_size) {
634 SizeConstraints constraints(min_size, max_size);
635 native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
636 constraints.GetMaximumSize());
638 gfx::Rect bounds = GetClientBounds();
639 gfx::Size constrained_size = constraints.ClampSize(bounds.size());
640 if (bounds.size() != constrained_size) {
641 bounds.set_size(constrained_size);
642 bounds.Inset(-native_app_window_->GetFrameInsets());
643 native_app_window_->SetBounds(bounds);
645 OnNativeWindowChanged();
648 void AppWindow::Show(ShowType show_type) {
649 app_delegate_->OnShow();
650 bool was_hidden = is_hidden_ || !has_been_shown_;
651 is_hidden_ = false;
653 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
654 switches::kEnableAppsShowOnFirstPaint)) {
655 show_on_first_paint_ = true;
657 if (!first_paint_complete_) {
658 delayed_show_type_ = show_type;
659 return;
663 switch (show_type) {
664 case SHOW_ACTIVE:
665 GetBaseWindow()->Show();
666 break;
667 case SHOW_INACTIVE:
668 GetBaseWindow()->ShowInactive();
669 break;
671 AppWindowRegistry::Get(browser_context_)->AppWindowShown(this, was_hidden);
673 has_been_shown_ = true;
674 SendOnWindowShownIfShown();
677 void AppWindow::Hide() {
678 // This is there to prevent race conditions with Hide() being called before
679 // there was a non-empty paint. It should have no effect in a non-racy
680 // scenario where the application is hiding then showing a window: the second
681 // show will not be delayed.
682 is_hidden_ = true;
683 show_on_first_paint_ = false;
684 GetBaseWindow()->Hide();
685 AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
686 app_delegate_->OnHide();
689 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
690 if (cached_always_on_top_ == always_on_top)
691 return;
693 cached_always_on_top_ = always_on_top;
695 // As a security measure, do not allow fullscreen windows or windows that
696 // overlap the taskbar to be on top. The property will be applied when the
697 // window exits fullscreen and moves away from the taskbar.
698 if (!IsFullscreen() && !IntersectsWithTaskbar())
699 native_app_window_->SetAlwaysOnTop(always_on_top);
701 OnNativeWindowChanged();
704 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
706 void AppWindow::RestoreAlwaysOnTop() {
707 if (cached_always_on_top_)
708 UpdateNativeAlwaysOnTop();
711 void AppWindow::SetInterceptAllKeys(bool want_all_keys) {
712 native_app_window_->SetInterceptAllKeys(want_all_keys);
715 void AppWindow::WindowEventsReady() {
716 can_send_events_ = true;
717 SendOnWindowShownIfShown();
720 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
721 DCHECK(properties);
723 properties->SetBoolean("fullscreen",
724 native_app_window_->IsFullscreenOrPending());
725 properties->SetBoolean("minimized", native_app_window_->IsMinimized());
726 properties->SetBoolean("maximized", native_app_window_->IsMaximized());
727 properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
728 properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
729 properties->SetBoolean(
730 "alphaEnabled",
731 requested_alpha_enabled_ && native_app_window_->CanHaveAlphaEnabled());
733 // These properties are undocumented and are to enable testing. Alpha is
734 // removed to
735 // make the values easier to check.
736 SkColor transparent_white = ~SK_ColorBLACK;
737 properties->SetInteger(
738 "activeFrameColor",
739 native_app_window_->ActiveFrameColor() & transparent_white);
740 properties->SetInteger(
741 "inactiveFrameColor",
742 native_app_window_->InactiveFrameColor() & transparent_white);
744 gfx::Rect content_bounds = GetClientBounds();
745 gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
746 gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
747 SetBoundsProperties(content_bounds,
748 content_min_size,
749 content_max_size,
750 "innerBounds",
751 properties);
753 gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
754 gfx::Rect frame_bounds = native_app_window_->GetBounds();
755 gfx::Size frame_min_size = SizeConstraints::AddFrameToConstraints(
756 content_min_size, frame_insets);
757 gfx::Size frame_max_size = SizeConstraints::AddFrameToConstraints(
758 content_max_size, frame_insets);
759 SetBoundsProperties(frame_bounds,
760 frame_min_size,
761 frame_max_size,
762 "outerBounds",
763 properties);
766 //------------------------------------------------------------------------------
767 // Private methods
769 void AppWindow::DidDownloadFavicon(
770 int id,
771 int http_status_code,
772 const GURL& image_url,
773 const std::vector<SkBitmap>& bitmaps,
774 const std::vector<gfx::Size>& original_bitmap_sizes) {
775 if (image_url != app_icon_url_ || bitmaps.empty())
776 return;
778 // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
779 // whose height >= the preferred size.
780 int largest_index = 0;
781 for (size_t i = 1; i < bitmaps.size(); ++i) {
782 if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
783 break;
784 largest_index = i;
786 const SkBitmap& largest = bitmaps[largest_index];
787 UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
790 void AppWindow::OnExtensionIconImageChanged(IconImage* image) {
791 DCHECK_EQ(app_icon_image_.get(), image);
793 UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
796 void AppWindow::UpdateExtensionAppIcon() {
797 // Avoid using any previous app icons were being downloaded.
798 image_loader_ptr_factory_.InvalidateWeakPtrs();
800 const Extension* extension = GetExtension();
801 if (!extension)
802 return;
804 gfx::ImageSkia app_default_icon =
805 *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
806 IDR_APP_DEFAULT_ICON);
808 app_icon_image_.reset(new IconImage(browser_context(),
809 extension,
810 IconsInfo::GetIcons(extension),
811 app_delegate_->PreferredIconSize(),
812 app_default_icon,
813 this));
815 // Triggers actual image loading with 1x resources. The 2x resource will
816 // be handled by IconImage class when requested.
817 app_icon_image_->image_skia().GetRepresentation(1.0f);
820 void AppWindow::SetNativeWindowFullscreen() {
821 native_app_window_->SetFullscreen(fullscreen_types_);
823 RestoreAlwaysOnTop();
826 bool AppWindow::IntersectsWithTaskbar() const {
827 #if defined(OS_WIN)
828 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
829 gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
830 std::vector<gfx::Display> displays = screen->GetAllDisplays();
832 for (std::vector<gfx::Display>::const_iterator it = displays.begin();
833 it != displays.end();
834 ++it) {
835 gfx::Rect taskbar_bounds = it->bounds();
836 taskbar_bounds.Subtract(it->work_area());
837 if (taskbar_bounds.IsEmpty())
838 continue;
840 if (window_bounds.Intersects(taskbar_bounds))
841 return true;
843 #endif
845 return false;
848 void AppWindow::UpdateNativeAlwaysOnTop() {
849 DCHECK(cached_always_on_top_);
850 bool is_on_top = native_app_window_->IsAlwaysOnTop();
851 bool fullscreen = IsFullscreen();
852 bool intersects_taskbar = IntersectsWithTaskbar();
854 if (is_on_top && (fullscreen || intersects_taskbar)) {
855 // When entering fullscreen or overlapping the taskbar, ensure windows are
856 // not always-on-top.
857 native_app_window_->SetAlwaysOnTop(false);
858 } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
859 // When exiting fullscreen and moving away from the taskbar, reinstate
860 // always-on-top.
861 native_app_window_->SetAlwaysOnTop(true);
865 void AppWindow::SendOnWindowShownIfShown() {
866 if (!can_send_events_ || !has_been_shown_)
867 return;
869 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
870 ::switches::kTestType)) {
871 app_window_contents_->DispatchWindowShownForTests();
875 void AppWindow::CloseContents(WebContents* contents) {
876 native_app_window_->Close();
879 bool AppWindow::ShouldSuppressDialogs(WebContents* source) {
880 return true;
883 content::ColorChooser* AppWindow::OpenColorChooser(
884 WebContents* web_contents,
885 SkColor initial_color,
886 const std::vector<content::ColorSuggestion>& suggestions) {
887 return app_delegate_->ShowColorChooser(web_contents, initial_color);
890 void AppWindow::RunFileChooser(WebContents* tab,
891 const content::FileChooserParams& params) {
892 if (window_type_is_panel()) {
893 // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
894 // dialogs to be unhosted but still close with the owning web contents.
895 // crbug.com/172502.
896 LOG(WARNING) << "File dialog opened by panel.";
897 return;
900 app_delegate_->RunFileChooser(tab, params);
903 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
905 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
906 native_app_window_->SetBounds(pos);
909 void AppWindow::NavigationStateChanged(content::WebContents* source,
910 content::InvalidateTypes changed_flags) {
911 if (changed_flags & content::INVALIDATE_TYPE_TITLE)
912 native_app_window_->UpdateWindowTitle();
913 else if (changed_flags & content::INVALIDATE_TYPE_TAB)
914 native_app_window_->UpdateWindowIcon();
917 void AppWindow::EnterFullscreenModeForTab(content::WebContents* source,
918 const GURL& origin) {
919 ToggleFullscreenModeForTab(source, true);
922 void AppWindow::ExitFullscreenModeForTab(content::WebContents* source) {
923 ToggleFullscreenModeForTab(source, false);
926 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
927 bool enter_fullscreen) {
928 const Extension* extension = GetExtension();
929 if (!extension)
930 return;
932 if (!IsExtensionWithPermissionOrSuggestInConsole(
933 APIPermission::kFullscreen, extension, source->GetMainFrame())) {
934 return;
937 SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
940 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
941 const {
942 return IsHtmlApiFullscreen();
945 blink::WebDisplayMode AppWindow::GetDisplayMode(
946 const content::WebContents* source) const {
947 return IsFullscreen() ? blink::WebDisplayModeFullscreen
948 : blink::WebDisplayModeStandalone;
951 WindowController* AppWindow::GetExtensionWindowController() const {
952 return app_window_contents_->GetWindowController();
955 content::WebContents* AppWindow::GetAssociatedWebContents() const {
956 return web_contents();
959 void AppWindow::OnExtensionUnloaded(BrowserContext* browser_context,
960 const Extension* extension,
961 UnloadedExtensionInfo::Reason reason) {
962 if (extension_id_ == extension->id())
963 native_app_window_->Close();
966 void AppWindow::OnExtensionWillBeInstalled(
967 BrowserContext* browser_context,
968 const Extension* extension,
969 bool is_update,
970 bool from_ephemeral,
971 const std::string& old_name) {
972 if (extension->id() == extension_id())
973 native_app_window_->UpdateShelfMenu();
975 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
976 bool blocked) {
977 app_delegate_->SetWebContentsBlocked(web_contents, blocked);
980 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
981 return app_delegate_->IsWebContentsVisible(web_contents);
984 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
985 return native_app_window_.get();
988 void AppWindow::SaveWindowPosition() {
989 DCHECK(native_app_window_);
990 if (window_key_.empty())
991 return;
993 AppWindowGeometryCache* cache =
994 AppWindowGeometryCache::Get(browser_context());
996 gfx::Rect bounds = native_app_window_->GetRestoredBounds();
997 gfx::Rect screen_bounds =
998 gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
999 ui::WindowShowState window_state = native_app_window_->GetRestoredState();
1000 cache->SaveGeometry(
1001 extension_id(), window_key_, bounds, screen_bounds, window_state);
1004 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1005 const gfx::Rect& cached_bounds,
1006 const gfx::Rect& cached_screen_bounds,
1007 const gfx::Rect& current_screen_bounds,
1008 const gfx::Size& minimum_size,
1009 gfx::Rect* bounds) const {
1010 *bounds = cached_bounds;
1012 // Reposition and resize the bounds if the cached_screen_bounds is different
1013 // from the current screen bounds and the current screen bounds doesn't
1014 // completely contain the bounds.
1015 if (cached_screen_bounds != current_screen_bounds &&
1016 !current_screen_bounds.Contains(cached_bounds)) {
1017 bounds->set_width(
1018 std::max(minimum_size.width(),
1019 std::min(bounds->width(), current_screen_bounds.width())));
1020 bounds->set_height(
1021 std::max(minimum_size.height(),
1022 std::min(bounds->height(), current_screen_bounds.height())));
1023 bounds->set_x(
1024 std::max(current_screen_bounds.x(),
1025 std::min(bounds->x(),
1026 current_screen_bounds.right() - bounds->width())));
1027 bounds->set_y(
1028 std::max(current_screen_bounds.y(),
1029 std::min(bounds->y(),
1030 current_screen_bounds.bottom() - bounds->height())));
1034 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1035 const {
1036 // Ensure width and height are specified.
1037 if (params.content_spec.bounds.width() == 0 &&
1038 params.window_spec.bounds.width() == 0) {
1039 params.content_spec.bounds.set_width(kDefaultWidth);
1041 if (params.content_spec.bounds.height() == 0 &&
1042 params.window_spec.bounds.height() == 0) {
1043 params.content_spec.bounds.set_height(kDefaultHeight);
1046 // If left and top are left undefined, the native app window will center
1047 // the window on the main screen in a platform-defined manner.
1049 // Load cached state if it exists.
1050 if (!params.window_key.empty()) {
1051 AppWindowGeometryCache* cache =
1052 AppWindowGeometryCache::Get(browser_context());
1054 gfx::Rect cached_bounds;
1055 gfx::Rect cached_screen_bounds;
1056 ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1057 if (cache->GetGeometry(extension_id(),
1058 params.window_key,
1059 &cached_bounds,
1060 &cached_screen_bounds,
1061 &cached_state)) {
1062 // App window has cached screen bounds, make sure it fits on screen in
1063 // case the screen resolution changed.
1064 gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1065 gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1066 gfx::Rect current_screen_bounds = display.work_area();
1067 SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1068 params.GetWindowMaximumSize(gfx::Insets()));
1069 AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1070 cached_screen_bounds,
1071 current_screen_bounds,
1072 constraints.GetMinimumSize(),
1073 &params.window_spec.bounds);
1074 params.state = cached_state;
1076 // Since we are restoring a cached state, reset the content bounds spec to
1077 // ensure it is not used.
1078 params.content_spec.ResetBounds();
1082 return params;
1085 // static
1086 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1087 const std::vector<DraggableRegion>& regions) {
1088 SkRegion* sk_region = new SkRegion;
1089 for (std::vector<DraggableRegion>::const_iterator iter = regions.begin();
1090 iter != regions.end();
1091 ++iter) {
1092 const DraggableRegion& region = *iter;
1093 sk_region->op(
1094 region.bounds.x(),
1095 region.bounds.y(),
1096 region.bounds.right(),
1097 region.bounds.bottom(),
1098 region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1100 return sk_region;
1103 } // namespace extensions