1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef CHROME_BROWSER_UI_ASH_LAUNCHER_CHROME_LAUNCHER_CONTROLLER_H_
6 #define CHROME_BROWSER_UI_ASH_LAUNCHER_CHROME_LAUNCHER_CONTROLLER_H_
14 #include "ash/display/display_controller.h"
15 #include "ash/shelf/shelf_delegate.h"
16 #include "ash/shelf/shelf_item_delegate.h"
17 #include "ash/shelf/shelf_item_types.h"
18 #include "ash/shelf/shelf_layout_manager_observer.h"
19 #include "ash/shelf/shelf_model_observer.h"
20 #include "ash/shelf/shelf_types.h"
21 #include "ash/shell_observer.h"
22 #include "base/basictypes.h"
23 #include "base/compiler_specific.h"
24 #include "base/memory/scoped_ptr.h"
25 #include "base/memory/scoped_vector.h"
26 #include "base/prefs/pref_change_registrar.h"
27 #include "chrome/browser/extensions/app_icon_loader.h"
28 #include "chrome/browser/prefs/pref_service_syncable_observer.h"
29 #include "chrome/browser/ui/ash/app_sync_ui_state_observer.h"
30 #include "chrome/browser/ui/ash/launcher/chrome_launcher_app_menu_item.h"
31 #include "chrome/browser/ui/ash/launcher/chrome_launcher_types.h"
32 #include "chrome/browser/ui/extensions/extension_enable_flow_delegate.h"
33 #include "chrome/common/extensions/extension_constants.h"
34 #include "content/public/browser/notification_observer.h"
35 #include "content/public/browser/notification_registrar.h"
36 #include "ui/aura/window_observer.h"
40 class BrowserShortcutLauncherItemController;
41 class BrowserStatusMonitor;
42 class ExtensionEnableFlow;
44 class LauncherItemController;
46 class ShellWindowLauncherController;
50 class ShelfItemDelegateManager;
62 namespace extensions {
70 // A list of the elements which makes up a simple menu description.
71 typedef ScopedVector<ChromeLauncherAppMenuItem> ChromeLauncherAppMenuItems;
73 // A class which needs to be overwritten dependent on the used OS to moitor
75 class ChromeLauncherControllerUserSwitchObserver {
77 ChromeLauncherControllerUserSwitchObserver() {}
78 virtual ~ChromeLauncherControllerUserSwitchObserver() {}
82 DISALLOW_COPY_AND_ASSIGN(ChromeLauncherControllerUserSwitchObserver);
85 // ChromeLauncherController manages the launcher items needed for content
86 // windows. Launcher items have a type, an optional app id, and a controller.
87 // This incarnation groups running tabs/windows in application specific lists.
88 // * Browser app windows have BrowserLauncherItemController, owned by the
89 // BrowserView instance.
90 // * App shell windows have ShellWindowLauncherItemController, owned by
91 // ShellWindowLauncherController.
92 // * Shortcuts have no LauncherItemController.
93 class ChromeLauncherController : public ash::ShelfDelegate,
94 public ash::ShelfModelObserver,
95 public ash::ShellObserver,
96 public ash::DisplayController::Observer,
97 public content::NotificationObserver,
98 public extensions::AppIconLoader::Delegate,
99 public PrefServiceSyncableObserver,
100 public AppSyncUIStateObserver,
101 public ExtensionEnableFlowDelegate,
102 public ash::ShelfLayoutManagerObserver {
104 // Indicates if a shelf item is incognito or not.
105 enum IncognitoState {
110 // Used to update the state of non plaform apps, as web contents change.
113 APP_STATE_WINDOW_ACTIVE,
118 // Mockable interface to get app ids from tabs.
121 virtual ~AppTabHelper() {}
123 // Returns the app id of the specified tab, or an empty string if there is
124 // no app. All known profiles will be queried for this.
125 virtual std::string GetAppID(content::WebContents* tab) = 0;
127 // Returns true if |id| is valid for the currently active profile.
128 // Used during restore to ignore no longer valid extensions.
129 // Note that already running applications are ignored by the restore
131 virtual bool IsValidIDForCurrentUser(const std::string& id) = 0;
133 // Sets the currently active profile for the usage of |GetAppID|.
134 virtual void SetCurrentUser(Profile* profile) = 0;
137 ChromeLauncherController(Profile* profile, ash::ShelfModel* model);
138 virtual ~ChromeLauncherController();
140 // Initializes this ChromeLauncherController.
143 // Creates an instance.
144 static ChromeLauncherController* CreateInstance(Profile* profile,
145 ash::ShelfModel* model);
147 // Returns the single ChromeLauncherController instance.
148 static ChromeLauncherController* instance() { return instance_; }
150 // Creates a new app item on the shelf for |controller|.
151 ash::ShelfID CreateAppLauncherItem(LauncherItemController* controller,
152 const std::string& app_id,
153 ash::ShelfItemStatus status);
155 // Updates the running status of an item. It will also update the status of
156 // browsers shelf item if needed.
157 void SetItemStatus(ash::ShelfID id, ash::ShelfItemStatus status);
159 // Updates the controller associated with id (which should be a shortcut).
160 // |controller| remains owned by caller.
161 void SetItemController(ash::ShelfID id, LauncherItemController* controller);
163 // Closes or unpins the shelf item.
164 void CloseLauncherItem(ash::ShelfID id);
166 // Pins the specified id. Currently only supports platform apps.
167 void Pin(ash::ShelfID id);
169 // Unpins the specified id, closing if not running.
170 void Unpin(ash::ShelfID id);
172 // Returns true if the item identified by |id| is pinned.
173 bool IsPinned(ash::ShelfID id);
175 // Pins/unpins the specified id.
176 void TogglePinned(ash::ShelfID id);
178 // Returns true if the specified item can be pinned or unpinned. Only apps can
180 bool IsPinnable(ash::ShelfID id) const;
182 // If there is no shelf item in the shelf for application |app_id|, one
183 // gets created. The (existing or created) shelf items get then locked
184 // against a users un-pinning removal.
185 void LockV1AppWithID(const std::string& app_id);
187 // A previously locked shelf item of type |app_id| gets unlocked. If the
188 // lock count reaches 0 and the item is not pinned it will go away.
189 void UnlockV1AppWithID(const std::string& app_id);
191 // Requests that the shelf item controller specified by |id| open a new
192 // instance of the app. |event_flags| holds the flags of the event which
193 // triggered this command.
194 void Launch(ash::ShelfID id, int event_flags);
196 // Closes the specified item.
197 void Close(ash::ShelfID id);
199 // Returns true if the specified item is open.
200 bool IsOpen(ash::ShelfID id);
202 // Returns true if the specified item is for a platform app.
203 bool IsPlatformApp(ash::ShelfID id);
205 // Opens a new instance of the application identified by |app_id|.
206 // Used by the app-list, and by pinned-app shelf items.
207 void LaunchApp(const std::string& app_id,
208 ash::LaunchSource source,
211 // If |app_id| is running, reactivates the app's most recently active window,
212 // otherwise launches and activates the app.
213 // Used by the app-list, and by pinned-app shelf items.
214 void ActivateApp(const std::string& app_id,
215 ash::LaunchSource source,
218 // Returns the launch type of app for the specified id.
219 extensions::LaunchType GetLaunchType(ash::ShelfID id);
221 // Set the image for a specific shelf item (e.g. when set by the app).
222 void SetLauncherItemImage(ash::ShelfID shelf_id, const gfx::ImageSkia& image);
224 // Find out if the given application |id| is a windowed app item and not a
225 // pinned item in the shelf.
226 bool IsWindowedAppInLauncher(const std::string& app_id);
228 // Updates the launch type of the app for the specified id to |launch_type|.
229 void SetLaunchType(ash::ShelfID id, extensions::LaunchType launch_type);
231 // Returns true if the user is currently logged in as a guest.
232 // Makes virtual for unittest in LauncherContextMenuTest.
233 virtual bool IsLoggedInAsGuest();
235 // Invoked when user clicks on button in the shelf and there is no last
236 // used window (or CTRL is held with the click).
237 void CreateNewWindow();
239 // Invoked when the user clicks on button in the shelf to create a new
241 void CreateNewIncognitoWindow();
243 // Updates the pinned pref state. The pinned state consists of a list pref.
244 // Each item of the list is a dictionary. The key |kAppIDPath| gives the
246 void PersistPinnedState();
248 ash::ShelfModel* model();
250 // Accessor to the currently loaded profile. Note that in multi profile use
251 // cases this might change over time.
254 // Gets the shelf auto-hide behavior on |root_window|.
255 ash::ShelfAutoHideBehavior GetShelfAutoHideBehavior(
256 aura::Window* root_window) const;
258 // Returns |true| if the user is allowed to modify the shelf auto-hide
259 // behavior on |root_window|.
260 bool CanUserModifyShelfAutoHideBehavior(aura::Window* root_window) const;
262 // Toggles the shelf auto-hide behavior on |root_window|. Does nothing if the
263 // user is not allowed to modify the auto-hide behavior.
264 void ToggleShelfAutoHideBehavior(aura::Window* root_window);
266 // The tab no longer represents its previously identified application.
267 void RemoveTabFromRunningApp(content::WebContents* tab,
268 const std::string& app_id);
270 // Notify the controller that the state of an non platform app's tabs
272 void UpdateAppState(content::WebContents* contents, AppState app_state);
274 // Returns ShelfID for |contents|. If |contents| is not an app or is not
275 // pinned, returns the id of browser shrotcut.
276 ash::ShelfID GetShelfIDForWebContents(content::WebContents* contents);
278 // Limits application refocusing to urls that match |url| for |id|.
279 void SetRefocusURLPatternForTest(ash::ShelfID id, const GURL& url);
281 // Returns the extension identified by |app_id|.
282 const extensions::Extension* GetExtensionForAppID(
283 const std::string& app_id) const;
285 // Activates a |window|. If |allow_minimize| is true and the system allows
286 // it, the the window will get minimized instead.
287 void ActivateWindowOrMinimizeIfActive(ui::BaseWindow* window,
288 bool allow_minimize);
290 // ash::ShelfDelegate overrides:
291 virtual void OnShelfCreated(ash::Shelf* shelf) OVERRIDE;
292 virtual void OnShelfDestroyed(ash::Shelf* shelf) OVERRIDE;
293 virtual ash::ShelfID GetShelfIDForAppID(const std::string& app_id) OVERRIDE;
294 virtual const std::string& GetAppIDForShelfID(ash::ShelfID id) OVERRIDE;
295 virtual void PinAppWithID(const std::string& app_id) OVERRIDE;
296 virtual bool IsAppPinned(const std::string& app_id) OVERRIDE;
297 virtual bool CanPin() const OVERRIDE;
298 virtual void UnpinAppWithID(const std::string& app_id) OVERRIDE;
300 // ash::ShelfModelObserver overrides:
301 virtual void ShelfItemAdded(int index) OVERRIDE;
302 virtual void ShelfItemRemoved(int index, ash::ShelfID id) OVERRIDE;
303 virtual void ShelfItemMoved(int start_index, int target_index) OVERRIDE;
304 virtual void ShelfItemChanged(int index,
305 const ash::ShelfItem& old_item) OVERRIDE;
306 virtual void ShelfStatusChanged() OVERRIDE;
308 // content::NotificationObserver overrides:
309 virtual void Observe(int type,
310 const content::NotificationSource& source,
311 const content::NotificationDetails& details) OVERRIDE;
313 // ash::ShellObserver overrides:
314 virtual void OnShelfAlignmentChanged(aura::Window* root_window) OVERRIDE;
316 // ash::DisplayController::Observer overrides:
317 virtual void OnDisplayConfigurationChanging() OVERRIDE;
318 virtual void OnDisplayConfigurationChanged() OVERRIDE;
320 // PrefServiceSyncableObserver overrides:
321 virtual void OnIsSyncingChanged() OVERRIDE;
323 // AppSyncUIStateObserver overrides:
324 virtual void OnAppSyncUIStatusChanged() OVERRIDE;
326 // ExtensionEnableFlowDelegate overrides:
327 virtual void ExtensionEnableFlowFinished() OVERRIDE;
328 virtual void ExtensionEnableFlowAborted(bool user_initiated) OVERRIDE;
330 // extensions::AppIconLoader overrides:
331 virtual void SetAppImage(const std::string& app_id,
332 const gfx::ImageSkia& image) OVERRIDE;
334 // ash::ShelfLayoutManagerObserver overrides:
335 virtual void OnAutoHideBehaviorChanged(
336 aura::Window* root_window,
337 ash::ShelfAutoHideBehavior new_behavior) OVERRIDE;
339 // Called when the active user has changed.
340 void ActiveUserChanged(const std::string& user_email);
342 // Called when a user got added to the session.
343 void AdditionalUserAddedToSession(Profile* profile);
345 // Get the list of all running incarnations of this item.
346 // |event_flags| specifies the flags which were set by the event which
347 // triggered this menu generation. It can be used to generate different lists.
348 ChromeLauncherAppMenuItems GetApplicationList(const ash::ShelfItem& item,
351 // Get the list of all tabs which belong to a certain application type.
352 std::vector<content::WebContents*> GetV1ApplicationsFromAppId(
355 // Activates a specified shell application.
356 void ActivateShellApp(const std::string& app_id, int index);
358 // Checks if a given |web_contents| is known to be associated with an
359 // application of type |app_id|.
360 bool IsWebContentHandledByApplication(content::WebContents* web_contents,
361 const std::string& app_id);
363 // Check if the gMail app is loaded and it can handle the given web content.
364 // This special treatment is required to address crbug.com/234268.
365 bool ContentCanBeHandledByGmailApp(content::WebContents* web_contents);
367 // Get the favicon for the application list entry for |web_contents|.
368 // Note that for incognito windows the incognito icon will be returned.
369 // If |web_contents| has not loaded, returns the default favicon.
370 gfx::Image GetAppListIcon(content::WebContents* web_contents) const;
372 // Get the title for the applicatoin list entry for |web_contents|.
373 // If |web_contents| has not loaded, returns "Net Tab".
374 base::string16 GetAppListTitle(content::WebContents* web_contents) const;
376 // Returns the LauncherItemController of BrowserShortcut.
377 BrowserShortcutLauncherItemController*
378 GetBrowserShortcutLauncherItemController();
380 LauncherItemController* GetLauncherItemController(const ash::ShelfID id);
382 // Returns true if |browser| is owned by the active user.
383 bool IsBrowserFromActiveUser(Browser* browser);
385 // Access to the BrowserStatusMonitor for tests.
386 BrowserStatusMonitor* browser_status_monitor_for_test() {
387 return browser_status_monitor_.get();
390 // Access to the ShellWindowController for tests.
391 ShellWindowLauncherController* shell_window_controller_for_test() {
392 return shell_window_controller_.get();
396 // Creates a new app shortcut item and controller on the shelf at |index|.
397 // Use kInsertItemAtEnd to add a shortcut as the last item.
398 ash::ShelfID CreateAppShortcutLauncherItem(const std::string& app_id,
401 // Sets the AppTabHelper/AppIconLoader, taking ownership of the helper class.
402 // These are intended for testing.
403 void SetAppTabHelperForTest(AppTabHelper* helper);
404 void SetAppIconLoaderForTest(extensions::AppIconLoader* loader);
405 const std::string& GetAppIdFromShelfIdForTest(ash::ShelfID id);
407 // Sets the ash::ShelfItemDelegateManager only for unittests and doesn't
408 // take an ownership of it.
409 void SetShelfItemDelegateManagerForTest(
410 ash::ShelfItemDelegateManager* manager);
413 friend class ChromeLauncherControllerTest;
414 friend class ShelfAppBrowserTest;
415 friend class LauncherPlatformAppBrowserTest;
417 typedef std::map<ash::ShelfID, LauncherItemController*> IDToItemControllerMap;
418 typedef std::list<content::WebContents*> WebContentsList;
419 typedef std::map<std::string, WebContentsList> AppIDToWebContentsListMap;
420 typedef std::map<content::WebContents*, std::string> WebContentsToAppIDMap;
422 // Remembers / restores list of running applications.
423 // Note that this order will neither be stored in the preference nor will it
424 // remember the order of closed applications since it is only temporary.
425 void RememberUnpinnedRunningApplicationOrder();
426 void RestoreUnpinnedRunningApplicationOrder(const std::string& user_id);
428 // Creates a new app shortcut item and controller on the shelf at |index|.
429 // Use kInsertItemAtEnd to add a shortcut as the last item.
430 ash::ShelfID CreateAppShortcutLauncherItemWithType(
431 const std::string& app_id,
433 ash::ShelfItemType shelf_item_type);
435 // Invoked when the associated browser or app is closed.
436 void LauncherItemClosed(ash::ShelfID id);
438 // Internal helpers for pinning and unpinning that handle both
439 // client-triggered and internal pinning operations.
440 void DoPinAppWithID(const std::string& app_id);
441 void DoUnpinAppWithID(const std::string& app_id);
443 // Pin a running app with |shelf_id| internally to |index|. It returns
444 // the index where the item was pinned.
445 int PinRunningAppInternal(int index, ash::ShelfID shelf_id);
447 // Unpin a locked application. This is an internal call which converts the
448 // model type of the given app index from a shortcut into an unpinned running
450 void UnpinRunningAppInternal(int index);
452 // Re-syncs shelf model with prefs::kPinnedLauncherApps.
453 void UpdateAppLaunchersFromPref();
455 // Persists the shelf auto-hide behavior to prefs.
456 void SetShelfAutoHideBehaviorPrefs(ash::ShelfAutoHideBehavior behavior,
457 aura::Window* root_window);
459 // Sets the shelf auto-hide behavior from prefs.
460 void SetShelfAutoHideBehaviorFromPrefs();
462 // Sets the shelf alignment from prefs.
463 void SetShelfAlignmentFromPrefs();
465 // Sets both of auto-hide behavior and alignment from prefs.
466 void SetShelfBehaviorsFromPrefs();
468 // Returns the most recently active web contents for an app.
469 content::WebContents* GetLastActiveWebContents(const std::string& app_id);
471 // Creates an app launcher to insert at |index|. Note that |index| may be
472 // adjusted by the model to meet ordering constraints.
473 // The |shelf_item_type| will be set into the ShelfModel.
474 ash::ShelfID InsertAppLauncherItem(LauncherItemController* controller,
475 const std::string& app_id,
476 ash::ShelfItemStatus status,
478 ash::ShelfItemType shelf_item_type);
480 bool HasItemController(ash::ShelfID id) const;
482 // Enumerate all Web contents which match a given shortcut |controller|.
483 std::vector<content::WebContents*> GetV1ApplicationsFromController(
484 LauncherItemController* controller);
486 // Create ShelfItem for Browser Shortcut.
487 ash::ShelfID CreateBrowserShortcutLauncherItem();
489 // Check if the given |web_contents| is in incognito mode.
490 bool IsIncognito(const content::WebContents* web_contents) const;
492 // Update browser shortcut's index.
493 void PersistChromeItemIndex(int index);
495 // Get browser shortcut's index from pref.
496 int GetChromeIconIndexFromPref() const;
498 // Depending on the provided flags, move either the chrome icon, the app icon
499 // or none to the given |target_index|. The provided |chrome_index| and
500 // |app_list_index| locations will get adjusted within this call to finalize
501 // the action and to make sure that the other item can still be moved
502 // afterwards (index adjustments).
503 void MoveChromeOrApplistToFinalPosition(
508 int* app_list_index);
510 // Finds the index of where to insert the next item.
511 int FindInsertionPoint(bool is_app_list);
513 // Get the browser shortcut's index in the shelf using the current's systems
514 // configuration of pinned and known (but not running) apps.
515 int GetChromeIconIndexForCreation();
517 // Get the list of pinned programs from the preferences.
518 std::vector<std::string> GetListOfPinnedAppsAndBrowser();
520 // Close all windowed V1 applications of a certain extension which was already
522 void CloseWindowedAppsFromRemovedExtension(const std::string& app_id);
524 // Set ShelfItemDelegate |item_delegate| for |id| and take an ownership.
525 // TODO(simon.hong81): Make this take a scoped_ptr of |item_delegate|.
526 void SetShelfItemDelegate(ash::ShelfID id,
527 ash::ShelfItemDelegate* item_delegate);
529 // Attach to a specific profile.
530 void AttachProfile(Profile* proifile);
532 // Forget the current profile to allow attaching to a new one.
533 void ReleaseProfile();
535 // Returns true if |app_id| is a Packaged App that has already launched on the
536 // native desktop and, if so, executes it as a desktop shortcut to activate
537 // desktop mode and send another OnLaunched event to the Extension.
538 bool LaunchedInNativeDesktop(const std::string& app_id);
540 static ChromeLauncherController* instance_;
542 ash::ShelfModel* model_;
544 ash::ShelfItemDelegateManager* item_delegate_manager_;
546 // Profile used for prefs and loading extensions. This is NOT necessarily the
547 // profile new windows are created with.
550 IDToItemControllerMap id_to_item_controller_map_;
552 // Maintains activation order of web contents for each app.
553 AppIDToWebContentsListMap app_id_to_web_contents_list_;
555 // Direct access to app_id for a web contents.
556 WebContentsToAppIDMap web_contents_to_app_id_;
558 // Used to track shell windows.
559 scoped_ptr<ShellWindowLauncherController> shell_window_controller_;
561 // Used to get app info for tabs.
562 scoped_ptr<AppTabHelper> app_tab_helper_;
564 // Used to load the image for an app item.
565 scoped_ptr<extensions::AppIconLoader> app_icon_loader_;
567 content::NotificationRegistrar notification_registrar_;
569 PrefChangeRegistrar pref_change_registrar_;
571 AppSyncUIState* app_sync_ui_state_;
573 scoped_ptr<ExtensionEnableFlow> extension_enable_flow_;
575 // Shelves that are currently being observed.
576 std::set<ash::Shelf*> shelves_;
578 // The owned browser status monitor.
579 scoped_ptr<BrowserStatusMonitor> browser_status_monitor_;
581 // A special observer class to detect user switches.
582 scoped_ptr<ChromeLauncherControllerUserSwitchObserver> user_switch_observer_;
584 // If true, incoming pinned state changes should be ignored.
585 bool ignore_persist_pinned_state_change_;
587 // True if each user has an own desktop.
588 bool multi_profile_desktop_separation_;
590 // The list of running & un-pinned applications for different users on hidden
592 typedef std::vector<std::string> RunningAppListIds;
593 typedef std::map<std::string, RunningAppListIds> RunningAppListIdMap;
594 RunningAppListIdMap last_used_running_application_order_;
596 DISALLOW_COPY_AND_ASSIGN(ChromeLauncherController);
599 #endif // CHROME_BROWSER_UI_ASH_LAUNCHER_CHROME_LAUNCHER_CONTROLLER_H_