Upstream version 10.38.222.0
[platform/framework/web/crosswalk.git] / src / apps / app_window.h
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 #ifndef APPS_APP_WINDOW_H_
6 #define APPS_APP_WINDOW_H_
7
8 #include <string>
9 #include <vector>
10
11 #include "base/memory/scoped_ptr.h"
12 #include "base/memory/weak_ptr.h"
13 #include "chrome/browser/sessions/session_id.h"
14 #include "components/web_modal/web_contents_modal_dialog_manager_delegate.h"
15 #include "content/public/browser/notification_observer.h"
16 #include "content/public/browser/notification_registrar.h"
17 #include "content/public/browser/web_contents_delegate.h"
18 #include "content/public/browser/web_contents_observer.h"
19 #include "extensions/browser/extension_icon_image.h"
20 #include "ui/base/ui_base_types.h"  // WindowShowState
21 #include "ui/gfx/image/image.h"
22 #include "ui/gfx/rect.h"
23
24 class GURL;
25 class SkRegion;
26
27 namespace base {
28 class DictionaryValue;
29 }
30
31 namespace content {
32 class BrowserContext;
33 class WebContents;
34 }
35
36 namespace extensions {
37 class Extension;
38 class PlatformAppBrowserTest;
39 class WindowController;
40
41 struct DraggableRegion;
42 }
43
44 namespace ui {
45 class BaseWindow;
46 }
47
48 namespace apps {
49
50 class AppDelegate;
51 class AppWebContentsHelper;
52 class NativeAppWindow;
53
54 // Manages the web contents for app windows. The implementation for this
55 // class should create and maintain the WebContents for the window, and handle
56 // any message passing between the web contents and the extension system or
57 // native window.
58 class AppWindowContents {
59  public:
60   AppWindowContents() {}
61   virtual ~AppWindowContents() {}
62
63   // Called to initialize the WebContents, before the app window is created.
64   virtual void Initialize(content::BrowserContext* context,
65                           const GURL& url) = 0;
66
67   // Called to load the contents, after the app window is created.
68   virtual void LoadContents(int32 creator_process_id) = 0;
69
70   // Called when the native window changes.
71   virtual void NativeWindowChanged(NativeAppWindow* native_app_window) = 0;
72
73   // Called when the native window closes.
74   virtual void NativeWindowClosed() = 0;
75
76   // Called in tests when the window is shown
77   virtual void DispatchWindowShownForTests() const = 0;
78
79   virtual content::WebContents* GetWebContents() const = 0;
80
81  private:
82   DISALLOW_COPY_AND_ASSIGN(AppWindowContents);
83 };
84
85 // AppWindow is the type of window used by platform apps. App windows
86 // have a WebContents but none of the chrome of normal browser windows.
87 class AppWindow : public content::NotificationObserver,
88                   public content::WebContentsDelegate,
89                   public content::WebContentsObserver,
90                   public web_modal::WebContentsModalDialogManagerDelegate,
91                   public extensions::IconImage::Observer {
92  public:
93   enum WindowType {
94     WINDOW_TYPE_DEFAULT = 1 << 0,   // Default app window.
95     WINDOW_TYPE_PANEL = 1 << 1,     // OS controlled panel window (Ash only).
96     WINDOW_TYPE_V1_PANEL = 1 << 2,  // For apps v1 support in Ash; deprecate
97                                     // with v1 apps.
98   };
99
100   enum Frame {
101     FRAME_CHROME,  // Chrome-style window frame.
102     FRAME_NONE,    // Frameless window.
103   };
104
105   enum FullscreenType {
106     // Not fullscreen.
107     FULLSCREEN_TYPE_NONE = 0,
108
109     // Fullscreen entered by the app.window api.
110     FULLSCREEN_TYPE_WINDOW_API = 1 << 0,
111
112     // Fullscreen entered by HTML requestFullscreen().
113     FULLSCREEN_TYPE_HTML_API = 1 << 1,
114
115     // Fullscreen entered by the OS. ChromeOS uses this type of fullscreen to
116     // enter immersive fullscreen when the user hits the <F4> key.
117     FULLSCREEN_TYPE_OS = 1 << 2,
118
119     // Fullscreen mode that could not be exited by the user. ChromeOS uses
120     // this type of fullscreen to run an app in kiosk mode.
121     FULLSCREEN_TYPE_FORCED = 1 << 3,
122   };
123
124   struct BoundsSpecification {
125     // INT_MIN represents an unspecified position component.
126     static const int kUnspecifiedPosition;
127
128     BoundsSpecification();
129     ~BoundsSpecification();
130
131     // INT_MIN designates 'unspecified' for the position components, and 0
132     // designates 'unspecified' for the size components. When unspecified,
133     // they should be replaced with a default value.
134     gfx::Rect bounds;
135
136     gfx::Size minimum_size;
137     gfx::Size maximum_size;
138
139     // Reset the bounds fields to their 'unspecified' values. The minimum and
140     // maximum size constraints remain unchanged.
141     void ResetBounds();
142   };
143
144   struct CreateParams {
145     CreateParams();
146     ~CreateParams();
147
148     WindowType window_type;
149     Frame frame;
150
151     bool has_frame_color;
152     SkColor active_frame_color;
153     SkColor inactive_frame_color;
154     bool alpha_enabled;
155
156     // The initial content/inner bounds specification (excluding any window
157     // decorations).
158     BoundsSpecification content_spec;
159
160     // The initial window/outer bounds specification (including window
161     // decorations).
162     BoundsSpecification window_spec;
163
164     std::string window_key;
165
166     // The process ID of the process that requested the create.
167     int32 creator_process_id;
168
169     // Initial state of the window.
170     ui::WindowShowState state;
171
172     // If true, don't show the window after creation.
173     bool hidden;
174
175     // If true, the window will be resizable by the user. Defaults to true.
176     bool resizable;
177
178     // If true, the window will be focused on creation. Defaults to true.
179     bool focused;
180
181     // If true, the window will stay on top of other windows that are not
182     // configured to be always on top. Defaults to false.
183     bool always_on_top;
184
185     // The API enables developers to specify content or window bounds. This
186     // function combines them into a single, constrained window size.
187     gfx::Rect GetInitialWindowBounds(const gfx::Insets& frame_insets) const;
188
189     // The API enables developers to specify content or window size constraints.
190     // These functions combine them so that we can work with one set of
191     // constraints.
192     gfx::Size GetContentMinimumSize(const gfx::Insets& frame_insets) const;
193     gfx::Size GetContentMaximumSize(const gfx::Insets& frame_insets) const;
194     gfx::Size GetWindowMinimumSize(const gfx::Insets& frame_insets) const;
195     gfx::Size GetWindowMaximumSize(const gfx::Insets& frame_insets) const;
196   };
197
198   // Convert draggable regions in raw format to SkRegion format. Caller is
199   // responsible for deleting the returned SkRegion instance.
200   static SkRegion* RawDraggableRegionsToSkRegion(
201       const std::vector<extensions::DraggableRegion>& regions);
202
203   // The constructor and Init methods are public for constructing a AppWindow
204   // with a non-standard render interface (e.g. v1 apps using Ash Panels).
205   // Normally AppWindow::Create should be used.
206   // Takes ownership of |app_delegate| and |delegate|.
207   AppWindow(content::BrowserContext* context,
208             AppDelegate* app_delegate,
209             const extensions::Extension* extension);
210
211   // Initializes the render interface, web contents, and native window.
212   // |app_window_contents| will become owned by AppWindow.
213   void Init(const GURL& url,
214             AppWindowContents* app_window_contents,
215             const CreateParams& params);
216
217   const std::string& window_key() const { return window_key_; }
218   const SessionID& session_id() const { return session_id_; }
219   const std::string& extension_id() const { return extension_id_; }
220   content::WebContents* web_contents() const;
221   WindowType window_type() const { return window_type_; }
222   bool window_type_is_panel() const {
223     return (window_type_ == WINDOW_TYPE_PANEL ||
224             window_type_ == WINDOW_TYPE_V1_PANEL);
225   }
226   content::BrowserContext* browser_context() const { return browser_context_; }
227   const gfx::Image& app_icon() const { return app_icon_; }
228   const GURL& app_icon_url() const { return app_icon_url_; }
229   const gfx::Image& badge_icon() const { return badge_icon_; }
230   const GURL& badge_icon_url() const { return badge_icon_url_; }
231   bool is_hidden() const { return is_hidden_; }
232
233   const extensions::Extension* GetExtension() const;
234   NativeAppWindow* GetBaseWindow();
235   gfx::NativeWindow GetNativeWindow();
236
237   // Returns the bounds that should be reported to the renderer.
238   gfx::Rect GetClientBounds() const;
239
240   // NativeAppWindows should call this to determine what the window's title
241   // is on startup and from within UpdateWindowTitle().
242   base::string16 GetTitle() const;
243
244   // Call to notify ShellRegistry and delete the window. Subclasses should
245   // invoke this method instead of using "delete this".
246   void OnNativeClose();
247
248   // Should be called by native implementations when the window size, position,
249   // or minimized/maximized state has changed.
250   void OnNativeWindowChanged();
251
252   // Should be called by native implementations when the window is activated.
253   void OnNativeWindowActivated();
254
255   // Specifies a url for the launcher icon.
256   void SetAppIconUrl(const GURL& icon_url);
257
258   // Specifies a url for the window badge.
259   void SetBadgeIconUrl(const GURL& icon_url);
260
261   // Clear the current badge.
262   void ClearBadge();
263
264   // Set the window shape. Passing a NULL |region| sets the default shape.
265   void UpdateShape(scoped_ptr<SkRegion> region);
266
267   // Called from the render interface to modify the draggable regions.
268   void UpdateDraggableRegions(
269       const std::vector<extensions::DraggableRegion>& regions);
270
271   // Updates the app image to |image|. Called internally from the image loader
272   // callback. Also called externally for v1 apps using Ash Panels.
273   void UpdateAppIcon(const gfx::Image& image);
274
275   // Enable or disable fullscreen mode. |type| specifies which type of
276   // fullscreen mode to change (note that disabling one type of fullscreen may
277   // not exit fullscreen mode because a window may have a different type of
278   // fullscreen enabled). If |type| is not FORCED, checks that the extension has
279   // the required permission.
280   void SetFullscreen(FullscreenType type, bool enable);
281
282   // Returns true if the app window is in a fullscreen state.
283   bool IsFullscreen() const;
284
285   // Returns true if the app window is in a forced fullscreen state (one that
286   // cannot be exited by the user).
287   bool IsForcedFullscreen() const;
288
289   // Returns true if the app window is in a fullscreen state entered from an
290   // HTML API request.
291   bool IsHtmlApiFullscreen() const;
292
293   // Transitions window into fullscreen, maximized, minimized or restores based
294   // on chrome.app.window API.
295   void Fullscreen();
296   void Maximize();
297   void Minimize();
298   void Restore();
299
300   // Transitions to OS fullscreen. See FULLSCREEN_TYPE_OS for more details.
301   void OSFullscreen();
302
303   // Transitions to forced fullscreen. See FULLSCREEN_TYPE_FORCED for more
304   // details.
305   void ForcedFullscreen();
306
307   // Set the minimum and maximum size of the content bounds.
308   void SetContentSizeConstraints(const gfx::Size& min_size,
309                                  const gfx::Size& max_size);
310
311   enum ShowType { SHOW_ACTIVE, SHOW_INACTIVE };
312
313   // Shows the window if its contents have been painted; otherwise flags the
314   // window to be shown as soon as its contents are painted for the first time.
315   void Show(ShowType show_type);
316
317   // Hides the window. If the window was previously flagged to be shown on
318   // first paint, it will be unflagged.
319   void Hide();
320
321   AppWindowContents* app_window_contents_for_test() {
322     return app_window_contents_.get();
323   }
324
325   int fullscreen_types_for_test() {
326     return fullscreen_types_;
327   }
328
329   // Set whether the window should stay above other windows which are not
330   // configured to be always-on-top.
331   void SetAlwaysOnTop(bool always_on_top);
332
333   // Whether the always-on-top property has been set by the chrome.app.window
334   // API. Note that the actual value of this property in the native app window
335   // may be false if the bit is silently switched off for security reasons.
336   bool IsAlwaysOnTop() const;
337
338   // Retrieve the current state of the app window as a dictionary, to pass to
339   // the renderer.
340   void GetSerializedState(base::DictionaryValue* properties) const;
341
342   // Called by the window API when events can be sent to the window for this
343   // app.
344   void WindowEventsReady();
345
346   // Whether the app window wants to be alpha enabled.
347   bool requested_alpha_enabled() const { return requested_alpha_enabled_; }
348
349  protected:
350   virtual ~AppWindow();
351
352  private:
353   // PlatformAppBrowserTest needs access to web_contents()
354   friend class extensions::PlatformAppBrowserTest;
355
356   // content::WebContentsDelegate implementation.
357   virtual void CloseContents(content::WebContents* contents) OVERRIDE;
358   virtual bool ShouldSuppressDialogs() OVERRIDE;
359   virtual content::ColorChooser* OpenColorChooser(
360       content::WebContents* web_contents,
361       SkColor color,
362       const std::vector<content::ColorSuggestion>& suggestions) OVERRIDE;
363   virtual void RunFileChooser(content::WebContents* tab,
364                               const content::FileChooserParams& params)
365       OVERRIDE;
366   virtual bool IsPopupOrPanel(const content::WebContents* source)
367       const OVERRIDE;
368   virtual void MoveContents(content::WebContents* source,
369                             const gfx::Rect& pos) OVERRIDE;
370   virtual void NavigationStateChanged(
371       const content::WebContents* source,
372       content::InvalidateTypes changed_flags) OVERRIDE;
373   virtual void ToggleFullscreenModeForTab(content::WebContents* source,
374                                           bool enter_fullscreen) OVERRIDE;
375   virtual bool IsFullscreenForTabOrPending(const content::WebContents* source)
376       const OVERRIDE;
377   virtual void RequestMediaAccessPermission(
378       content::WebContents* web_contents,
379       const content::MediaStreamRequest& request,
380       const content::MediaResponseCallback& callback) OVERRIDE;
381   virtual content::WebContents* OpenURLFromTab(
382       content::WebContents* source,
383       const content::OpenURLParams& params) OVERRIDE;
384   virtual void AddNewContents(content::WebContents* source,
385                               content::WebContents* new_contents,
386                               WindowOpenDisposition disposition,
387                               const gfx::Rect& initial_pos,
388                               bool user_gesture,
389                               bool* was_blocked) OVERRIDE;
390   virtual bool PreHandleKeyboardEvent(
391       content::WebContents* source,
392       const content::NativeWebKeyboardEvent& event,
393       bool* is_keyboard_shortcut) OVERRIDE;
394   virtual void HandleKeyboardEvent(content::WebContents* source,
395                                    const content::NativeWebKeyboardEvent& event)
396       OVERRIDE;
397   virtual void RequestToLockMouse(content::WebContents* web_contents,
398                                   bool user_gesture,
399                                   bool last_unlocked_by_target) OVERRIDE;
400   virtual bool PreHandleGestureEvent(content::WebContents* source,
401                                      const blink::WebGestureEvent& event)
402       OVERRIDE;
403
404   // content::WebContentsObserver implementation.
405   virtual void DidFirstVisuallyNonEmptyPaint() OVERRIDE;
406
407   // content::NotificationObserver implementation.
408   virtual void Observe(int type,
409                        const content::NotificationSource& source,
410                        const content::NotificationDetails& details) OVERRIDE;
411
412   // web_modal::WebContentsModalDialogManagerDelegate implementation.
413   virtual void SetWebContentsBlocked(content::WebContents* web_contents,
414                                      bool blocked) OVERRIDE;
415   virtual bool IsWebContentsVisible(content::WebContents* web_contents)
416       OVERRIDE;
417
418   // Saves the window geometry/position/screen bounds.
419   void SaveWindowPosition();
420
421   // Helper method to adjust the cached bounds so that we can make sure it can
422   // be visible on the screen. See http://crbug.com/145752.
423   void AdjustBoundsToBeVisibleOnScreen(const gfx::Rect& cached_bounds,
424                                        const gfx::Rect& cached_screen_bounds,
425                                        const gfx::Rect& current_screen_bounds,
426                                        const gfx::Size& minimum_size,
427                                        gfx::Rect* bounds) const;
428
429   // Loads the appropriate default or cached window bounds. Returns a new
430   // CreateParams that should be used to create the window.
431   CreateParams LoadDefaults(CreateParams params) const;
432
433   // Load the app's image, firing a load state change when loaded.
434   void UpdateExtensionAppIcon();
435
436   // Set the fullscreen state in the native app window.
437   void SetNativeWindowFullscreen();
438
439   // Returns true if there is any overlap between the window and the taskbar
440   // (Windows only).
441   bool IntersectsWithTaskbar() const;
442
443   // Update the always-on-top bit in the native app window.
444   void UpdateNativeAlwaysOnTop();
445
446   // Sends the onWindowShown event to the app if the window has been shown. Only
447   // has an effect in tests.
448   void SendOnWindowShownIfShown();
449
450   // web_modal::WebContentsModalDialogManagerDelegate implementation.
451   virtual web_modal::WebContentsModalDialogHost* GetWebContentsModalDialogHost()
452       OVERRIDE;
453
454   // Updates the badge to |image|. Called internally from the image loader
455   // callback.
456   void UpdateBadgeIcon(const gfx::Image& image);
457
458   // Callback from web_contents()->DownloadFavicon.
459   void DidDownloadFavicon(int id,
460                           int http_status_code,
461                           const GURL& image_url,
462                           const std::vector<SkBitmap>& bitmaps,
463                           const std::vector<gfx::Size>& original_bitmap_sizes);
464
465   // extensions::IconImage::Observer implementation.
466   virtual void OnExtensionIconImageChanged(extensions::IconImage* image)
467       OVERRIDE;
468
469   // The browser context with which this window is associated. AppWindow does
470   // not own this object.
471   content::BrowserContext* browser_context_;
472
473   const std::string extension_id_;
474
475   // Identifier that is used when saving and restoring geometry for this
476   // window.
477   std::string window_key_;
478
479   const SessionID session_id_;
480   WindowType window_type_;
481   content::NotificationRegistrar registrar_;
482
483   // Icon shown in the task bar.
484   gfx::Image app_icon_;
485
486   // Icon URL to be used for setting the app icon. If not empty, app_icon_ will
487   // be fetched and set using this URL.
488   GURL app_icon_url_;
489
490   // An object to load the app's icon as an extension resource.
491   scoped_ptr<extensions::IconImage> app_icon_image_;
492
493   // Badge for icon shown in the task bar.
494   gfx::Image badge_icon_;
495
496   // URL to be used for setting the badge on the app icon.
497   GURL badge_icon_url_;
498
499   // An object to load the badge as an extension resource.
500   scoped_ptr<extensions::IconImage> badge_icon_image_;
501
502   scoped_ptr<NativeAppWindow> native_app_window_;
503   scoped_ptr<AppWindowContents> app_window_contents_;
504   scoped_ptr<AppDelegate> app_delegate_;
505   scoped_ptr<AppWebContentsHelper> helper_;
506
507   base::WeakPtrFactory<AppWindow> image_loader_ptr_factory_;
508
509   // Bit field of FullscreenType.
510   int fullscreen_types_;
511
512   // Show has been called, so the window should be shown once the first visually
513   // non-empty paint occurs.
514   bool show_on_first_paint_;
515
516   // The first visually non-empty paint has completed.
517   bool first_paint_complete_;
518
519   // Whether the window has been shown or not.
520   bool has_been_shown_;
521
522   // Whether events can be sent to the window.
523   bool can_send_events_;
524
525   // Whether the window is hidden or not. Hidden in this context means actively
526   // by the chrome.app.window API, not in an operating system context. For
527   // example windows which are minimized are not hidden, and windows which are
528   // part of a hidden app on OS X are not hidden. Windows which were created
529   // with the |hidden| flag set to true, or which have been programmatically
530   // hidden, are considered hidden.
531   bool is_hidden_;
532
533   // Whether the delayed Show() call was for an active or inactive window.
534   ShowType delayed_show_type_;
535
536   // Cache the desired value of the always-on-top property. When windows enter
537   // fullscreen or overlap the Windows taskbar, this property will be
538   // automatically and silently switched off for security reasons. It is
539   // reinstated when the window exits fullscreen and moves away from the
540   // taskbar.
541   bool cached_always_on_top_;
542
543   // Whether |alpha_enabled| was set in the CreateParams.
544   bool requested_alpha_enabled_;
545
546   DISALLOW_COPY_AND_ASSIGN(AppWindow);
547 };
548
549 }  // namespace apps
550
551 #endif  // APPS_APP_WINDOW_H_