Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(130)

Side by Side Diff: chrome/browser/ui/ash/launcher/chrome_launcher_controller_impl.cc

Issue 2839933005: mash: Merge ChromeLauncherController and *Impl subclass. (Closed)
Patch Set: Address comments. Created 3 years, 7 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
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.
4
5 #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_impl.h"
6
7 #include <stddef.h>
8
9 #include <vector>
10
11 #include "ash/multi_profile_uma.h"
12 #include "ash/public/cpp/app_launch_id.h"
13 #include "ash/public/cpp/shelf_item_delegate.h"
14 #include "ash/resources/grit/ash_resources.h"
15 #include "ash/root_window_controller.h"
16 #include "ash/shelf/shelf_model.h"
17 #include "ash/shelf/wm_shelf.h"
18 #include "ash/shell.h"
19 #include "ash/shell_port.h"
20 #include "ash/strings/grit/ash_strings.h"
21 #include "ash/system/tray/system_tray_delegate.h"
22 #include "ash/wm/window_util.h"
23 #include "ash/wm_window.h"
24 #include "base/command_line.h"
25 #include "base/macros.h"
26 #include "base/strings/pattern.h"
27 #include "base/strings/string_util.h"
28 #include "base/strings/utf_string_conversions.h"
29 #include "base/threading/thread_task_runner_handle.h"
30 #include "base/values.h"
31 #include "build/build_config.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/chrome_notification_types.h"
34 #include "chrome/browser/chromeos/arc/arc_util.h"
35 #include "chrome/browser/defaults.h"
36 #include "chrome/browser/extensions/extension_util.h"
37 #include "chrome/browser/prefs/incognito_mode_prefs.h"
38 #include "chrome/browser/prefs/pref_service_syncable_util.h"
39 #include "chrome/browser/profiles/profile.h"
40 #include "chrome/browser/profiles/profile_manager.h"
41 #include "chrome/browser/ui/app_list/app_list_syncable_service_factory.h"
42 #include "chrome/browser/ui/app_list/arc/arc_app_utils.h"
43 #include "chrome/browser/ui/ash/app_sync_ui_state.h"
44 #include "chrome/browser/ui/ash/ash_util.h"
45 #include "chrome/browser/ui/ash/chrome_shell_delegate.h"
46 #include "chrome/browser/ui/ash/launcher/app_shortcut_launcher_item_controller.h "
47 #include "chrome/browser/ui/ash/launcher/app_window_launcher_controller.h"
48 #include "chrome/browser/ui/ash/launcher/app_window_launcher_item_controller.h"
49 #include "chrome/browser/ui/ash/launcher/arc_app_deferred_launcher_controller.h"
50 #include "chrome/browser/ui/ash/launcher/arc_app_window_launcher_controller.h"
51 #include "chrome/browser/ui/ash/launcher/browser_shortcut_launcher_item_controll er.h"
52 #include "chrome/browser/ui/ash/launcher/browser_status_monitor.h"
53 #include "chrome/browser/ui/ash/launcher/chrome_launcher_controller_util.h"
54 #include "chrome/browser/ui/ash/launcher/launcher_arc_app_updater.h"
55 #include "chrome/browser/ui/ash/launcher/launcher_controller_helper.h"
56 #include "chrome/browser/ui/ash/launcher/launcher_extension_app_updater.h"
57 #include "chrome/browser/ui/ash/launcher/multi_profile_app_window_launcher_contr oller.h"
58 #include "chrome/browser/ui/ash/launcher/multi_profile_browser_status_monitor.h"
59 #include "chrome/browser/ui/ash/multi_user/multi_user_util.h"
60 #include "chrome/browser/ui/ash/multi_user/multi_user_window_manager.h"
61 #include "chrome/browser/ui/browser.h"
62 #include "chrome/browser/ui/browser_finder.h"
63 #include "chrome/browser/ui/browser_list.h"
64 #include "chrome/browser/ui/browser_tabstrip.h"
65 #include "chrome/browser/ui/browser_window.h"
66 #include "chrome/browser/ui/tabs/tab_strip_model.h"
67 #include "chrome/browser/web_applications/web_app.h"
68 #include "chrome/common/chrome_switches.h"
69 #include "chrome/common/pref_names.h"
70 #include "chrome/common/url_constants.h"
71 #include "chrome/grit/chromium_strings.h"
72 #include "chrome/grit/generated_resources.h"
73 #include "chrome/grit/theme_resources.h"
74 #include "components/favicon/content/content_favicon_driver.h"
75 #include "components/prefs/scoped_user_pref_update.h"
76 #include "components/signin/core/account_id/account_id.h"
77 #include "components/strings/grit/components_strings.h"
78 #include "components/sync_preferences/pref_service_syncable.h"
79 #include "components/user_manager/user_manager.h"
80 #include "content/public/browser/navigation_entry.h"
81 #include "content/public/browser/web_contents.h"
82 #include "extensions/common/extension.h"
83 #include "ui/aura/window.h"
84 #include "ui/aura/window_event_dispatcher.h"
85 #include "ui/base/l10n/l10n_util.h"
86 #include "ui/base/resource/resource_bundle.h"
87 #include "ui/base/window_open_disposition.h"
88 #include "ui/display/types/display_constants.h"
89 #include "ui/keyboard/keyboard_util.h"
90 #include "ui/resources/grit/ui_resources.h"
91 #include "ui/wm/core/window_animations.h"
92
93 using extensions::Extension;
94 using extension_misc::kChromeAppId;
95 using extension_misc::kGmailAppId;
96 using content::WebContents;
97
98 namespace {
99
100 int64_t GetDisplayIDForShelf(ash::WmShelf* shelf) {
101 display::Display display =
102 shelf->GetWindow()->GetRootWindow()->GetDisplayNearestWindow();
103 DCHECK(display.is_valid());
104 return display.id();
105 }
106
107 // A callback that does nothing after shelf item selection handling.
108 void NoopCallback(ash::ShelfAction, base::Optional<ash::MenuItemList>) {}
109
110 // Calls ItemSelected with |source|, default arguments, and no callback.
111 void SelectItemWithSource(ash::ShelfItemDelegate* delegate,
112 ash::ShelfLaunchSource source) {
113 delegate->ItemSelected(nullptr, display::kInvalidDisplayId, source,
114 base::Bind(&NoopCallback));
115 }
116
117 // Returns true if the given |item| has a pinned shelf item type.
118 bool ItemTypeIsPinned(const ash::ShelfItem& item) {
119 return item.type == ash::TYPE_PINNED_APP ||
120 item.type == ash::TYPE_BROWSER_SHORTCUT;
121 }
122
123 } // namespace
124
125 // A class to get events from ChromeOS when a user gets changed or added.
126 class ChromeLauncherControllerUserSwitchObserver
127 : public user_manager::UserManager::UserSessionStateObserver {
128 public:
129 ChromeLauncherControllerUserSwitchObserver(
130 ChromeLauncherControllerImpl* controller)
131 : controller_(controller) {
132 DCHECK(user_manager::UserManager::IsInitialized());
133 user_manager::UserManager::Get()->AddSessionStateObserver(this);
134 }
135 ~ChromeLauncherControllerUserSwitchObserver() override {
136 user_manager::UserManager::Get()->RemoveSessionStateObserver(this);
137 }
138
139 // user_manager::UserManager::UserSessionStateObserver overrides:
140 void UserAddedToSession(const user_manager::User* added_user) override;
141
142 // ChromeLauncherControllerUserSwitchObserver:
143 void OnUserProfileReadyToSwitch(Profile* profile);
144
145 private:
146 // Add a user to the session.
147 void AddUser(Profile* profile);
148
149 // The owning ChromeLauncherControllerImpl.
150 ChromeLauncherControllerImpl* controller_;
151
152 // Users which were just added to the system, but which profiles were not yet
153 // (fully) loaded.
154 std::set<std::string> added_user_ids_waiting_for_profiles_;
155
156 DISALLOW_COPY_AND_ASSIGN(ChromeLauncherControllerUserSwitchObserver);
157 };
158
159 void ChromeLauncherControllerUserSwitchObserver::UserAddedToSession(
160 const user_manager::User* active_user) {
161 Profile* profile =
162 multi_user_util::GetProfileFromAccountId(active_user->GetAccountId());
163 // If we do not have a profile yet, we postpone forwarding the notification
164 // until it is loaded.
165 if (!profile) {
166 added_user_ids_waiting_for_profiles_.insert(
167 active_user->GetAccountId().GetUserEmail());
168 } else {
169 AddUser(profile);
170 }
171 }
172
173 void ChromeLauncherControllerUserSwitchObserver::OnUserProfileReadyToSwitch(
174 Profile* profile) {
175 if (!added_user_ids_waiting_for_profiles_.empty()) {
176 // Check if the profile is from a user which was on the waiting list.
177 // TODO(alemate): added_user_ids_waiting_for_profiles_ should be
178 // a set<AccountId>
179 std::string user_id =
180 multi_user_util::GetAccountIdFromProfile(profile).GetUserEmail();
181 std::set<std::string>::iterator it =
182 std::find(added_user_ids_waiting_for_profiles_.begin(),
183 added_user_ids_waiting_for_profiles_.end(), user_id);
184 if (it != added_user_ids_waiting_for_profiles_.end()) {
185 added_user_ids_waiting_for_profiles_.erase(it);
186 AddUser(profile->GetOriginalProfile());
187 }
188 }
189 }
190
191 void ChromeLauncherControllerUserSwitchObserver::AddUser(Profile* profile) {
192 if (chrome::MultiUserWindowManager::GetMultiProfileMode() ==
193 chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED)
194 chrome::MultiUserWindowManager::GetInstance()->AddUser(profile);
195 controller_->AdditionalUserAddedToSession(profile->GetOriginalProfile());
196 }
197
198 ChromeLauncherControllerImpl::ChromeLauncherControllerImpl(
199 Profile* profile,
200 ash::ShelfModel* model)
201 : model_(model), weak_ptr_factory_(this) {
202 DCHECK(model_);
203 if (!profile) {
204 // If no profile was passed, we take the currently active profile and use it
205 // as the owner of the current desktop.
206 // Use the original profile as on chromeos we may get a temporary off the
207 // record profile, unless in guest session (where off the record profile is
208 // the right one).
209 profile = ProfileManager::GetActiveUserProfile();
210 if (!profile->IsGuestSession() && !profile->IsSystemProfile())
211 profile = profile->GetOriginalProfile();
212
213 app_sync_ui_state_ = AppSyncUIState::Get(profile);
214 if (app_sync_ui_state_)
215 app_sync_ui_state_->AddObserver(this);
216 }
217
218 // All profile relevant settings get bound to the current profile.
219 AttachProfile(profile);
220 model_->AddObserver(this);
221
222 if (arc::IsArcAllowedForProfile(this->profile()))
223 arc_deferred_launcher_.reset(new ArcAppDeferredLauncherController(this));
224
225 // In multi profile mode we might have a window manager. We try to create it
226 // here. If the instantiation fails, the manager is not needed.
227 chrome::MultiUserWindowManager::CreateInstance();
228
229 // On Chrome OS using multi profile we want to switch the content of the shelf
230 // with a user change. Note that for unit tests the instance can be NULL.
231 if (chrome::MultiUserWindowManager::GetMultiProfileMode() !=
232 chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_OFF) {
233 user_switch_observer_.reset(
234 new ChromeLauncherControllerUserSwitchObserver(this));
235 }
236
237 std::unique_ptr<AppWindowLauncherController> extension_app_window_controller;
238 // Create our v1/v2 application / browser monitors which will inform the
239 // launcher of status changes.
240 if (chrome::MultiUserWindowManager::GetMultiProfileMode() ==
241 chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED) {
242 // If running in separated destkop mode, we create the multi profile version
243 // of status monitor.
244 browser_status_monitor_.reset(new MultiProfileBrowserStatusMonitor(this));
245 browser_status_monitor_->Initialize();
246 extension_app_window_controller.reset(
247 new MultiProfileAppWindowLauncherController(this));
248 } else {
249 // Create our v1/v2 application / browser monitors which will inform the
250 // launcher of status changes.
251 browser_status_monitor_.reset(new BrowserStatusMonitor(this));
252 browser_status_monitor_->Initialize();
253 extension_app_window_controller.reset(
254 new ExtensionAppWindowLauncherController(this));
255 }
256 app_window_controllers_.push_back(std::move(extension_app_window_controller));
257 app_window_controllers_.push_back(
258 base::MakeUnique<ArcAppWindowLauncherController>(this));
259
260 // Right now ash::Shell isn't created for tests.
261 // TODO(mukai): Allows it to observe display change and write tests.
262 if (ash::Shell::HasInstance())
263 ash::Shell::Get()->window_tree_host_manager()->AddObserver(this);
264 }
265
266 ChromeLauncherControllerImpl::~ChromeLauncherControllerImpl() {
267 // Reset the BrowserStatusMonitor as it has a weak pointer to this.
268 browser_status_monitor_.reset();
269
270 // Reset the app window controllers here since it has a weak pointer to this.
271 app_window_controllers_.clear();
272
273 model_->RemoveObserver(this);
274 if (ash::Shell::HasInstance())
275 ash::Shell::Get()->window_tree_host_manager()->RemoveObserver(this);
276
277 // Release all profile dependent resources.
278 ReleaseProfile();
279
280 // Get rid of the multi user window manager instance.
281 chrome::MultiUserWindowManager::DeleteInstance();
282 }
283
284 ash::ShelfID ChromeLauncherControllerImpl::CreateAppLauncherItem(
285 std::unique_ptr<ash::ShelfItemDelegate> item_delegate,
286 ash::ShelfItemStatus status) {
287 return InsertAppLauncherItem(std::move(item_delegate), status,
288 model_->item_count(), ash::TYPE_APP);
289 }
290
291 const ash::ShelfItem* ChromeLauncherControllerImpl::GetItem(
292 ash::ShelfID id) const {
293 const int index = model_->ItemIndexByID(id);
294 if (index >= 0 && index < model_->item_count())
295 return &model_->items()[index];
296 return nullptr;
297 }
298
299 void ChromeLauncherControllerImpl::SetItemType(ash::ShelfID id,
300 ash::ShelfItemType type) {
301 const ash::ShelfItem* item = GetItem(id);
302 if (item && item->type != type) {
303 ash::ShelfItem new_item = *item;
304 new_item.type = type;
305 model_->Set(model_->ItemIndexByID(id), new_item);
306 }
307 }
308
309 void ChromeLauncherControllerImpl::SetItemStatus(ash::ShelfID id,
310 ash::ShelfItemStatus status) {
311 const ash::ShelfItem* item = GetItem(id);
312 if (item && item->status != status) {
313 ash::ShelfItem new_item = *item;
314 new_item.status = status;
315 model_->Set(model_->ItemIndexByID(id), new_item);
316 }
317 }
318
319 void ChromeLauncherControllerImpl::CloseLauncherItem(ash::ShelfID id) {
320 CHECK(id);
321 if (IsPinned(id)) {
322 // Create a new shortcut delegate.
323 SetItemStatus(id, ash::STATUS_CLOSED);
324 model_->SetShelfItemDelegate(id, AppShortcutLauncherItemController::Create(
325 GetItem(id)->app_launch_id));
326 } else {
327 RemoveShelfItem(id);
328 }
329 }
330
331 void ChromeLauncherControllerImpl::UnpinShelfItemInternal(ash::ShelfID id) {
332 const ash::ShelfItem* item = GetItem(id);
333 if (item && item->status != ash::STATUS_CLOSED)
334 UnpinRunningAppInternal(model_->ItemIndexByID(id));
335 else
336 RemoveShelfItem(id);
337 }
338
339 bool ChromeLauncherControllerImpl::IsPinned(ash::ShelfID id) {
340 const ash::ShelfItem* item = GetItem(id);
341 return item && ItemTypeIsPinned(*item);
342 }
343
344 void ChromeLauncherControllerImpl::SetV1AppStatus(const std::string& app_id,
345 ash::ShelfItemStatus status) {
346 ash::ShelfID id = GetShelfIDForAppID(app_id);
347 const ash::ShelfItem* item = GetItem(id);
348 if (item) {
349 if (!IsPinned(id) && status == ash::STATUS_CLOSED)
350 RemoveShelfItem(id);
351 else
352 SetItemStatus(id, status);
353 } else if (status != ash::STATUS_CLOSED && !app_id.empty()) {
354 InsertAppLauncherItem(
355 AppShortcutLauncherItemController::Create(ash::AppLaunchId(app_id)),
356 status, model_->item_count(), ash::TYPE_APP);
357 }
358 }
359
360 void ChromeLauncherControllerImpl::Launch(ash::ShelfID id, int event_flags) {
361 ash::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(id);
362 if (!delegate)
363 return; // In case invoked from menu and item closed while menu up.
364
365 // Launching some items replaces the associated item delegate instance,
366 // which destroys the app and launch id strings; making copies avoid crashes.
367 LaunchApp(ash::AppLaunchId(delegate->app_id(), delegate->launch_id()),
368 ash::LAUNCH_FROM_UNKNOWN, event_flags);
369 }
370
371 void ChromeLauncherControllerImpl::Close(ash::ShelfID id) {
372 ash::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(id);
373 if (!delegate)
374 return; // May happen if menu closed.
375 delegate->Close();
376 }
377
378 bool ChromeLauncherControllerImpl::IsOpen(ash::ShelfID id) {
379 const ash::ShelfItem* item = GetItem(id);
380 return item && item->status != ash::STATUS_CLOSED;
381 }
382
383 bool ChromeLauncherControllerImpl::IsPlatformApp(ash::ShelfID id) {
384 std::string app_id = GetAppIDForShelfID(id);
385 const Extension* extension = GetExtensionForAppID(app_id, profile());
386 // An extension can be synced / updated at any time and therefore not be
387 // available.
388 return extension ? extension->is_platform_app() : false;
389 }
390
391 void ChromeLauncherControllerImpl::ActivateApp(const std::string& app_id,
392 ash::ShelfLaunchSource source,
393 int event_flags) {
394 // If there is an existing non-shortcut delegate for this app, open it.
395 ash::ShelfID id = GetShelfIDForAppID(app_id);
396 if (id) {
397 SelectItemWithSource(model_->GetShelfItemDelegate(id), source);
398 return;
399 }
400
401 // Create a temporary application launcher item and use it to see if there are
402 // running instances.
403 ash::AppLaunchId app_launch_id(app_id);
404 std::unique_ptr<AppShortcutLauncherItemController> item_delegate =
405 AppShortcutLauncherItemController::Create(app_launch_id);
406 if (!item_delegate->GetRunningApplications().empty())
407 SelectItemWithSource(item_delegate.get(), source);
408 else
409 LaunchApp(app_launch_id, source, event_flags);
410 }
411
412 void ChromeLauncherControllerImpl::SetLauncherItemImage(
413 ash::ShelfID shelf_id,
414 const gfx::ImageSkia& image) {
415 const ash::ShelfItem* item = GetItem(shelf_id);
416 if (item) {
417 ash::ShelfItem new_item = *item;
418 new_item.image = image;
419 model_->Set(model_->ItemIndexByID(shelf_id), new_item);
420 }
421 }
422
423 void ChromeLauncherControllerImpl::UpdateAppState(
424 content::WebContents* contents,
425 AppState app_state) {
426 std::string app_id = launcher_controller_helper()->GetAppID(contents);
427
428 // Check if the gMail app is loaded and it matches the given content.
429 // This special treatment is needed to address crbug.com/234268.
430 if (app_id.empty() && ContentCanBeHandledByGmailApp(contents))
431 app_id = kGmailAppId;
432
433 // Check the old |app_id| for a tab. If the contents has changed we need to
434 // remove it from the previous app.
435 if (web_contents_to_app_id_.find(contents) != web_contents_to_app_id_.end()) {
436 std::string last_app_id = web_contents_to_app_id_[contents];
437 if (last_app_id != app_id) {
438 ash::ShelfID id = GetShelfIDForAppID(last_app_id);
439 if (id) {
440 // Since GetAppState() will use |web_contents_to_app_id_| we remove
441 // the connection before calling it.
442 web_contents_to_app_id_.erase(contents);
443 SetItemStatus(id, GetAppState(last_app_id));
444 }
445 }
446 }
447
448 if (app_state == APP_STATE_REMOVED)
449 web_contents_to_app_id_.erase(contents);
450 else
451 web_contents_to_app_id_[contents] = app_id;
452
453 ash::ShelfID id = GetShelfIDForAppID(app_id);
454 if (id) {
455 SetItemStatus(id, (app_state == APP_STATE_WINDOW_ACTIVE ||
456 app_state == APP_STATE_ACTIVE)
457 ? ash::STATUS_ACTIVE
458 : GetAppState(app_id));
459 }
460 }
461
462 ash::ShelfID ChromeLauncherControllerImpl::GetShelfIDForWebContents(
463 content::WebContents* contents) {
464 std::string app_id = launcher_controller_helper()->GetAppID(contents);
465 if (app_id.empty() && ContentCanBeHandledByGmailApp(contents))
466 app_id = kGmailAppId;
467
468 ash::ShelfID id = GetShelfIDForAppID(app_id);
469 // If there is no dedicated app item, use the browser shortcut item.
470 return id == ash::kInvalidShelfID ? GetShelfIDForAppID(kChromeAppId) : id;
471 }
472
473 void ChromeLauncherControllerImpl::SetRefocusURLPatternForTest(
474 ash::ShelfID id,
475 const GURL& url) {
476 const ash::ShelfItem* item = GetItem(id);
477 if (item && !IsPlatformApp(id) &&
478 (item->type == ash::TYPE_PINNED_APP || item->type == ash::TYPE_APP)) {
479 ash::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(id);
480 AppShortcutLauncherItemController* item_controller =
481 static_cast<AppShortcutLauncherItemController*>(delegate);
482 item_controller->set_refocus_url(url);
483 } else {
484 NOTREACHED() << "Invalid launcher item or type";
485 }
486 }
487
488 ash::ShelfAction ChromeLauncherControllerImpl::ActivateWindowOrMinimizeIfActive(
489 ui::BaseWindow* window,
490 bool allow_minimize) {
491 // In separated desktop mode we might have to teleport a window back to the
492 // current user.
493 if (chrome::MultiUserWindowManager::GetMultiProfileMode() ==
494 chrome::MultiUserWindowManager::MULTI_PROFILE_MODE_SEPARATED) {
495 aura::Window* native_window = window->GetNativeWindow();
496 const AccountId& current_account_id =
497 multi_user_util::GetAccountIdFromProfile(profile());
498 chrome::MultiUserWindowManager* manager =
499 chrome::MultiUserWindowManager::GetInstance();
500 if (!manager->IsWindowOnDesktopOfUser(native_window, current_account_id)) {
501 ash::MultiProfileUMA::RecordTeleportAction(
502 ash::MultiProfileUMA::TELEPORT_WINDOW_RETURN_BY_LAUNCHER);
503 manager->ShowWindowForUser(native_window, current_account_id);
504 window->Activate();
505 return ash::SHELF_ACTION_WINDOW_ACTIVATED;
506 }
507 }
508
509 if (window->IsActive() && allow_minimize) {
510 window->Minimize();
511 return ash::SHELF_ACTION_WINDOW_MINIMIZED;
512 }
513
514 window->Show();
515 window->Activate();
516 return ash::SHELF_ACTION_WINDOW_ACTIVATED;
517 }
518
519 void ChromeLauncherControllerImpl::ActiveUserChanged(
520 const std::string& user_email) {
521 // Store the order of running applications for the user which gets inactive.
522 RememberUnpinnedRunningApplicationOrder();
523 // Coming here the default profile is already switched. All profile specific
524 // resources get released and the new profile gets attached instead.
525 ReleaseProfile();
526 // When coming here, the active user has already be changed so that we can
527 // set it as active.
528 AttachProfile(ProfileManager::GetActiveUserProfile());
529 // Update the V1 applications.
530 browser_status_monitor_->ActiveUserChanged(user_email);
531 // Switch the running applications to the new user.
532 for (auto& controller : app_window_controllers_)
533 controller->ActiveUserChanged(user_email);
534 // Update the user specific shell properties from the new user profile.
535 // Shelf preferences are loaded in ChromeLauncherController::AttachProfile.
536 UpdateAppLaunchersFromPref();
537 SetVirtualKeyboardBehaviorFromPrefs();
538
539 // Restore the order of running, but unpinned applications for the activated
540 // user.
541 RestoreUnpinnedRunningApplicationOrder(user_email);
542 // TODO(crbug.com/557406): Fix this interaction pattern in Mash.
543 if (!ash_util::IsRunningInMash()) {
544 // Inform the system tray of the change.
545 ash::Shell::Get()->system_tray_delegate()->ActiveUserWasChanged();
546 // Force on-screen keyboard to reset.
547 if (keyboard::IsKeyboardEnabled())
548 ash::Shell::Get()->CreateKeyboard();
549 }
550 }
551
552 void ChromeLauncherControllerImpl::AdditionalUserAddedToSession(
553 Profile* profile) {
554 // Switch the running applications to the new user.
555 for (auto& controller : app_window_controllers_)
556 controller->AdditionalUserAddedToSession(profile);
557 }
558
559 ash::MenuItemList ChromeLauncherControllerImpl::GetAppMenuItemsForTesting(
560 const ash::ShelfItem& item) {
561 ash::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(item.id);
562 return delegate ? delegate->GetAppMenuItems(ui::EF_NONE)
563 : ash::MenuItemList();
564 }
565
566 std::vector<content::WebContents*>
567 ChromeLauncherControllerImpl::GetV1ApplicationsFromAppId(
568 const std::string& app_id) {
569 const ash::ShelfItem* item = GetItem(GetShelfIDForAppID(app_id));
570 // If there is no such item pinned to the launcher, no menu gets created.
571 if (!item || item->type != ash::TYPE_PINNED_APP)
572 return std::vector<content::WebContents*>();
573 ash::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(item->id);
574 AppShortcutLauncherItemController* item_controller =
575 static_cast<AppShortcutLauncherItemController*>(delegate);
576 return item_controller->GetRunningApplications();
577 }
578
579 void ChromeLauncherControllerImpl::ActivateShellApp(const std::string& app_id,
580 int window_index) {
581 const ash::ShelfItem* item = GetItem(GetShelfIDForAppID(app_id));
582 if (item &&
583 (item->type == ash::TYPE_APP || item->type == ash::TYPE_PINNED_APP)) {
584 ash::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(item->id);
585 AppWindowLauncherItemController* item_controller =
586 delegate->AsAppWindowLauncherItemController();
587 item_controller->ActivateIndexedApp(window_index);
588 }
589 }
590
591 bool ChromeLauncherControllerImpl::IsWebContentHandledByApplication(
592 content::WebContents* web_contents,
593 const std::string& app_id) {
594 if ((web_contents_to_app_id_.find(web_contents) !=
595 web_contents_to_app_id_.end()) &&
596 (web_contents_to_app_id_[web_contents] == app_id))
597 return true;
598 return (app_id == kGmailAppId && ContentCanBeHandledByGmailApp(web_contents));
599 }
600
601 bool ChromeLauncherControllerImpl::ContentCanBeHandledByGmailApp(
602 content::WebContents* web_contents) {
603 ash::ShelfID id = GetShelfIDForAppID(kGmailAppId);
604 if (id) {
605 const GURL url = web_contents->GetURL();
606 // We need to extend the application matching for the gMail app beyond the
607 // manifest file's specification. This is required because of the namespace
608 // overlap with the offline app ("/mail/mu/").
609 if (!base::MatchPattern(url.path(), "/mail/mu/*") &&
610 base::MatchPattern(url.path(), "/mail/*") &&
611 GetExtensionForAppID(kGmailAppId, profile()) &&
612 GetExtensionForAppID(kGmailAppId, profile())->OverlapsWithOrigin(url))
613 return true;
614 }
615 return false;
616 }
617
618 gfx::Image ChromeLauncherControllerImpl::GetAppListIcon(
619 content::WebContents* web_contents) const {
620 ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
621 if (IsIncognito(web_contents))
622 return rb.GetImageNamed(IDR_ASH_SHELF_LIST_INCOGNITO_BROWSER);
623 favicon::FaviconDriver* favicon_driver =
624 favicon::ContentFaviconDriver::FromWebContents(web_contents);
625 gfx::Image result = favicon_driver->GetFavicon();
626 if (result.IsEmpty())
627 return rb.GetImageNamed(IDR_DEFAULT_FAVICON);
628 return result;
629 }
630
631 base::string16 ChromeLauncherControllerImpl::GetAppListTitle(
632 content::WebContents* web_contents) const {
633 base::string16 title = web_contents->GetTitle();
634 if (!title.empty())
635 return title;
636 WebContentsToAppIDMap::const_iterator iter =
637 web_contents_to_app_id_.find(web_contents);
638 if (iter != web_contents_to_app_id_.end()) {
639 std::string app_id = iter->second;
640 const extensions::Extension* extension =
641 GetExtensionForAppID(app_id, profile());
642 if (extension)
643 return base::UTF8ToUTF16(extension->name());
644 }
645 return l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
646 }
647
648 BrowserShortcutLauncherItemController*
649 ChromeLauncherControllerImpl::GetBrowserShortcutLauncherItemController() {
650 ash::ShelfID id = GetShelfIDForAppID(kChromeAppId);
651 ash::mojom::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(id);
652 DCHECK(delegate) << "There should be always be a browser shortcut item.";
653 return static_cast<BrowserShortcutLauncherItemController*>(delegate);
654 }
655
656 bool ChromeLauncherControllerImpl::ShelfBoundsChangesProbablyWithUser(
657 ash::WmShelf* shelf,
658 const AccountId& account_id) const {
659 Profile* other_profile = multi_user_util::GetProfileFromAccountId(account_id);
660 if (!other_profile || other_profile == profile())
661 return false;
662
663 // Note: The Auto hide state from preferences is not the same as the actual
664 // visibility of the shelf. Depending on all the various states (full screen,
665 // no window on desktop, multi user, ..) the shelf could be shown - or not.
666 PrefService* prefs = profile()->GetPrefs();
667 PrefService* other_prefs = other_profile->GetPrefs();
668 const int64_t display = GetDisplayIDForShelf(shelf);
669 const bool currently_shown =
670 ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER ==
671 ash::launcher::GetShelfAutoHideBehaviorPref(prefs, display);
672 const bool other_shown =
673 ash::SHELF_AUTO_HIDE_BEHAVIOR_NEVER ==
674 ash::launcher::GetShelfAutoHideBehaviorPref(other_prefs, display);
675
676 return currently_shown != other_shown ||
677 ash::launcher::GetShelfAlignmentPref(prefs, display) !=
678 ash::launcher::GetShelfAlignmentPref(other_prefs, display);
679 }
680
681 void ChromeLauncherControllerImpl::OnUserProfileReadyToSwitch(
682 Profile* profile) {
683 if (user_switch_observer_.get())
684 user_switch_observer_->OnUserProfileReadyToSwitch(profile);
685 }
686
687 ArcAppDeferredLauncherController*
688 ChromeLauncherControllerImpl::GetArcDeferredLauncher() {
689 return arc_deferred_launcher_.get();
690 }
691
692 const std::string& ChromeLauncherControllerImpl::GetLaunchIDForShelfID(
693 ash::ShelfID id) {
694 ash::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(id);
695 return delegate ? delegate->launch_id() : base::EmptyString();
696 }
697
698 void ChromeLauncherControllerImpl::AttachProfile(Profile* profile_to_attach) {
699 // The base class implementation updates the helper and app icon loaders.
700 ChromeLauncherController::AttachProfile(profile_to_attach);
701
702 pref_change_registrar_.Init(profile()->GetPrefs());
703 pref_change_registrar_.Add(
704 prefs::kPolicyPinnedLauncherApps,
705 base::Bind(&ChromeLauncherControllerImpl::UpdateAppLaunchersFromPref,
706 base::Unretained(this)));
707 // Handling of prefs::kArcEnabled change should be called deferred to avoid
708 // race condition when OnAppUninstalledPrepared for ARC apps is called after
709 // UpdateAppLaunchersFromPref.
710 pref_change_registrar_.Add(
711 prefs::kArcEnabled,
712 base::Bind(
713 &ChromeLauncherControllerImpl::ScheduleUpdateAppLaunchersFromPref,
714 base::Unretained(this)));
715 pref_change_registrar_.Add(
716 prefs::kShelfAlignmentLocal,
717 base::Bind(&ChromeLauncherController::SetShelfAlignmentFromPrefs,
718 base::Unretained(this)));
719 pref_change_registrar_.Add(
720 prefs::kShelfAutoHideBehaviorLocal,
721 base::Bind(&ChromeLauncherController::SetShelfAutoHideBehaviorFromPrefs,
722 base::Unretained(this)));
723 pref_change_registrar_.Add(
724 prefs::kShelfPreferences,
725 base::Bind(&ChromeLauncherController::SetShelfBehaviorsFromPrefs,
726 base::Unretained(this)));
727 pref_change_registrar_.Add(
728 prefs::kTouchVirtualKeyboardEnabled,
729 base::Bind(
730 &ChromeLauncherControllerImpl::SetVirtualKeyboardBehaviorFromPrefs,
731 base::Unretained(this)));
732
733 std::unique_ptr<LauncherAppUpdater> extension_app_updater(
734 new LauncherExtensionAppUpdater(this, profile()));
735 app_updaters_.push_back(std::move(extension_app_updater));
736
737 if (arc::IsArcAllowedForProfile(profile())) {
738 std::unique_ptr<LauncherAppUpdater> arc_app_updater(
739 new LauncherArcAppUpdater(this, profile()));
740 app_updaters_.push_back(std::move(arc_app_updater));
741 }
742
743 app_list::AppListSyncableService* app_service =
744 app_list::AppListSyncableServiceFactory::GetForProfile(profile());
745 if (app_service)
746 app_service->AddObserverAndStart(this);
747
748 PrefServiceSyncableFromProfile(profile())->AddObserver(this);
749 }
750
751 ash::ShelfID ChromeLauncherControllerImpl::GetShelfIDForAppID(
752 const std::string& app_id) {
753 return model_->GetShelfIDForAppID(app_id);
754 }
755
756 ash::ShelfID ChromeLauncherControllerImpl::GetShelfIDForAppIDAndLaunchID(
757 const std::string& app_id,
758 const std::string& launch_id) {
759 return model_->GetShelfIDForAppIDAndLaunchID(app_id, launch_id);
760 }
761
762 const std::string& ChromeLauncherControllerImpl::GetAppIDForShelfID(
763 ash::ShelfID id) {
764 return model_->GetAppIDForShelfID(id);
765 }
766
767 void ChromeLauncherControllerImpl::PinAppWithID(const std::string& app_id) {
768 model_->PinAppWithID(app_id);
769 }
770
771 bool ChromeLauncherControllerImpl::IsAppPinned(const std::string& app_id) {
772 return model_->IsAppPinned(app_id);
773 }
774
775 void ChromeLauncherControllerImpl::UnpinAppWithID(const std::string& app_id) {
776 model_->UnpinAppWithID(app_id);
777 }
778
779 ///////////////////////////////////////////////////////////////////////////////
780 // LauncherAppUpdater::Delegate:
781
782 void ChromeLauncherControllerImpl::OnAppInstalled(
783 content::BrowserContext* browser_context,
784 const std::string& app_id) {
785 if (IsAppPinned(app_id)) {
786 // Clear and re-fetch to ensure icon is up-to-date.
787 AppIconLoader* app_icon_loader = GetAppIconLoaderForApp(app_id);
788 if (app_icon_loader) {
789 app_icon_loader->ClearImage(app_id);
790 app_icon_loader->FetchImage(app_id);
791 }
792 }
793
794 UpdateAppLaunchersFromPref();
795 }
796
797 void ChromeLauncherControllerImpl::OnAppUpdated(
798 content::BrowserContext* browser_context,
799 const std::string& app_id) {
800 AppIconLoader* app_icon_loader = GetAppIconLoaderForApp(app_id);
801 if (app_icon_loader)
802 app_icon_loader->UpdateImage(app_id);
803 }
804
805 void ChromeLauncherControllerImpl::OnAppUninstalledPrepared(
806 content::BrowserContext* browser_context,
807 const std::string& app_id) {
808 // Since we might have windowed apps of this type which might have
809 // outstanding locks which needs to be removed.
810 const Profile* profile = Profile::FromBrowserContext(browser_context);
811 ash::ShelfID shelf_id = GetShelfIDForAppID(app_id);
812 if (shelf_id != ash::kInvalidShelfID)
813 CloseWindowedAppsFromRemovedExtension(app_id, profile);
814
815 if (IsAppPinned(app_id)) {
816 if (profile == this->profile() && shelf_id != ash::kInvalidShelfID) {
817 // Some apps may be removed locally. Unpin the item without removing the
818 // pin position from profile preferences. When needed, it is automatically
819 // deleted on app list model update.
820 UnpinShelfItemInternal(shelf_id);
821 }
822 AppIconLoader* app_icon_loader = GetAppIconLoaderForApp(app_id);
823 if (app_icon_loader)
824 app_icon_loader->ClearImage(app_id);
825 }
826 }
827
828 ///////////////////////////////////////////////////////////////////////////////
829 // ChromeLauncherControllerImpl protected:
830
831 void ChromeLauncherControllerImpl::OnInit() {
832 CreateBrowserShortcutLauncherItem();
833 UpdateAppLaunchersFromPref();
834
835 // TODO(sky): update unit test so that this test isn't necessary.
836 if (ash::Shell::HasInstance())
837 SetVirtualKeyboardBehaviorFromPrefs();
838
839 prefs_observer_ =
840 ash::launcher::ChromeLauncherPrefsObserver::CreateIfNecessary(profile());
841 }
842
843 ash::ShelfID ChromeLauncherControllerImpl::CreateAppShortcutLauncherItem(
844 const ash::AppLaunchId& app_launch_id,
845 int index) {
846 return InsertAppLauncherItem(
847 AppShortcutLauncherItemController::Create(app_launch_id),
848 ash::STATUS_CLOSED, index, ash::TYPE_PINNED_APP);
849 }
850
851 ///////////////////////////////////////////////////////////////////////////////
852 // ChromeLauncherControllerImpl private:
853
854 void ChromeLauncherControllerImpl::RememberUnpinnedRunningApplicationOrder() {
855 RunningAppListIds list;
856 for (int i = 0; i < model_->item_count(); i++) {
857 if (model_->items()[i].type == ash::TYPE_APP)
858 list.push_back(GetAppIDForShelfID(model_->items()[i].id));
859 }
860 const std::string user_email =
861 multi_user_util::GetAccountIdFromProfile(profile()).GetUserEmail();
862 last_used_running_application_order_[user_email] = list;
863 }
864
865 void ChromeLauncherControllerImpl::RestoreUnpinnedRunningApplicationOrder(
866 const std::string& user_id) {
867 const RunningAppListIdMap::iterator app_id_list =
868 last_used_running_application_order_.find(user_id);
869 if (app_id_list == last_used_running_application_order_.end())
870 return;
871
872 // Find the first insertion point for running applications.
873 int running_index = model_->FirstRunningAppIndex();
874 for (const std::string& app_id : app_id_list->second) {
875 const ash::ShelfItem* item = GetItem(GetShelfIDForAppID(app_id));
876 if (item && item->type == ash::TYPE_APP) {
877 int app_index = model_->ItemIndexByID(item->id);
878 DCHECK_GE(app_index, 0);
879 if (running_index != app_index)
880 model_->Move(running_index, app_index);
881 running_index++;
882 }
883 }
884 }
885
886 void ChromeLauncherControllerImpl::RemoveShelfItem(ash::ShelfID id) {
887 const int index = model_->ItemIndexByID(id);
888 if (index >= 0 && index < model_->item_count())
889 model_->RemoveItemAt(index);
890 }
891
892 void ChromeLauncherControllerImpl::PinRunningAppInternal(
893 int index,
894 ash::ShelfID shelf_id) {
895 DCHECK_EQ(GetItem(shelf_id)->type, ash::TYPE_APP);
896 SetItemType(shelf_id, ash::TYPE_PINNED_APP);
897 int running_index = model_->ItemIndexByID(shelf_id);
898 if (running_index < index)
899 --index;
900 if (running_index != index)
901 model_->Move(running_index, index);
902 }
903
904 void ChromeLauncherControllerImpl::UnpinRunningAppInternal(int index) {
905 DCHECK(index >= 0 && index < model_->item_count());
906 ash::ShelfItem item = model_->items()[index];
907 DCHECK_EQ(item.type, ash::TYPE_PINNED_APP);
908 SetItemType(item.id, ash::TYPE_APP);
909 }
910
911 void ChromeLauncherControllerImpl::SyncPinPosition(ash::ShelfID shelf_id) {
912 DCHECK(should_sync_pin_changes());
913 DCHECK(shelf_id);
914
915 const int max_index = model_->item_count();
916 const int index = model_->ItemIndexByID(shelf_id);
917 DCHECK_GT(index, 0);
918
919 const std::string& app_id = GetAppIDForShelfID(shelf_id);
920 DCHECK(!app_id.empty());
921 const std::string& launch_id = GetLaunchIDForShelfID(shelf_id);
922
923 std::string app_id_before;
924 std::string launch_id_before;
925 std::vector<ash::AppLaunchId> app_launch_ids_after;
926
927 for (int i = index - 1; i > 0; --i) {
928 const ash::ShelfID shelf_id_before = model_->items()[i].id;
929 if (IsPinned(shelf_id_before)) {
930 app_id_before = GetAppIDForShelfID(shelf_id_before);
931 DCHECK(!app_id_before.empty());
932 launch_id_before = GetLaunchIDForShelfID(shelf_id_before);
933 break;
934 }
935 }
936
937 for (int i = index + 1; i < max_index; ++i) {
938 const ash::ShelfID shelf_id_after = model_->items()[i].id;
939 if (IsPinned(shelf_id_after)) {
940 const std::string app_id_after = GetAppIDForShelfID(shelf_id_after);
941 DCHECK(!app_id_after.empty());
942 const std::string launch_id_after = GetLaunchIDForShelfID(shelf_id_after);
943 app_launch_ids_after.push_back(
944 ash::AppLaunchId(app_id_after, launch_id_after));
945 }
946 }
947
948 ash::AppLaunchId app_launch_id_before =
949 app_id_before.empty() ? ash::AppLaunchId()
950 : ash::AppLaunchId(app_id_before, launch_id_before);
951
952 ash::launcher::SetPinPosition(profile(), ash::AppLaunchId(app_id, launch_id),
953 app_launch_id_before, app_launch_ids_after);
954 }
955
956 void ChromeLauncherControllerImpl::OnSyncModelUpdated() {
957 UpdateAppLaunchersFromPref();
958 }
959
960 void ChromeLauncherControllerImpl::OnIsSyncingChanged() {
961 UpdateAppLaunchersFromPref();
962 }
963
964 void ChromeLauncherControllerImpl::ScheduleUpdateAppLaunchersFromPref() {
965 base::ThreadTaskRunnerHandle::Get()->PostTask(
966 FROM_HERE,
967 base::Bind(&ChromeLauncherControllerImpl::UpdateAppLaunchersFromPref,
968 weak_ptr_factory_.GetWeakPtr()));
969 }
970
971 void ChromeLauncherControllerImpl::UpdateAppLaunchersFromPref() {
972 // Do not sync pin changes during this function to avoid cyclical updates.
973 // This function makes the shelf model reflect synced prefs, and should not
974 // cyclically trigger sync changes (eg. ShelfItemAdded calls SyncPinPosition).
975 ScopedPinSyncDisabler scoped_pin_sync_disabler = GetScopedPinSyncDisabler();
976
977 const std::vector<ash::AppLaunchId> pinned_apps =
978 ash::launcher::GetPinnedAppsFromPrefs(profile()->GetPrefs(),
979 launcher_controller_helper());
980
981 int index = 0;
982 // Skip app list items if it exists.
983 if (model_->items()[0].type == ash::TYPE_APP_LIST)
984 ++index;
985
986 // Apply pins in two steps. At the first step, go through the list of apps to
987 // pin, move existing pin to current position specified by |index| or create
988 // the new pin at that position.
989 for (const auto& pref_app_launch_id : pinned_apps) {
990 // Filter out apps that may be mapped wrongly.
991 // TODO(khmel): b/31703859 is to refactore shelf mapping.
992 const std::string app_id = pref_app_launch_id.app_id();
993 const std::string shelf_app_id =
994 ArcAppWindowLauncherController::GetShelfAppIdFromArcAppId(app_id);
995 if (shelf_app_id != app_id)
996 continue;
997
998 // Update apps icon if applicable.
999 OnAppUpdated(profile(), app_id);
1000
1001 // Find existing pin or app from the right of current |index|.
1002 int app_index = index;
1003 for (; app_index < model_->item_count(); ++app_index) {
1004 const ash::ShelfItem& item = model_->items()[app_index];
1005 if (item.app_launch_id.app_id() == app_id &&
1006 item.app_launch_id.launch_id() == pref_app_launch_id.launch_id()) {
1007 break;
1008 }
1009 }
1010 if (app_index < model_->item_count()) {
1011 // Found existing pin or running app.
1012 const ash::ShelfItem item = model_->items()[app_index];
1013 if (ItemTypeIsPinned(item)) {
1014 // Just move to required position or keep it inplace.
1015 model_->Move(app_index, index);
1016 } else {
1017 PinRunningAppInternal(index, item.id);
1018 }
1019 DCHECK_EQ(model_->ItemIndexByID(item.id), index);
1020 } else {
1021 // This is fresh pin. Create new one.
1022 DCHECK_NE(app_id, kChromeAppId);
1023 CreateAppShortcutLauncherItem(pref_app_launch_id, index);
1024 }
1025 ++index;
1026 }
1027
1028 // At second step remove any pin to the right from the current index.
1029 while (index < model_->item_count()) {
1030 const ash::ShelfItem item = model_->items()[index];
1031 if (item.type == ash::TYPE_PINNED_APP)
1032 UnpinShelfItemInternal(item.id);
1033 else
1034 ++index;
1035 }
1036
1037 UpdatePolicyPinnedAppsFromPrefs();
1038 }
1039
1040 void ChromeLauncherControllerImpl::UpdatePolicyPinnedAppsFromPrefs() {
1041 for (int index = 0; index < model_->item_count(); index++) {
1042 ash::ShelfItem item = model_->items()[index];
1043 const bool pinned_by_policy =
1044 GetPinnableForAppID(item.app_launch_id.app_id(), profile()) ==
1045 AppListControllerDelegate::PIN_FIXED;
1046 if (item.pinned_by_policy != pinned_by_policy) {
1047 item.pinned_by_policy = pinned_by_policy;
1048 model_->Set(index, item);
1049 }
1050 }
1051 }
1052
1053 void ChromeLauncherControllerImpl::SetVirtualKeyboardBehaviorFromPrefs() {
1054 const PrefService* service = profile()->GetPrefs();
1055 const bool was_enabled = keyboard::IsKeyboardEnabled();
1056 if (!service->HasPrefPath(prefs::kTouchVirtualKeyboardEnabled)) {
1057 keyboard::SetKeyboardShowOverride(keyboard::KEYBOARD_SHOW_OVERRIDE_NONE);
1058 } else {
1059 const bool enable =
1060 service->GetBoolean(prefs::kTouchVirtualKeyboardEnabled);
1061 keyboard::SetKeyboardShowOverride(
1062 enable ? keyboard::KEYBOARD_SHOW_OVERRIDE_ENABLED
1063 : keyboard::KEYBOARD_SHOW_OVERRIDE_DISABLED);
1064 }
1065 // TODO(crbug.com/557406): Fix this interaction pattern in Mash.
1066 if (!ash_util::IsRunningInMash()) {
1067 const bool is_enabled = keyboard::IsKeyboardEnabled();
1068 if (was_enabled && !is_enabled)
1069 ash::Shell::Get()->DeactivateKeyboard();
1070 else if (is_enabled && !was_enabled)
1071 ash::Shell::Get()->CreateKeyboard();
1072 }
1073 }
1074
1075 ash::ShelfItemStatus ChromeLauncherControllerImpl::GetAppState(
1076 const std::string& app_id) {
1077 ash::ShelfItemStatus status = ash::STATUS_CLOSED;
1078 for (WebContentsToAppIDMap::iterator it = web_contents_to_app_id_.begin();
1079 it != web_contents_to_app_id_.end(); ++it) {
1080 if (it->second == app_id) {
1081 Browser* browser = chrome::FindBrowserWithWebContents(it->first);
1082 // Usually there should never be an item in our |web_contents_to_app_id_|
1083 // list which got deleted already. However - in some situations e.g.
1084 // Browser::SwapTabContent there is temporarily no associated browser.
1085 if (!browser)
1086 continue;
1087 if (browser->window()->IsActive()) {
1088 return browser->tab_strip_model()->GetActiveWebContents() == it->first
1089 ? ash::STATUS_ACTIVE
1090 : ash::STATUS_RUNNING;
1091 } else {
1092 status = ash::STATUS_RUNNING;
1093 }
1094 }
1095 }
1096 return status;
1097 }
1098
1099 ash::ShelfID ChromeLauncherControllerImpl::InsertAppLauncherItem(
1100 std::unique_ptr<ash::ShelfItemDelegate> item_delegate,
1101 ash::ShelfItemStatus status,
1102 int index,
1103 ash::ShelfItemType shelf_item_type) {
1104 ash::ShelfID id = model_->next_id();
1105 CHECK(!GetItem(id));
1106 CHECK(item_delegate);
1107 // Ash's ShelfWindowWatcher handles app panel windows separately.
1108 DCHECK_NE(ash::TYPE_APP_PANEL, shelf_item_type);
1109 ash::ShelfItem item;
1110 item.status = status;
1111 item.type = shelf_item_type;
1112 item.app_launch_id = item_delegate->app_launch_id();
1113 // Set the delegate first to avoid constructing one in ShelfItemAdded.
1114 model_->SetShelfItemDelegate(id, std::move(item_delegate));
1115 model_->AddAt(index, item);
1116 return id;
1117 }
1118
1119 void ChromeLauncherControllerImpl::CreateBrowserShortcutLauncherItem() {
1120 // Do not sync the pin position of the browser shortcut item when it is added;
1121 // its initial position before prefs have loaded is unimportant and the sync
1122 // service may not yet be initialized.
1123 ScopedPinSyncDisabler scoped_pin_sync_disabler = GetScopedPinSyncDisabler();
1124
1125 ash::ShelfItem browser_shortcut;
1126 browser_shortcut.type = ash::TYPE_BROWSER_SHORTCUT;
1127 ResourceBundle& rb = ResourceBundle::GetSharedInstance();
1128 browser_shortcut.image = *rb.GetImageSkiaNamed(IDR_PRODUCT_LOGO_32);
1129 browser_shortcut.title = l10n_util::GetStringUTF16(IDS_PRODUCT_NAME);
1130 browser_shortcut.app_launch_id = ash::AppLaunchId(kChromeAppId);
1131 ash::ShelfID id = model_->next_id();
1132 std::unique_ptr<BrowserShortcutLauncherItemController> item_delegate =
1133 base::MakeUnique<BrowserShortcutLauncherItemController>(model_);
1134 BrowserShortcutLauncherItemController* item_controller = item_delegate.get();
1135 // Set the delegate first to avoid constructing another one in ShelfItemAdded.
1136 model_->SetShelfItemDelegate(id, std::move(item_delegate));
1137 model_->AddAt(0, browser_shortcut);
1138 item_controller->UpdateBrowserItemState();
1139 }
1140
1141 bool ChromeLauncherControllerImpl::IsIncognito(
1142 const content::WebContents* web_contents) const {
1143 const Profile* profile =
1144 Profile::FromBrowserContext(web_contents->GetBrowserContext());
1145 return profile->IsOffTheRecord() && !profile->IsGuestSession() &&
1146 !profile->IsSystemProfile();
1147 }
1148
1149 int ChromeLauncherControllerImpl::FindInsertionPoint() {
1150 for (int i = model_->item_count() - 1; i > 0; --i) {
1151 if (ItemTypeIsPinned(model_->items()[i]))
1152 return i;
1153 }
1154 return 0;
1155 }
1156
1157 void ChromeLauncherControllerImpl::CloseWindowedAppsFromRemovedExtension(
1158 const std::string& app_id,
1159 const Profile* profile) {
1160 // This function cannot rely on the controller's enumeration functionality
1161 // since the extension has already been unloaded.
1162 const BrowserList* browser_list = BrowserList::GetInstance();
1163 std::vector<Browser*> browser_to_close;
1164 for (BrowserList::const_reverse_iterator it =
1165 browser_list->begin_last_active();
1166 it != browser_list->end_last_active(); ++it) {
1167 Browser* browser = *it;
1168 if (!browser->is_type_tabbed() && browser->is_type_popup() &&
1169 browser->is_app() &&
1170 app_id ==
1171 web_app::GetExtensionIdFromApplicationName(browser->app_name()) &&
1172 profile == browser->profile()) {
1173 browser_to_close.push_back(browser);
1174 }
1175 }
1176 while (!browser_to_close.empty()) {
1177 TabStripModel* tab_strip = browser_to_close.back()->tab_strip_model();
1178 if (!tab_strip->empty())
1179 tab_strip->CloseWebContentsAt(0, TabStripModel::CLOSE_NONE);
1180 browser_to_close.pop_back();
1181 }
1182 }
1183
1184 void ChromeLauncherControllerImpl::ReleaseProfile() {
1185 if (app_sync_ui_state_)
1186 app_sync_ui_state_->RemoveObserver(this);
1187
1188 app_updaters_.clear();
1189
1190 prefs_observer_.reset();
1191
1192 pref_change_registrar_.RemoveAll();
1193
1194 app_list::AppListSyncableService* app_service =
1195 app_list::AppListSyncableServiceFactory::GetForProfile(profile());
1196 if (app_service)
1197 app_service->RemoveObserver(this);
1198
1199 PrefServiceSyncableFromProfile(profile())->RemoveObserver(this);
1200 }
1201
1202 ///////////////////////////////////////////////////////////////////////////////
1203 // ash::ShelfModelObserver:
1204
1205 void ChromeLauncherControllerImpl::ShelfItemAdded(int index) {
1206 // Update the pin position preference as needed.
1207 ash::ShelfItem item = model_->items()[index];
1208 if (ItemTypeIsPinned(item) && should_sync_pin_changes())
1209 SyncPinPosition(item.id);
1210
1211 // TODO(khmel): Fix this Arc application id mapping. See http://b/31703859
1212 const std::string shelf_app_id =
1213 ArcAppWindowLauncherController::GetShelfAppIdFromArcAppId(
1214 item.app_launch_id.app_id());
1215
1216 // Fetch and update the icon for the app's item.
1217 AppIconLoader* app_icon_loader = GetAppIconLoaderForApp(shelf_app_id);
1218 if (app_icon_loader) {
1219 app_icon_loader->FetchImage(shelf_app_id);
1220 app_icon_loader->UpdateImage(shelf_app_id);
1221 }
1222
1223 // Update the item with any missing Chrome-specific info.
1224 if (item.type == ash::TYPE_APP || item.type == ash::TYPE_PINNED_APP) {
1225 bool needs_update = false;
1226 if (item.image.isNull()) {
1227 needs_update = true;
1228 item.image = extensions::util::GetDefaultAppIcon();
1229 }
1230 if (item.title.empty()) {
1231 needs_update = true;
1232 item.title =
1233 LauncherControllerHelper::GetAppTitle(profile(), shelf_app_id);
1234 }
1235 ash::ShelfItemStatus status = GetAppState(shelf_app_id);
1236 if (status != item.status && status != ash::STATUS_CLOSED) {
1237 needs_update = true;
1238 item.status = status;
1239 }
1240 if (needs_update)
1241 model_->Set(index, item);
1242 }
1243
1244 // Construct a ShelfItemDelegate for the item if one does not yet exist.
1245 if (!model_->GetShelfItemDelegate(item.id)) {
1246 model_->SetShelfItemDelegate(
1247 item.id, AppShortcutLauncherItemController::Create(ash::AppLaunchId(
1248 shelf_app_id, item.app_launch_id.launch_id())));
1249 }
1250 }
1251
1252 void ChromeLauncherControllerImpl::ShelfItemRemoved(
1253 int index,
1254 const ash::ShelfItem& old_item) {
1255 // TODO(khmel): Fix this Arc application id mapping. See http://b/31703859
1256 const std::string shelf_app_id =
1257 ArcAppWindowLauncherController::GetShelfAppIdFromArcAppId(
1258 old_item.app_launch_id.app_id());
1259
1260 // Remove the pin position from preferences as needed.
1261 if (ItemTypeIsPinned(old_item) && should_sync_pin_changes()) {
1262 ash::AppLaunchId app_launch_id(shelf_app_id,
1263 old_item.app_launch_id.launch_id());
1264 ash::launcher::RemovePinPosition(profile(), app_launch_id);
1265 }
1266
1267 AppIconLoader* app_icon_loader = GetAppIconLoaderForApp(shelf_app_id);
1268 if (app_icon_loader)
1269 app_icon_loader->ClearImage(shelf_app_id);
1270 }
1271
1272 void ChromeLauncherControllerImpl::ShelfItemMoved(int start_index,
1273 int target_index) {
1274 // Update the pin position preference as needed.
1275 const ash::ShelfItem& item = model_->items()[target_index];
1276 DCHECK_NE(ash::TYPE_APP_LIST, item.type);
1277 if (ItemTypeIsPinned(item) && should_sync_pin_changes())
1278 SyncPinPosition(item.id);
1279 }
1280
1281 void ChromeLauncherControllerImpl::ShelfItemChanged(
1282 int index,
1283 const ash::ShelfItem& old_item) {
1284 if (!should_sync_pin_changes())
1285 return;
1286
1287 const ash::ShelfItem& item = model_->items()[index];
1288 // Add or remove the pin position from preferences as needed.
1289 if (!ItemTypeIsPinned(old_item) && ItemTypeIsPinned(item)) {
1290 SyncPinPosition(item.id);
1291 } else if (ItemTypeIsPinned(old_item) && !ItemTypeIsPinned(item)) {
1292 // TODO(khmel): Fix this Arc application id mapping. See http://b/31703859
1293 const std::string shelf_app_id =
1294 ArcAppWindowLauncherController::GetShelfAppIdFromArcAppId(
1295 old_item.app_launch_id.app_id());
1296
1297 ash::AppLaunchId app_launch_id(shelf_app_id,
1298 old_item.app_launch_id.launch_id());
1299 ash::launcher::RemovePinPosition(profile(), app_launch_id);
1300 }
1301 }
1302
1303 ///////////////////////////////////////////////////////////////////////////////
1304 // ash::WindowTreeHostManager::Observer:
1305
1306 void ChromeLauncherControllerImpl::OnDisplayConfigurationChanged() {
1307 // In BOTTOM_LOCKED state, ignore the call of SetShelfBehaviorsFromPrefs.
1308 // Because it might be called by some operations, like crbug.com/627040
1309 // rotating screen.
1310 ash::WmShelf* shelf =
1311 ash::WmShelf::ForWindow(ash::ShellPort::Get()->GetPrimaryRootWindow());
1312 if (shelf->alignment() != ash::SHELF_ALIGNMENT_BOTTOM_LOCKED)
1313 SetShelfBehaviorsFromPrefs();
1314 }
1315
1316 ///////////////////////////////////////////////////////////////////////////////
1317 // AppSyncUIStateObserver:
1318
1319 void ChromeLauncherControllerImpl::OnAppSyncUIStatusChanged() {
1320 // Update the app list button title to reflect the syncing status.
1321 base::string16 title = l10n_util::GetStringUTF16(
1322 app_sync_ui_state_->status() == AppSyncUIState::STATUS_SYNCING
1323 ? IDS_ASH_SHELF_APP_LIST_LAUNCHER_SYNCING_TITLE
1324 : IDS_ASH_SHELF_APP_LIST_LAUNCHER_TITLE);
1325
1326 const int app_list_index = model_->GetItemIndexForType(ash::TYPE_APP_LIST);
1327 DCHECK_GE(app_list_index, 0);
1328 ash::ShelfItem item = model_->items()[app_list_index];
1329 if (item.title != title) {
1330 item.title = title;
1331 model_->Set(app_list_index, item);
1332 }
1333 }
1334
1335 ///////////////////////////////////////////////////////////////////////////////
1336 // AppIconLoaderDelegate:
1337
1338 void ChromeLauncherControllerImpl::OnAppImageUpdated(
1339 const std::string& app_id,
1340 const gfx::ImageSkia& image) {
1341 // TODO: need to get this working for shortcuts.
1342 for (int index = 0; index < model_->item_count(); ++index) {
1343 ash::ShelfItem item = model_->items()[index];
1344 ash::ShelfItemDelegate* delegate = model_->GetShelfItemDelegate(item.id);
1345 if (item.type == ash::TYPE_APP_PANEL || !delegate ||
1346 delegate->image_set_by_controller() ||
1347 item.app_launch_id.app_id() != app_id) {
1348 continue;
1349 }
1350 item.image = image;
1351 if (arc_deferred_launcher_)
1352 arc_deferred_launcher_->MaybeApplySpinningEffect(app_id, &item.image);
1353 model_->Set(index, item);
1354 // It's possible we're waiting on more than one item, so don't break.
1355 }
1356 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698