Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / extensions / browser / app_window / app_window.cc
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.
4
5 #include "extensions/browser/app_window/app_window.h"
6
7 #include <algorithm>
8 #include <string>
9 #include <vector>
10
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/notification_details.h"
20 #include "content/public/browser/notification_service.h"
21 #include "content/public/browser/notification_source.h"
22 #include "content/public/browser/notification_types.h"
23 #include "content/public/browser/render_view_host.h"
24 #include "content/public/browser/resource_dispatcher_host.h"
25 #include "content/public/browser/web_contents.h"
26 #include "content/public/common/content_switches.h"
27 #include "content/public/common/media_stream_request.h"
28 #include "extensions/browser/app_window/app_delegate.h"
29 #include "extensions/browser/app_window/app_web_contents_helper.h"
30 #include "extensions/browser/app_window/app_window_client.h"
31 #include "extensions/browser/app_window/app_window_geometry_cache.h"
32 #include "extensions/browser/app_window/app_window_registry.h"
33 #include "extensions/browser/app_window/native_app_window.h"
34 #include "extensions/browser/app_window/size_constraints.h"
35 #include "extensions/browser/extension_registry.h"
36 #include "extensions/browser/extension_system.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"
51
52 #if !defined(OS_MACOSX)
53 #include "base/prefs/pref_service.h"
54 #include "extensions/browser/pref_names.h"
55 #endif
56
57 using content::BrowserContext;
58 using content::ConsoleMessageLevel;
59 using content::WebContents;
60 using web_modal::WebContentsModalDialogHost;
61 using web_modal::WebContentsModalDialogManager;
62
63 namespace extensions {
64
65 namespace {
66
67 const int kDefaultWidth = 512;
68 const int kDefaultHeight = 384;
69
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());
77 }
78
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());
86
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());
91
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());
98
99   window_properties->Set(bounds_name, bounds_properties.release());
100 }
101
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());
111   }
112   if (content_constraints.height() > 0) {
113     combined_constraints.set_height(
114         content_constraints.height() + frame_insets.height());
115   }
116   return combined_constraints;
117 }
118
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()));
128   }
129   if (window_constraints.height() > 0) {
130     combined_constraints.set_height(
131         std::max(0, window_constraints.height() - frame_insets.height()));
132   }
133   return combined_constraints;
134 }
135
136 }  // namespace
137
138 // AppWindow::BoundsSpecification
139
140 const int AppWindow::BoundsSpecification::kUnspecifiedPosition = INT_MIN;
141
142 AppWindow::BoundsSpecification::BoundsSpecification()
143     : bounds(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0) {}
144
145 AppWindow::BoundsSpecification::~BoundsSpecification() {}
146
147 void AppWindow::BoundsSpecification::ResetBounds() {
148   bounds.SetRect(kUnspecifiedPosition, kUnspecifiedPosition, 0, 0);
149 }
150
151 // AppWindow::CreateParams
152
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) {
168 }
169
170 AppWindow::CreateParams::~CreateParams() {}
171
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());
183   }
184   if (content_spec.bounds.height() > 0) {
185     combined_bounds.set_height(
186         content_spec.bounds.height() + frame_insets.height());
187   }
188
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()));
196
197   return combined_bounds;
198 }
199
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);
205 }
206
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);
212 }
213
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);
219 }
220
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);
226 }
227
228 // AppWindow
229
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       image_loader_ptr_factory_(this),
238       fullscreen_types_(FULLSCREEN_TYPE_NONE),
239       show_on_first_paint_(false),
240       first_paint_complete_(false),
241       has_been_shown_(false),
242       can_send_events_(false),
243       is_hidden_(false),
244       cached_always_on_top_(false),
245       requested_alpha_enabled_(false) {
246   ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
247   CHECK(!client->IsGuestSession(context) || context->IsOffTheRecord())
248       << "Only off the record window may be opened in the guest mode.";
249 }
250
251 void AppWindow::Init(const GURL& url,
252                      AppWindowContents* app_window_contents,
253                      const CreateParams& params) {
254   // Initialize the render interface and web contents
255   app_window_contents_.reset(app_window_contents);
256   app_window_contents_->Initialize(browser_context(), url);
257   WebContents* web_contents = app_window_contents_->GetWebContents();
258   if (CommandLine::ForCurrentProcess()->HasSwitch(
259           switches::kEnableAppsShowOnFirstPaint)) {
260     content::WebContentsObserver::Observe(web_contents);
261   }
262   app_delegate_->InitWebContents(web_contents);
263
264   WebContentsModalDialogManager::CreateForWebContents(web_contents);
265
266   web_contents->SetDelegate(this);
267   WebContentsModalDialogManager::FromWebContents(web_contents)
268       ->SetDelegate(this);
269   SetViewType(web_contents, VIEW_TYPE_APP_WINDOW);
270
271   // Initialize the window
272   CreateParams new_params = LoadDefaults(params);
273   window_type_ = new_params.window_type;
274   window_key_ = new_params.window_key;
275
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;
280
281   requested_alpha_enabled_ = new_params.alpha_enabled;
282
283   AppWindowClient* app_window_client = AppWindowClient::Get();
284   native_app_window_.reset(
285       app_window_client->CreateNativeAppWindow(this, &new_params));
286
287   helper_.reset(new AppWebContentsHelper(
288       browser_context_, extension_id_, web_contents, app_delegate_.get()));
289
290   popup_manager_.reset(
291       new web_modal::PopupManager(GetWebContentsModalDialogHost()));
292   popup_manager_->RegisterWith(web_contents);
293
294   UpdateExtensionAppIcon();
295   AppWindowRegistry::Get(browser_context_)->AddAppWindow(this);
296
297   if (new_params.hidden) {
298     // Although the window starts hidden by default, calling Hide() here
299     // notifies observers of the window being hidden.
300     Hide();
301   } else {
302     // Panels are not activated by default.
303     Show(window_type_is_panel() || !new_params.focused ? SHOW_INACTIVE
304                                                        : SHOW_ACTIVE);
305   }
306
307   if (new_params.state == ui::SHOW_STATE_FULLSCREEN)
308     Fullscreen();
309   else if (new_params.state == ui::SHOW_STATE_MAXIMIZED)
310     Maximize();
311   else if (new_params.state == ui::SHOW_STATE_MINIMIZED)
312     Minimize();
313
314   OnNativeWindowChanged();
315
316   // When the render view host is changed, the native window needs to know
317   // about it in case it has any setup to do to make the renderer appear
318   // properly. In particular, on Windows, the view's clickthrough region needs
319   // to be set[
320   ExtensionsBrowserClient* client = ExtensionsBrowserClient::Get();
321   registrar_.Add(this,
322                  NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED,
323                  content::Source<content::BrowserContext>(
324                      client->GetOriginalContext(browser_context_)));
325   // Update the app menu if an ephemeral app becomes installed.
326   registrar_.Add(this,
327                  NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED,
328                  content::Source<content::BrowserContext>(
329                      client->GetOriginalContext(browser_context_)));
330
331   // Close when the browser process is exiting.
332   app_delegate_->SetTerminatingCallback(
333       base::Bind(&NativeAppWindow::Close,
334                  base::Unretained(native_app_window_.get())));
335
336   app_window_contents_->LoadContents(new_params.creator_process_id);
337
338   if (CommandLine::ForCurrentProcess()->HasSwitch(
339           extensions::switches::kEnableAppsShowOnFirstPaint)) {
340     // We want to show the window only when the content has been painted. For
341     // that to happen, we need to define a size for the content, otherwise the
342     // layout will happen in a 0x0 area.
343     gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
344     gfx::Rect initial_bounds = new_params.GetInitialWindowBounds(frame_insets);
345     initial_bounds.Inset(frame_insets);
346     app_delegate_->ResizeWebContents(web_contents, initial_bounds.size());
347   }
348 }
349
350 AppWindow::~AppWindow() {
351 }
352
353 void AppWindow::RequestMediaAccessPermission(
354     content::WebContents* web_contents,
355     const content::MediaStreamRequest& request,
356     const content::MediaResponseCallback& callback) {
357   DCHECK_EQ(AppWindow::web_contents(), web_contents);
358   helper_->RequestMediaAccessPermission(request, callback);
359 }
360
361 bool AppWindow::CheckMediaAccessPermission(content::WebContents* web_contents,
362                                            const GURL& security_origin,
363                                            content::MediaStreamType type) {
364   DCHECK_EQ(AppWindow::web_contents(), web_contents);
365   return helper_->CheckMediaAccessPermission(security_origin, type);
366 }
367
368 WebContents* AppWindow::OpenURLFromTab(WebContents* source,
369                                        const content::OpenURLParams& params) {
370   DCHECK_EQ(web_contents(), source);
371   return helper_->OpenURLFromTab(params);
372 }
373
374 void AppWindow::AddNewContents(WebContents* source,
375                                WebContents* new_contents,
376                                WindowOpenDisposition disposition,
377                                const gfx::Rect& initial_pos,
378                                bool user_gesture,
379                                bool* was_blocked) {
380   DCHECK(new_contents->GetBrowserContext() == browser_context_);
381   app_delegate_->AddNewContents(browser_context_,
382                                 new_contents,
383                                 disposition,
384                                 initial_pos,
385                                 user_gesture,
386                                 was_blocked);
387 }
388
389 bool AppWindow::PreHandleKeyboardEvent(
390     content::WebContents* source,
391     const content::NativeWebKeyboardEvent& event,
392     bool* is_keyboard_shortcut) {
393   const Extension* extension = GetExtension();
394   if (!extension)
395     return false;
396
397   // Here, we can handle a key event before the content gets it. When we are
398   // fullscreen and it is not forced, we want to allow the user to leave
399   // when ESC is pressed.
400   // However, if the application has the "overrideEscFullscreen" permission, we
401   // should let it override that behavior.
402   // ::HandleKeyboardEvent() will only be called if the KeyEvent's default
403   // action is not prevented.
404   // Thus, we should handle the KeyEvent here only if the permission is not set.
405   if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
406       !IsForcedFullscreen() &&
407       !extension->permissions_data()->HasAPIPermission(
408           APIPermission::kOverrideEscFullscreen)) {
409     Restore();
410     return true;
411   }
412
413   return false;
414 }
415
416 void AppWindow::HandleKeyboardEvent(
417     WebContents* source,
418     const content::NativeWebKeyboardEvent& event) {
419   // If the window is currently fullscreen and not forced, ESC should leave
420   // fullscreen.  If this code is being called for ESC, that means that the
421   // KeyEvent's default behavior was not prevented by the content.
422   if (event.windowsKeyCode == ui::VKEY_ESCAPE && IsFullscreen() &&
423       !IsForcedFullscreen()) {
424     Restore();
425     return;
426   }
427
428   native_app_window_->HandleKeyboardEvent(event);
429 }
430
431 void AppWindow::RequestToLockMouse(WebContents* web_contents,
432                                    bool user_gesture,
433                                    bool last_unlocked_by_target) {
434   DCHECK_EQ(AppWindow::web_contents(), web_contents);
435   helper_->RequestToLockMouse();
436 }
437
438 bool AppWindow::PreHandleGestureEvent(WebContents* source,
439                                       const blink::WebGestureEvent& event) {
440   return AppWebContentsHelper::ShouldSuppressGestureEvent(event);
441 }
442
443 void AppWindow::DidFirstVisuallyNonEmptyPaint() {
444   first_paint_complete_ = true;
445   if (show_on_first_paint_) {
446     DCHECK(delayed_show_type_ == SHOW_ACTIVE ||
447            delayed_show_type_ == SHOW_INACTIVE);
448     Show(delayed_show_type_);
449   }
450 }
451
452 void AppWindow::OnNativeClose() {
453   AppWindowRegistry::Get(browser_context_)->RemoveAppWindow(this);
454   if (app_window_contents_) {
455     WebContents* web_contents = app_window_contents_->GetWebContents();
456     WebContentsModalDialogManager::FromWebContents(web_contents)
457         ->SetDelegate(NULL);
458     app_window_contents_->NativeWindowClosed();
459   }
460   delete this;
461 }
462
463 void AppWindow::OnNativeWindowChanged() {
464   SaveWindowPosition();
465
466 #if defined(OS_WIN)
467   if (native_app_window_ && cached_always_on_top_ && !IsFullscreen() &&
468       !native_app_window_->IsMaximized() &&
469       !native_app_window_->IsMinimized()) {
470     UpdateNativeAlwaysOnTop();
471   }
472 #endif
473
474   if (app_window_contents_ && native_app_window_)
475     app_window_contents_->NativeWindowChanged(native_app_window_.get());
476 }
477
478 void AppWindow::OnNativeWindowActivated() {
479   AppWindowRegistry::Get(browser_context_)->AppWindowActivated(this);
480 }
481
482 content::WebContents* AppWindow::web_contents() const {
483   return app_window_contents_->GetWebContents();
484 }
485
486 const Extension* AppWindow::GetExtension() const {
487   return ExtensionRegistry::Get(browser_context_)
488       ->enabled_extensions()
489       .GetByID(extension_id_);
490 }
491
492 NativeAppWindow* AppWindow::GetBaseWindow() { return native_app_window_.get(); }
493
494 gfx::NativeWindow AppWindow::GetNativeWindow() {
495   return GetBaseWindow()->GetNativeWindow();
496 }
497
498 gfx::Rect AppWindow::GetClientBounds() const {
499   gfx::Rect bounds = native_app_window_->GetBounds();
500   bounds.Inset(native_app_window_->GetFrameInsets());
501   return bounds;
502 }
503
504 base::string16 AppWindow::GetTitle() const {
505   const Extension* extension = GetExtension();
506   if (!extension)
507     return base::string16();
508
509   // WebContents::GetTitle() will return the page's URL if there's no <title>
510   // specified. However, we'd prefer to show the name of the extension in that
511   // case, so we directly inspect the NavigationEntry's title.
512   base::string16 title;
513   if (!web_contents() || !web_contents()->GetController().GetActiveEntry() ||
514       web_contents()->GetController().GetActiveEntry()->GetTitle().empty()) {
515     title = base::UTF8ToUTF16(extension->name());
516   } else {
517     title = web_contents()->GetTitle();
518   }
519   base::RemoveChars(title, base::ASCIIToUTF16("\n"), &title);
520   return title;
521 }
522
523 void AppWindow::SetAppIconUrl(const GURL& url) {
524   // If the same url is being used for the badge, ignore it.
525   if (url == badge_icon_url_)
526     return;
527
528   // Avoid using any previous icons that were being downloaded.
529   image_loader_ptr_factory_.InvalidateWeakPtrs();
530
531   // Reset |app_icon_image_| to abort pending image load (if any).
532   app_icon_image_.reset();
533
534   app_icon_url_ = url;
535   web_contents()->DownloadImage(
536       url,
537       true,  // is a favicon
538       0,     // no maximum size
539       base::Bind(&AppWindow::DidDownloadFavicon,
540                  image_loader_ptr_factory_.GetWeakPtr()));
541 }
542
543 void AppWindow::SetBadgeIconUrl(const GURL& url) {
544   // Avoid using any previous icons that were being downloaded.
545   image_loader_ptr_factory_.InvalidateWeakPtrs();
546
547   // Reset |app_icon_image_| to abort pending image load (if any).
548   badge_icon_image_.reset();
549
550   badge_icon_url_ = url;
551   web_contents()->DownloadImage(
552       url,
553       true,  // is a favicon
554       0,     // no maximum size
555       base::Bind(&AppWindow::DidDownloadFavicon,
556                  image_loader_ptr_factory_.GetWeakPtr()));
557 }
558
559 void AppWindow::ClearBadge() {
560   badge_icon_image_.reset();
561   badge_icon_url_ = GURL();
562   UpdateBadgeIcon(gfx::Image());
563 }
564
565 void AppWindow::UpdateShape(scoped_ptr<SkRegion> region) {
566   native_app_window_->UpdateShape(region.Pass());
567 }
568
569 void AppWindow::UpdateDraggableRegions(
570     const std::vector<DraggableRegion>& regions) {
571   native_app_window_->UpdateDraggableRegions(regions);
572 }
573
574 void AppWindow::UpdateAppIcon(const gfx::Image& image) {
575   if (image.IsEmpty())
576     return;
577   app_icon_ = image;
578   native_app_window_->UpdateWindowIcon();
579   AppWindowRegistry::Get(browser_context_)->AppWindowIconChanged(this);
580 }
581
582 void AppWindow::SetFullscreen(FullscreenType type, bool enable) {
583   DCHECK_NE(FULLSCREEN_TYPE_NONE, type);
584
585   if (enable) {
586 #if !defined(OS_MACOSX)
587     // Do not enter fullscreen mode if disallowed by pref.
588     // TODO(bartfab): Add a test once it becomes possible to simulate a user
589     // gesture. http://crbug.com/174178
590     if (type != FULLSCREEN_TYPE_FORCED) {
591       PrefService* prefs =
592           ExtensionsBrowserClient::Get()->GetPrefServiceForContext(
593               browser_context());
594       if (!prefs->GetBoolean(pref_names::kAppFullscreenAllowed))
595         return;
596     }
597 #endif
598     fullscreen_types_ |= type;
599   } else {
600     fullscreen_types_ &= ~type;
601   }
602   SetNativeWindowFullscreen();
603 }
604
605 bool AppWindow::IsFullscreen() const {
606   return fullscreen_types_ != FULLSCREEN_TYPE_NONE;
607 }
608
609 bool AppWindow::IsForcedFullscreen() const {
610   return (fullscreen_types_ & FULLSCREEN_TYPE_FORCED) != 0;
611 }
612
613 bool AppWindow::IsHtmlApiFullscreen() const {
614   return (fullscreen_types_ & FULLSCREEN_TYPE_HTML_API) != 0;
615 }
616
617 void AppWindow::Fullscreen() {
618   SetFullscreen(FULLSCREEN_TYPE_WINDOW_API, true);
619 }
620
621 void AppWindow::Maximize() { GetBaseWindow()->Maximize(); }
622
623 void AppWindow::Minimize() { GetBaseWindow()->Minimize(); }
624
625 void AppWindow::Restore() {
626   if (IsFullscreen()) {
627     fullscreen_types_ = FULLSCREEN_TYPE_NONE;
628     SetNativeWindowFullscreen();
629   } else {
630     GetBaseWindow()->Restore();
631   }
632 }
633
634 void AppWindow::OSFullscreen() {
635   SetFullscreen(FULLSCREEN_TYPE_OS, true);
636 }
637
638 void AppWindow::ForcedFullscreen() {
639   SetFullscreen(FULLSCREEN_TYPE_FORCED, true);
640 }
641
642 void AppWindow::SetContentSizeConstraints(const gfx::Size& min_size,
643                                           const gfx::Size& max_size) {
644   SizeConstraints constraints(min_size, max_size);
645   native_app_window_->SetContentSizeConstraints(constraints.GetMinimumSize(),
646                                                 constraints.GetMaximumSize());
647
648   gfx::Rect bounds = GetClientBounds();
649   gfx::Size constrained_size = constraints.ClampSize(bounds.size());
650   if (bounds.size() != constrained_size) {
651     bounds.set_size(constrained_size);
652     bounds.Inset(-native_app_window_->GetFrameInsets());
653     native_app_window_->SetBounds(bounds);
654   }
655   OnNativeWindowChanged();
656 }
657
658 void AppWindow::Show(ShowType show_type) {
659   bool was_hidden = is_hidden_ || !has_been_shown_;
660   is_hidden_ = false;
661
662   if (CommandLine::ForCurrentProcess()->HasSwitch(
663           switches::kEnableAppsShowOnFirstPaint)) {
664     show_on_first_paint_ = true;
665
666     if (!first_paint_complete_) {
667       delayed_show_type_ = show_type;
668       return;
669     }
670   }
671
672   switch (show_type) {
673     case SHOW_ACTIVE:
674       GetBaseWindow()->Show();
675       break;
676     case SHOW_INACTIVE:
677       GetBaseWindow()->ShowInactive();
678       break;
679   }
680   AppWindowRegistry::Get(browser_context_)->AppWindowShown(this, was_hidden);
681
682   has_been_shown_ = true;
683   SendOnWindowShownIfShown();
684 }
685
686 void AppWindow::Hide() {
687   // This is there to prevent race conditions with Hide() being called before
688   // there was a non-empty paint. It should have no effect in a non-racy
689   // scenario where the application is hiding then showing a window: the second
690   // show will not be delayed.
691   is_hidden_ = true;
692   show_on_first_paint_ = false;
693   GetBaseWindow()->Hide();
694   AppWindowRegistry::Get(browser_context_)->AppWindowHidden(this);
695 }
696
697 void AppWindow::SetAlwaysOnTop(bool always_on_top) {
698   if (cached_always_on_top_ == always_on_top)
699     return;
700
701   cached_always_on_top_ = always_on_top;
702
703   // As a security measure, do not allow fullscreen windows or windows that
704   // overlap the taskbar to be on top. The property will be applied when the
705   // window exits fullscreen and moves away from the taskbar.
706   if (!IsFullscreen() && !IntersectsWithTaskbar())
707     native_app_window_->SetAlwaysOnTop(always_on_top);
708
709   OnNativeWindowChanged();
710 }
711
712 bool AppWindow::IsAlwaysOnTop() const { return cached_always_on_top_; }
713
714 void AppWindow::WindowEventsReady() {
715   can_send_events_ = true;
716   SendOnWindowShownIfShown();
717 }
718
719 void AppWindow::GetSerializedState(base::DictionaryValue* properties) const {
720   DCHECK(properties);
721
722   properties->SetBoolean("fullscreen",
723                          native_app_window_->IsFullscreenOrPending());
724   properties->SetBoolean("minimized", native_app_window_->IsMinimized());
725   properties->SetBoolean("maximized", native_app_window_->IsMaximized());
726   properties->SetBoolean("alwaysOnTop", IsAlwaysOnTop());
727   properties->SetBoolean("hasFrameColor", native_app_window_->HasFrameColor());
728   properties->SetBoolean(
729       "alphaEnabled",
730       requested_alpha_enabled_ && native_app_window_->CanHaveAlphaEnabled());
731
732   // These properties are undocumented and are to enable testing. Alpha is
733   // removed to
734   // make the values easier to check.
735   SkColor transparent_white = ~SK_ColorBLACK;
736   properties->SetInteger(
737       "activeFrameColor",
738       native_app_window_->ActiveFrameColor() & transparent_white);
739   properties->SetInteger(
740       "inactiveFrameColor",
741       native_app_window_->InactiveFrameColor() & transparent_white);
742
743   gfx::Rect content_bounds = GetClientBounds();
744   gfx::Size content_min_size = native_app_window_->GetContentMinimumSize();
745   gfx::Size content_max_size = native_app_window_->GetContentMaximumSize();
746   SetBoundsProperties(content_bounds,
747                       content_min_size,
748                       content_max_size,
749                       "innerBounds",
750                       properties);
751
752   gfx::Insets frame_insets = native_app_window_->GetFrameInsets();
753   gfx::Rect frame_bounds = native_app_window_->GetBounds();
754   gfx::Size frame_min_size = SizeConstraints::AddFrameToConstraints(
755       content_min_size, frame_insets);
756   gfx::Size frame_max_size = SizeConstraints::AddFrameToConstraints(
757       content_max_size, frame_insets);
758   SetBoundsProperties(frame_bounds,
759                       frame_min_size,
760                       frame_max_size,
761                       "outerBounds",
762                       properties);
763 }
764
765 //------------------------------------------------------------------------------
766 // Private methods
767
768 void AppWindow::UpdateBadgeIcon(const gfx::Image& image) {
769   badge_icon_ = image;
770   native_app_window_->UpdateBadgeIcon();
771 }
772
773 void AppWindow::DidDownloadFavicon(
774     int id,
775     int http_status_code,
776     const GURL& image_url,
777     const std::vector<SkBitmap>& bitmaps,
778     const std::vector<gfx::Size>& original_bitmap_sizes) {
779   if ((image_url != app_icon_url_ && image_url != badge_icon_url_) ||
780       bitmaps.empty()) {
781     return;
782   }
783
784   // Bitmaps are ordered largest to smallest. Choose the smallest bitmap
785   // whose height >= the preferred size.
786   int largest_index = 0;
787   for (size_t i = 1; i < bitmaps.size(); ++i) {
788     if (bitmaps[i].height() < app_delegate_->PreferredIconSize())
789       break;
790     largest_index = i;
791   }
792   const SkBitmap& largest = bitmaps[largest_index];
793   if (image_url == app_icon_url_) {
794     UpdateAppIcon(gfx::Image::CreateFrom1xBitmap(largest));
795     return;
796   }
797
798   UpdateBadgeIcon(gfx::Image::CreateFrom1xBitmap(largest));
799 }
800
801 void AppWindow::OnExtensionIconImageChanged(IconImage* image) {
802   DCHECK_EQ(app_icon_image_.get(), image);
803
804   UpdateAppIcon(gfx::Image(app_icon_image_->image_skia()));
805 }
806
807 void AppWindow::UpdateExtensionAppIcon() {
808   // Avoid using any previous app icons were being downloaded.
809   image_loader_ptr_factory_.InvalidateWeakPtrs();
810
811   const Extension* extension = GetExtension();
812   if (!extension)
813     return;
814
815   gfx::ImageSkia app_default_icon =
816       *ResourceBundle::GetSharedInstance().GetImageSkiaNamed(
817           IDR_APP_DEFAULT_ICON);
818
819   app_icon_image_.reset(new IconImage(browser_context(),
820                                       extension,
821                                       IconsInfo::GetIcons(extension),
822                                       app_delegate_->PreferredIconSize(),
823                                       app_default_icon,
824                                       this));
825
826   // Triggers actual image loading with 1x resources. The 2x resource will
827   // be handled by IconImage class when requested.
828   app_icon_image_->image_skia().GetRepresentation(1.0f);
829 }
830
831 void AppWindow::SetNativeWindowFullscreen() {
832   native_app_window_->SetFullscreen(fullscreen_types_);
833
834   if (cached_always_on_top_)
835     UpdateNativeAlwaysOnTop();
836 }
837
838 bool AppWindow::IntersectsWithTaskbar() const {
839 #if defined(OS_WIN)
840   gfx::Screen* screen = gfx::Screen::GetNativeScreen();
841   gfx::Rect window_bounds = native_app_window_->GetRestoredBounds();
842   std::vector<gfx::Display> displays = screen->GetAllDisplays();
843
844   for (std::vector<gfx::Display>::const_iterator it = displays.begin();
845        it != displays.end();
846        ++it) {
847     gfx::Rect taskbar_bounds = it->bounds();
848     taskbar_bounds.Subtract(it->work_area());
849     if (taskbar_bounds.IsEmpty())
850       continue;
851
852     if (window_bounds.Intersects(taskbar_bounds))
853       return true;
854   }
855 #endif
856
857   return false;
858 }
859
860 void AppWindow::UpdateNativeAlwaysOnTop() {
861   DCHECK(cached_always_on_top_);
862   bool is_on_top = native_app_window_->IsAlwaysOnTop();
863   bool fullscreen = IsFullscreen();
864   bool intersects_taskbar = IntersectsWithTaskbar();
865
866   if (is_on_top && (fullscreen || intersects_taskbar)) {
867     // When entering fullscreen or overlapping the taskbar, ensure windows are
868     // not always-on-top.
869     native_app_window_->SetAlwaysOnTop(false);
870   } else if (!is_on_top && !fullscreen && !intersects_taskbar) {
871     // When exiting fullscreen and moving away from the taskbar, reinstate
872     // always-on-top.
873     native_app_window_->SetAlwaysOnTop(true);
874   }
875 }
876
877 void AppWindow::SendOnWindowShownIfShown() {
878   if (!can_send_events_ || !has_been_shown_)
879     return;
880
881   if (CommandLine::ForCurrentProcess()->HasSwitch(::switches::kTestType)) {
882     app_window_contents_->DispatchWindowShownForTests();
883   }
884 }
885
886 void AppWindow::CloseContents(WebContents* contents) {
887   native_app_window_->Close();
888 }
889
890 bool AppWindow::ShouldSuppressDialogs() { return true; }
891
892 content::ColorChooser* AppWindow::OpenColorChooser(
893     WebContents* web_contents,
894     SkColor initial_color,
895     const std::vector<content::ColorSuggestion>& suggestions) {
896   return app_delegate_->ShowColorChooser(web_contents, initial_color);
897 }
898
899 void AppWindow::RunFileChooser(WebContents* tab,
900                                const content::FileChooserParams& params) {
901   if (window_type_is_panel()) {
902     // Panels can't host a file dialog, abort. TODO(stevenjb): allow file
903     // dialogs to be unhosted but still close with the owning web contents.
904     // crbug.com/172502.
905     LOG(WARNING) << "File dialog opened by panel.";
906     return;
907   }
908
909   app_delegate_->RunFileChooser(tab, params);
910 }
911
912 bool AppWindow::IsPopupOrPanel(const WebContents* source) const { return true; }
913
914 void AppWindow::MoveContents(WebContents* source, const gfx::Rect& pos) {
915   native_app_window_->SetBounds(pos);
916 }
917
918 void AppWindow::NavigationStateChanged(const content::WebContents* source,
919                                        content::InvalidateTypes changed_flags) {
920   if (changed_flags & content::INVALIDATE_TYPE_TITLE)
921     native_app_window_->UpdateWindowTitle();
922   else if (changed_flags & content::INVALIDATE_TYPE_TAB)
923     native_app_window_->UpdateWindowIcon();
924 }
925
926 void AppWindow::ToggleFullscreenModeForTab(content::WebContents* source,
927                                            bool enter_fullscreen) {
928   const Extension* extension = GetExtension();
929   if (!extension)
930     return;
931
932   if (!IsExtensionWithPermissionOrSuggestInConsole(
933           APIPermission::kFullscreen, extension, source->GetRenderViewHost())) {
934     return;
935   }
936
937   SetFullscreen(FULLSCREEN_TYPE_HTML_API, enter_fullscreen);
938 }
939
940 bool AppWindow::IsFullscreenForTabOrPending(const content::WebContents* source)
941     const {
942   return IsHtmlApiFullscreen();
943 }
944
945 void AppWindow::Observe(int type,
946                         const content::NotificationSource& source,
947                         const content::NotificationDetails& details) {
948   switch (type) {
949     case NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED: {
950       const Extension* unloaded_extension =
951           content::Details<UnloadedExtensionInfo>(details)->extension;
952       if (extension_id_ == unloaded_extension->id())
953         native_app_window_->Close();
954       break;
955     }
956     case NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED: {
957       const Extension* installed_extension =
958           content::Details<const InstalledExtensionInfo>(details)->extension;
959       DCHECK(installed_extension);
960       if (installed_extension->id() == extension_id())
961         native_app_window_->UpdateShelfMenu();
962       break;
963     }
964     default:
965       NOTREACHED() << "Received unexpected notification";
966   }
967 }
968
969 void AppWindow::SetWebContentsBlocked(content::WebContents* web_contents,
970                                       bool blocked) {
971   app_delegate_->SetWebContentsBlocked(web_contents, blocked);
972 }
973
974 bool AppWindow::IsWebContentsVisible(content::WebContents* web_contents) {
975   return app_delegate_->IsWebContentsVisible(web_contents);
976 }
977
978 WebContentsModalDialogHost* AppWindow::GetWebContentsModalDialogHost() {
979   return native_app_window_.get();
980 }
981
982 void AppWindow::SaveWindowPosition() {
983   if (window_key_.empty())
984     return;
985   if (!native_app_window_)
986     return;
987
988   AppWindowGeometryCache* cache =
989       AppWindowGeometryCache::Get(browser_context());
990
991   gfx::Rect bounds = native_app_window_->GetRestoredBounds();
992   gfx::Rect screen_bounds =
993       gfx::Screen::GetNativeScreen()->GetDisplayMatching(bounds).work_area();
994   ui::WindowShowState window_state = native_app_window_->GetRestoredState();
995   cache->SaveGeometry(
996       extension_id(), window_key_, bounds, screen_bounds, window_state);
997 }
998
999 void AppWindow::AdjustBoundsToBeVisibleOnScreen(
1000     const gfx::Rect& cached_bounds,
1001     const gfx::Rect& cached_screen_bounds,
1002     const gfx::Rect& current_screen_bounds,
1003     const gfx::Size& minimum_size,
1004     gfx::Rect* bounds) const {
1005   *bounds = cached_bounds;
1006
1007   // Reposition and resize the bounds if the cached_screen_bounds is different
1008   // from the current screen bounds and the current screen bounds doesn't
1009   // completely contain the bounds.
1010   if (cached_screen_bounds != current_screen_bounds &&
1011       !current_screen_bounds.Contains(cached_bounds)) {
1012     bounds->set_width(
1013         std::max(minimum_size.width(),
1014                  std::min(bounds->width(), current_screen_bounds.width())));
1015     bounds->set_height(
1016         std::max(minimum_size.height(),
1017                  std::min(bounds->height(), current_screen_bounds.height())));
1018     bounds->set_x(
1019         std::max(current_screen_bounds.x(),
1020                  std::min(bounds->x(),
1021                           current_screen_bounds.right() - bounds->width())));
1022     bounds->set_y(
1023         std::max(current_screen_bounds.y(),
1024                  std::min(bounds->y(),
1025                           current_screen_bounds.bottom() - bounds->height())));
1026   }
1027 }
1028
1029 AppWindow::CreateParams AppWindow::LoadDefaults(CreateParams params)
1030     const {
1031   // Ensure width and height are specified.
1032   if (params.content_spec.bounds.width() == 0 &&
1033       params.window_spec.bounds.width() == 0) {
1034     params.content_spec.bounds.set_width(kDefaultWidth);
1035   }
1036   if (params.content_spec.bounds.height() == 0 &&
1037       params.window_spec.bounds.height() == 0) {
1038     params.content_spec.bounds.set_height(kDefaultHeight);
1039   }
1040
1041   // If left and top are left undefined, the native app window will center
1042   // the window on the main screen in a platform-defined manner.
1043
1044   // Load cached state if it exists.
1045   if (!params.window_key.empty()) {
1046     AppWindowGeometryCache* cache =
1047         AppWindowGeometryCache::Get(browser_context());
1048
1049     gfx::Rect cached_bounds;
1050     gfx::Rect cached_screen_bounds;
1051     ui::WindowShowState cached_state = ui::SHOW_STATE_DEFAULT;
1052     if (cache->GetGeometry(extension_id(),
1053                            params.window_key,
1054                            &cached_bounds,
1055                            &cached_screen_bounds,
1056                            &cached_state)) {
1057       // App window has cached screen bounds, make sure it fits on screen in
1058       // case the screen resolution changed.
1059       gfx::Screen* screen = gfx::Screen::GetNativeScreen();
1060       gfx::Display display = screen->GetDisplayMatching(cached_bounds);
1061       gfx::Rect current_screen_bounds = display.work_area();
1062       SizeConstraints constraints(params.GetWindowMinimumSize(gfx::Insets()),
1063                                   params.GetWindowMaximumSize(gfx::Insets()));
1064       AdjustBoundsToBeVisibleOnScreen(cached_bounds,
1065                                       cached_screen_bounds,
1066                                       current_screen_bounds,
1067                                       constraints.GetMinimumSize(),
1068                                       &params.window_spec.bounds);
1069       params.state = cached_state;
1070
1071       // Since we are restoring a cached state, reset the content bounds spec to
1072       // ensure it is not used.
1073       params.content_spec.ResetBounds();
1074     }
1075   }
1076
1077   return params;
1078 }
1079
1080 // static
1081 SkRegion* AppWindow::RawDraggableRegionsToSkRegion(
1082     const std::vector<DraggableRegion>& regions) {
1083   SkRegion* sk_region = new SkRegion;
1084   for (std::vector<DraggableRegion>::const_iterator iter = regions.begin();
1085        iter != regions.end();
1086        ++iter) {
1087     const DraggableRegion& region = *iter;
1088     sk_region->op(
1089         region.bounds.x(),
1090         region.bounds.y(),
1091         region.bounds.right(),
1092         region.bounds.bottom(),
1093         region.draggable ? SkRegion::kUnion_Op : SkRegion::kDifference_Op);
1094   }
1095   return sk_region;
1096 }
1097
1098 }  // namespace extensions