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