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