1 /*
2  * Copyright (C) 2017 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
5  * except in compliance with the License. You may obtain a copy of the License at
6  *
7  *      http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software distributed under the
10  * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
11  * KIND, either express or implied. See the License for the specific language governing
12  * permissions and limitations under the License.
13  */
14 
15 package com.android.systemui;
16 
17 import android.annotation.Nullable;
18 import android.app.INotificationManager;
19 import android.hardware.SensorPrivacyManager;
20 import android.hardware.display.NightDisplayListener;
21 import android.os.Handler;
22 import android.os.Looper;
23 import android.util.ArrayMap;
24 import android.util.DisplayMetrics;
25 import android.view.IWindowManager;
26 
27 import com.android.internal.annotations.VisibleForTesting;
28 import com.android.internal.logging.MetricsLogger;
29 import com.android.internal.statusbar.IStatusBarService;
30 import com.android.internal.util.Preconditions;
31 import com.android.keyguard.clock.ClockManager;
32 import com.android.settingslib.bluetooth.LocalBluetoothManager;
33 import com.android.systemui.appops.AppOpsController;
34 import com.android.systemui.assist.AssistManager;
35 import com.android.systemui.bubbles.BubbleController;
36 import com.android.systemui.colorextraction.SysuiColorExtractor;
37 import com.android.systemui.dock.DockManager;
38 import com.android.systemui.fragments.FragmentService;
39 import com.android.systemui.keyguard.ScreenLifecycle;
40 import com.android.systemui.keyguard.WakefulnessLifecycle;
41 import com.android.systemui.plugins.ActivityStarter;
42 import com.android.systemui.plugins.DarkIconDispatcher;
43 import com.android.systemui.plugins.FalsingManager;
44 import com.android.systemui.plugins.PluginDependencyProvider;
45 import com.android.systemui.plugins.VolumeDialogController;
46 import com.android.systemui.plugins.statusbar.StatusBarStateController;
47 import com.android.systemui.power.EnhancedEstimates;
48 import com.android.systemui.power.PowerUI;
49 import com.android.systemui.recents.OverviewProxyService;
50 import com.android.systemui.shared.plugins.PluginManager;
51 import com.android.systemui.shared.system.ActivityManagerWrapper;
52 import com.android.systemui.shared.system.DevicePolicyManagerWrapper;
53 import com.android.systemui.shared.system.PackageManagerWrapper;
54 import com.android.systemui.statusbar.NavigationBarController;
55 import com.android.systemui.statusbar.NotificationListener;
56 import com.android.systemui.statusbar.NotificationLockscreenUserManager;
57 import com.android.systemui.statusbar.NotificationMediaManager;
58 import com.android.systemui.statusbar.NotificationRemoteInputManager;
59 import com.android.systemui.statusbar.NotificationViewHierarchyManager;
60 import com.android.systemui.statusbar.SmartReplyController;
61 import com.android.systemui.statusbar.VibratorHelper;
62 import com.android.systemui.statusbar.notification.NotificationAlertingManager;
63 import com.android.systemui.statusbar.notification.NotificationEntryManager;
64 import com.android.systemui.statusbar.notification.NotificationFilter;
65 import com.android.systemui.statusbar.notification.NotificationInterruptionStateProvider;
66 import com.android.systemui.statusbar.notification.VisualStabilityManager;
67 import com.android.systemui.statusbar.notification.collection.NotificationData.KeyguardEnvironment;
68 import com.android.systemui.statusbar.notification.logging.NotificationLogger;
69 import com.android.systemui.statusbar.notification.row.ChannelEditorDialogController;
70 import com.android.systemui.statusbar.notification.row.NotificationBlockingHelperManager;
71 import com.android.systemui.statusbar.notification.row.NotificationGutsManager;
72 import com.android.systemui.statusbar.phone.AutoHideController;
73 import com.android.systemui.statusbar.phone.KeyguardDismissUtil;
74 import com.android.systemui.statusbar.phone.LightBarController;
75 import com.android.systemui.statusbar.phone.LockscreenGestureLogger;
76 import com.android.systemui.statusbar.phone.ManagedProfileController;
77 import com.android.systemui.statusbar.phone.NavigationModeController;
78 import com.android.systemui.statusbar.phone.NotificationGroupAlertTransferHelper;
79 import com.android.systemui.statusbar.phone.NotificationGroupManager;
80 import com.android.systemui.statusbar.phone.ShadeController;
81 import com.android.systemui.statusbar.phone.StatusBarIconController;
82 import com.android.systemui.statusbar.phone.StatusBarWindowController;
83 import com.android.systemui.statusbar.policy.AccessibilityController;
84 import com.android.systemui.statusbar.policy.AccessibilityManagerWrapper;
85 import com.android.systemui.statusbar.policy.BatteryController;
86 import com.android.systemui.statusbar.policy.BluetoothController;
87 import com.android.systemui.statusbar.policy.CastController;
88 import com.android.systemui.statusbar.policy.ConfigurationController;
89 import com.android.systemui.statusbar.policy.DataSaverController;
90 import com.android.systemui.statusbar.policy.DeviceProvisionedController;
91 import com.android.systemui.statusbar.policy.ExtensionController;
92 import com.android.systemui.statusbar.policy.FlashlightController;
93 import com.android.systemui.statusbar.policy.HotspotController;
94 import com.android.systemui.statusbar.policy.KeyguardMonitor;
95 import com.android.systemui.statusbar.policy.LocationController;
96 import com.android.systemui.statusbar.policy.NetworkController;
97 import com.android.systemui.statusbar.policy.NextAlarmController;
98 import com.android.systemui.statusbar.policy.RemoteInputQuickSettingsDisabler;
99 import com.android.systemui.statusbar.policy.RotationLockController;
100 import com.android.systemui.statusbar.policy.SecurityController;
101 import com.android.systemui.statusbar.policy.SensorPrivacyController;
102 import com.android.systemui.statusbar.policy.SmartReplyConstants;
103 import com.android.systemui.statusbar.policy.UserInfoController;
104 import com.android.systemui.statusbar.policy.UserSwitcherController;
105 import com.android.systemui.statusbar.policy.ZenModeController;
106 import com.android.systemui.tuner.TunablePadding.TunablePaddingService;
107 import com.android.systemui.tuner.TunerService;
108 import com.android.systemui.util.AsyncSensorManager;
109 import com.android.systemui.util.leak.GarbageMonitor;
110 import com.android.systemui.util.leak.LeakDetector;
111 import com.android.systemui.util.leak.LeakReporter;
112 
113 import java.io.FileDescriptor;
114 import java.io.PrintWriter;
115 import java.util.function.Consumer;
116 
117 import javax.inject.Inject;
118 import javax.inject.Named;
119 
120 import dagger.Lazy;
121 import dagger.Subcomponent;
122 
123 /**
124  * Class to handle ugly dependencies throughout sysui until we determine the
125  * long-term dependency injection solution.
126  *
127  * Classes added here should be things that are expected to live the lifetime of sysui,
128  * and are generally applicable to many parts of sysui. They will be lazily
129  * initialized to ensure they aren't created on form factors that don't need them
130  * (e.g. HotspotController on TV). Despite being lazily initialized, it is expected
131  * that all dependencies will be gotten during sysui startup, and not during runtime
132  * to avoid jank.
133  *
134  * All classes used here are expected to manage their own lifecycle, meaning if
135  * they have no clients they should not have any registered resources like bound
136  * services, registered receivers, etc.
137  */
138 public class Dependency {
139     /**
140      * Key for getting a background Looper for background work.
141      */
142     public static final String BG_LOOPER_NAME = "background_looper";
143     /**
144      * Key for getting a background Handler for background work.
145      */
146     public static final String BG_HANDLER_NAME = "background_handler";
147     /**
148      * Key for getting a Handler for receiving time tick broadcasts on.
149      */
150     public static final String TIME_TICK_HANDLER_NAME = "time_tick_handler";
151     /**
152      * Generic handler on the main thread.
153      */
154     public static final String MAIN_HANDLER_NAME = "main_handler";
155 
156     /**
157      * An email address to send memory leak reports to by default.
158      */
159     public static final String LEAK_REPORT_EMAIL_NAME = "leak_report_email";
160 
161     /**
162      * Whether this platform supports long-pressing notifications to show notification channel
163      * settings.
164      */
165     public static final String ALLOW_NOTIFICATION_LONG_PRESS_NAME = "allow_notif_longpress";
166 
167     /**
168      * Key for getting a background Looper for background work.
169      */
170     public static final DependencyKey<Looper> BG_LOOPER = new DependencyKey<>(BG_LOOPER_NAME);
171     /**
172      * Key for getting a background Handler for background work.
173      */
174     public static final DependencyKey<Handler> BG_HANDLER = new DependencyKey<>(BG_HANDLER_NAME);
175     /**
176      * Key for getting a Handler for receiving time tick broadcasts on.
177      */
178     public static final DependencyKey<Handler> TIME_TICK_HANDLER =
179             new DependencyKey<>(TIME_TICK_HANDLER_NAME);
180     /**
181      * Generic handler on the main thread.
182      */
183     public static final DependencyKey<Handler> MAIN_HANDLER =
184             new DependencyKey<>(MAIN_HANDLER_NAME);
185 
186     /**
187      * An email address to send memory leak reports to by default.
188      */
189     public static final DependencyKey<String> LEAK_REPORT_EMAIL =
190             new DependencyKey<>(LEAK_REPORT_EMAIL_NAME);
191 
192     private final ArrayMap<Object, Object> mDependencies = new ArrayMap<>();
193     private final ArrayMap<Object, LazyDependencyCreator> mProviders = new ArrayMap<>();
194 
195     @Inject Lazy<ActivityStarter> mActivityStarter;
196     @Inject Lazy<ActivityStarterDelegate> mActivityStarterDelegate;
197     @Inject Lazy<AsyncSensorManager> mAsyncSensorManager;
198     @Inject Lazy<BluetoothController> mBluetoothController;
199     @Inject Lazy<LocationController> mLocationController;
200     @Inject Lazy<RotationLockController> mRotationLockController;
201     @Inject Lazy<NetworkController> mNetworkController;
202     @Inject Lazy<ZenModeController> mZenModeController;
203     @Inject Lazy<HotspotController> mHotspotController;
204     @Inject Lazy<CastController> mCastController;
205     @Inject Lazy<FlashlightController> mFlashlightController;
206     @Inject Lazy<UserSwitcherController> mUserSwitcherController;
207     @Inject Lazy<UserInfoController> mUserInfoController;
208     @Inject Lazy<KeyguardMonitor> mKeyguardMonitor;
209     @Inject Lazy<BatteryController> mBatteryController;
210     @Inject Lazy<NightDisplayListener> mNightDisplayListener;
211     @Inject Lazy<ManagedProfileController> mManagedProfileController;
212     @Inject Lazy<NextAlarmController> mNextAlarmController;
213     @Inject Lazy<DataSaverController> mDataSaverController;
214     @Inject Lazy<AccessibilityController> mAccessibilityController;
215     @Inject Lazy<DeviceProvisionedController> mDeviceProvisionedController;
216     @Inject Lazy<PluginManager> mPluginManager;
217     @Inject Lazy<AssistManager> mAssistManager;
218     @Inject Lazy<SecurityController> mSecurityController;
219     @Inject Lazy<LeakDetector> mLeakDetector;
220     @Inject Lazy<LeakReporter> mLeakReporter;
221     @Inject Lazy<GarbageMonitor> mGarbageMonitor;
222     @Inject Lazy<TunerService> mTunerService;
223     @Inject Lazy<StatusBarWindowController> mStatusBarWindowController;
224     @Inject Lazy<DarkIconDispatcher> mDarkIconDispatcher;
225     @Inject Lazy<ConfigurationController> mConfigurationController;
226     @Inject Lazy<StatusBarIconController> mStatusBarIconController;
227     @Inject Lazy<ScreenLifecycle> mScreenLifecycle;
228     @Inject Lazy<WakefulnessLifecycle> mWakefulnessLifecycle;
229     @Inject Lazy<FragmentService> mFragmentService;
230     @Inject Lazy<ExtensionController> mExtensionController;
231     @Inject Lazy<PluginDependencyProvider> mPluginDependencyProvider;
232     @Nullable
233     @Inject Lazy<LocalBluetoothManager> mLocalBluetoothManager;
234     @Inject Lazy<VolumeDialogController> mVolumeDialogController;
235     @Inject Lazy<MetricsLogger> mMetricsLogger;
236     @Inject Lazy<AccessibilityManagerWrapper> mAccessibilityManagerWrapper;
237     @Inject Lazy<SysuiColorExtractor> mSysuiColorExtractor;
238     @Inject Lazy<TunablePaddingService> mTunablePaddingService;
239     @Inject Lazy<ForegroundServiceController> mForegroundServiceController;
240     @Inject Lazy<UiOffloadThread> mUiOffloadThread;
241     @Inject Lazy<PowerUI.WarningsUI> mWarningsUI;
242     @Inject Lazy<LightBarController> mLightBarController;
243     @Inject Lazy<IWindowManager> mIWindowManager;
244     @Inject Lazy<OverviewProxyService> mOverviewProxyService;
245     @Inject Lazy<NavigationModeController> mNavBarModeController;
246     @Inject Lazy<EnhancedEstimates> mEnhancedEstimates;
247     @Inject Lazy<VibratorHelper> mVibratorHelper;
248     @Inject Lazy<IStatusBarService> mIStatusBarService;
249     @Inject Lazy<DisplayMetrics> mDisplayMetrics;
250     @Inject Lazy<LockscreenGestureLogger> mLockscreenGestureLogger;
251     @Inject Lazy<KeyguardEnvironment> mKeyguardEnvironment;
252     @Inject Lazy<ShadeController> mShadeController;
253     @Inject Lazy<NotificationRemoteInputManager.Callback> mNotificationRemoteInputManagerCallback;
254     @Inject Lazy<InitController> mInitController;
255     @Inject Lazy<AppOpsController> mAppOpsController;
256     @Inject Lazy<NavigationBarController> mNavigationBarController;
257     @Inject Lazy<StatusBarStateController> mStatusBarStateController;
258     @Inject Lazy<NotificationLockscreenUserManager> mNotificationLockscreenUserManager;
259     @Inject Lazy<NotificationGroupAlertTransferHelper> mNotificationGroupAlertTransferHelper;
260     @Inject Lazy<NotificationGroupManager> mNotificationGroupManager;
261     @Inject Lazy<VisualStabilityManager> mVisualStabilityManager;
262     @Inject Lazy<NotificationGutsManager> mNotificationGutsManager;
263     @Inject Lazy<NotificationMediaManager> mNotificationMediaManager;
264     @Inject Lazy<NotificationBlockingHelperManager> mNotificationBlockingHelperManager;
265     @Inject Lazy<NotificationRemoteInputManager> mNotificationRemoteInputManager;
266     @Inject Lazy<SmartReplyConstants> mSmartReplyConstants;
267     @Inject Lazy<NotificationListener> mNotificationListener;
268     @Inject Lazy<NotificationLogger> mNotificationLogger;
269     @Inject Lazy<NotificationViewHierarchyManager> mNotificationViewHierarchyManager;
270     @Inject Lazy<NotificationFilter> mNotificationFilter;
271     @Inject Lazy<NotificationInterruptionStateProvider> mNotificationInterruptionStateProvider;
272     @Inject Lazy<KeyguardDismissUtil> mKeyguardDismissUtil;
273     @Inject Lazy<SmartReplyController> mSmartReplyController;
274     @Inject Lazy<RemoteInputQuickSettingsDisabler> mRemoteInputQuickSettingsDisabler;
275     @Inject Lazy<BubbleController> mBubbleController;
276     @Inject Lazy<NotificationEntryManager> mNotificationEntryManager;
277     @Inject
278     Lazy<NotificationAlertingManager> mNotificationAlertingManager;
279     @Inject Lazy<SensorPrivacyManager> mSensorPrivacyManager;
280     @Inject Lazy<AutoHideController> mAutoHideController;
281     @Inject Lazy<ForegroundServiceNotificationListener> mForegroundServiceNotificationListener;
282     @Inject @Named(BG_LOOPER_NAME) Lazy<Looper> mBgLooper;
283     @Inject @Named(BG_HANDLER_NAME) Lazy<Handler> mBgHandler;
284     @Inject @Named(MAIN_HANDLER_NAME) Lazy<Handler> mMainHandler;
285     @Inject @Named(TIME_TICK_HANDLER_NAME) Lazy<Handler> mTimeTickHandler;
286     @Nullable
287     @Inject @Named(LEAK_REPORT_EMAIL_NAME) Lazy<String> mLeakReportEmail;
288     @Inject Lazy<ClockManager> mClockManager;
289     @Inject Lazy<ActivityManagerWrapper> mActivityManagerWrapper;
290     @Inject Lazy<DevicePolicyManagerWrapper> mDevicePolicyManagerWrapper;
291     @Inject Lazy<PackageManagerWrapper> mPackageManagerWrapper;
292     @Inject Lazy<SensorPrivacyController> mSensorPrivacyController;
293     @Inject Lazy<DumpController> mDumpController;
294     @Inject Lazy<DockManager> mDockManager;
295     @Inject Lazy<ChannelEditorDialogController> mChannelEditorDialogController;
296     @Inject Lazy<INotificationManager> mINotificationManager;
297     @Inject Lazy<FalsingManager> mFalsingManager;
298 
299     @Inject
Dependency()300     public Dependency() {
301     }
302 
303 
304     /**
305      * Initialize Depenency.
306      */
initDependencies(SystemUIRootComponent rootComponent)307     public static void initDependencies(SystemUIRootComponent rootComponent) {
308         if (sDependency != null) {
309             return;
310         }
311         sDependency = new Dependency();
312         rootComponent.createDependency().createSystemUI(sDependency);
313         sDependency.start();
314     }
315 
start()316     protected void start() {
317         // TODO: Think about ways to push these creation rules out of Dependency to cut down
318         // on imports.
319         mProviders.put(TIME_TICK_HANDLER, mTimeTickHandler::get);
320         mProviders.put(BG_LOOPER, mBgLooper::get);
321         mProviders.put(BG_HANDLER, mBgHandler::get);
322         mProviders.put(MAIN_HANDLER, mMainHandler::get);
323         mProviders.put(ActivityStarter.class, mActivityStarter::get);
324         mProviders.put(ActivityStarterDelegate.class, mActivityStarterDelegate::get);
325 
326         mProviders.put(AsyncSensorManager.class, mAsyncSensorManager::get);
327 
328         mProviders.put(BluetoothController.class, mBluetoothController::get);
329         mProviders.put(SensorPrivacyManager.class, mSensorPrivacyManager::get);
330 
331         mProviders.put(LocationController.class, mLocationController::get);
332 
333         mProviders.put(RotationLockController.class, mRotationLockController::get);
334 
335         mProviders.put(NetworkController.class, mNetworkController::get);
336 
337         mProviders.put(ZenModeController.class, mZenModeController::get);
338 
339         mProviders.put(HotspotController.class, mHotspotController::get);
340 
341         mProviders.put(CastController.class, mCastController::get);
342 
343         mProviders.put(FlashlightController.class, mFlashlightController::get);
344 
345         mProviders.put(KeyguardMonitor.class, mKeyguardMonitor::get);
346 
347         mProviders.put(UserSwitcherController.class, mUserSwitcherController::get);
348 
349         mProviders.put(UserInfoController.class, mUserInfoController::get);
350 
351         mProviders.put(BatteryController.class, mBatteryController::get);
352 
353         mProviders.put(NightDisplayListener.class, mNightDisplayListener::get);
354 
355         mProviders.put(ManagedProfileController.class, mManagedProfileController::get);
356 
357         mProviders.put(NextAlarmController.class, mNextAlarmController::get);
358 
359         mProviders.put(DataSaverController.class, mDataSaverController::get);
360 
361         mProviders.put(AccessibilityController.class, mAccessibilityController::get);
362 
363         mProviders.put(DeviceProvisionedController.class, mDeviceProvisionedController::get);
364 
365         mProviders.put(PluginManager.class, mPluginManager::get);
366 
367         mProviders.put(AssistManager.class, mAssistManager::get);
368 
369         mProviders.put(SecurityController.class, mSecurityController::get);
370 
371         mProviders.put(LeakDetector.class, mLeakDetector::get);
372 
373         mProviders.put(LEAK_REPORT_EMAIL, mLeakReportEmail::get);
374 
375         mProviders.put(LeakReporter.class, mLeakReporter::get);
376 
377         mProviders.put(GarbageMonitor.class, mGarbageMonitor::get);
378 
379         mProviders.put(TunerService.class, mTunerService::get);
380 
381         mProviders.put(StatusBarWindowController.class, mStatusBarWindowController::get);
382 
383         mProviders.put(DarkIconDispatcher.class, mDarkIconDispatcher::get);
384 
385         mProviders.put(ConfigurationController.class, mConfigurationController::get);
386 
387         mProviders.put(StatusBarIconController.class, mStatusBarIconController::get);
388 
389         mProviders.put(ScreenLifecycle.class, mScreenLifecycle::get);
390 
391         mProviders.put(WakefulnessLifecycle.class, mWakefulnessLifecycle::get);
392 
393         mProviders.put(FragmentService.class, mFragmentService::get);
394 
395         mProviders.put(ExtensionController.class, mExtensionController::get);
396 
397         mProviders.put(PluginDependencyProvider.class, mPluginDependencyProvider::get);
398 
399         mProviders.put(LocalBluetoothManager.class, mLocalBluetoothManager::get);
400 
401         mProviders.put(VolumeDialogController.class, mVolumeDialogController::get);
402 
403         mProviders.put(MetricsLogger.class, mMetricsLogger::get);
404 
405         mProviders.put(AccessibilityManagerWrapper.class, mAccessibilityManagerWrapper::get);
406 
407         mProviders.put(SysuiColorExtractor.class, mSysuiColorExtractor::get);
408 
409         mProviders.put(TunablePaddingService.class, mTunablePaddingService::get);
410 
411         mProviders.put(ForegroundServiceController.class, mForegroundServiceController::get);
412 
413         mProviders.put(UiOffloadThread.class, mUiOffloadThread::get);
414 
415         mProviders.put(PowerUI.WarningsUI.class, mWarningsUI::get);
416 
417         mProviders.put(LightBarController.class, mLightBarController::get);
418 
419         mProviders.put(IWindowManager.class, mIWindowManager::get);
420 
421         mProviders.put(OverviewProxyService.class, mOverviewProxyService::get);
422 
423         mProviders.put(NavigationModeController.class, mNavBarModeController::get);
424 
425         mProviders.put(EnhancedEstimates.class, mEnhancedEstimates::get);
426 
427         mProviders.put(VibratorHelper.class, mVibratorHelper::get);
428 
429         mProviders.put(IStatusBarService.class, mIStatusBarService::get);
430 
431         mProviders.put(DisplayMetrics.class, mDisplayMetrics::get);
432 
433         mProviders.put(LockscreenGestureLogger.class, mLockscreenGestureLogger::get);
434 
435         mProviders.put(KeyguardEnvironment.class, mKeyguardEnvironment::get);
436         mProviders.put(ShadeController.class, mShadeController::get);
437         mProviders.put(NotificationRemoteInputManager.Callback.class,
438                 mNotificationRemoteInputManagerCallback::get);
439 
440         mProviders.put(InitController.class, mInitController::get);
441 
442         mProviders.put(AppOpsController.class, mAppOpsController::get);
443 
444         mProviders.put(NavigationBarController.class, mNavigationBarController::get);
445 
446         mProviders.put(StatusBarStateController.class, mStatusBarStateController::get);
447         mProviders.put(NotificationLockscreenUserManager.class,
448                 mNotificationLockscreenUserManager::get);
449         mProviders.put(VisualStabilityManager.class, mVisualStabilityManager::get);
450         mProviders.put(NotificationGroupManager.class, mNotificationGroupManager::get);
451         mProviders.put(NotificationGroupAlertTransferHelper.class,
452                 mNotificationGroupAlertTransferHelper::get);
453         mProviders.put(NotificationMediaManager.class, mNotificationMediaManager::get);
454         mProviders.put(NotificationGutsManager.class, mNotificationGutsManager::get);
455         mProviders.put(NotificationBlockingHelperManager.class,
456                 mNotificationBlockingHelperManager::get);
457         mProviders.put(NotificationRemoteInputManager.class,
458                 mNotificationRemoteInputManager::get);
459         mProviders.put(SmartReplyConstants.class, mSmartReplyConstants::get);
460         mProviders.put(NotificationListener.class, mNotificationListener::get);
461         mProviders.put(NotificationLogger.class, mNotificationLogger::get);
462         mProviders.put(NotificationViewHierarchyManager.class,
463                 mNotificationViewHierarchyManager::get);
464         mProviders.put(NotificationFilter.class, mNotificationFilter::get);
465         mProviders.put(NotificationInterruptionStateProvider.class,
466                 mNotificationInterruptionStateProvider::get);
467         mProviders.put(KeyguardDismissUtil.class, mKeyguardDismissUtil::get);
468         mProviders.put(SmartReplyController.class, mSmartReplyController::get);
469         mProviders.put(RemoteInputQuickSettingsDisabler.class,
470                 mRemoteInputQuickSettingsDisabler::get);
471         mProviders.put(BubbleController.class, mBubbleController::get);
472         mProviders.put(NotificationEntryManager.class, mNotificationEntryManager::get);
473         mProviders.put(NotificationAlertingManager.class, mNotificationAlertingManager::get);
474         mProviders.put(ForegroundServiceNotificationListener.class,
475                 mForegroundServiceNotificationListener::get);
476         mProviders.put(ClockManager.class, mClockManager::get);
477         mProviders.put(ActivityManagerWrapper.class, mActivityManagerWrapper::get);
478         mProviders.put(DevicePolicyManagerWrapper.class, mDevicePolicyManagerWrapper::get);
479         mProviders.put(PackageManagerWrapper.class, mPackageManagerWrapper::get);
480         mProviders.put(SensorPrivacyController.class, mSensorPrivacyController::get);
481         mProviders.put(DumpController.class, mDumpController::get);
482         mProviders.put(DockManager.class, mDockManager::get);
483         mProviders.put(ChannelEditorDialogController.class, mChannelEditorDialogController::get);
484         mProviders.put(INotificationManager.class, mINotificationManager::get);
485         mProviders.put(FalsingManager.class, mFalsingManager::get);
486 
487         // TODO(b/118592525): to support multi-display , we start to add something which is
488         //                    per-display, while others may be global. I think it's time to add
489         //                    a new class maybe named DisplayDependency to solve per-display
490         //                    Dependency problem.
491         mProviders.put(AutoHideController.class, mAutoHideController::get);
492 
493         sDependency = this;
494     }
495 
staticDump(FileDescriptor fd, PrintWriter pw, String[] args)496     static void staticDump(FileDescriptor fd, PrintWriter pw, String[] args) {
497         sDependency.dump(fd, pw, args);
498     }
499 
500     /**
501      * {@see SystemUI.dump}
502      */
dump(FileDescriptor fd, PrintWriter pw, String[] args)503     public synchronized void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
504         // Make sure that the DumpController gets added to mDependencies, as they are only added
505         // with Dependency#get.
506         getDependency(DumpController.class);
507 
508         // If an arg is specified, try to dump the dependency
509         String controller = args != null && args.length > 1
510                 ? args[1].toLowerCase()
511                 : null;
512         if (controller != null) {
513             pw.println("Dumping controller=" + controller + ":");
514         } else {
515             pw.println("Dumping existing controllers:");
516         }
517         mDependencies.values().stream()
518                 .filter(obj -> obj instanceof Dumpable && (controller == null
519                         || obj.getClass().getName().toLowerCase().endsWith(controller)))
520                 .forEach(o -> ((Dumpable) o).dump(fd, pw, args));
521     }
522 
getDependency(Class<T> cls)523     protected final <T> T getDependency(Class<T> cls) {
524         return getDependencyInner(cls);
525     }
526 
getDependency(DependencyKey<T> key)527     protected final <T> T getDependency(DependencyKey<T> key) {
528         return getDependencyInner(key);
529     }
530 
getDependencyInner(Object key)531     private synchronized <T> T getDependencyInner(Object key) {
532         @SuppressWarnings("unchecked")
533         T obj = (T) mDependencies.get(key);
534         if (obj == null) {
535             obj = createDependency(key);
536             mDependencies.put(key, obj);
537         }
538         return obj;
539     }
540 
541     @VisibleForTesting
createDependency(Object cls)542     protected <T> T createDependency(Object cls) {
543         Preconditions.checkArgument(cls instanceof DependencyKey<?> || cls instanceof Class<?>);
544 
545         @SuppressWarnings("unchecked")
546         LazyDependencyCreator<T> provider = mProviders.get(cls);
547         if (provider == null) {
548             throw new IllegalArgumentException("Unsupported dependency " + cls
549                     + ". " + mProviders.size() + " providers known.");
550         }
551         return provider.createDependency();
552     }
553 
554     private static Dependency sDependency;
555 
556     /**
557      * Interface for a class that can create a dependency. Used to implement laziness
558      * @param <T> The type of the dependency being created
559      */
560     private interface LazyDependencyCreator<T> {
createDependency()561         T createDependency();
562     }
563 
destroyDependency(Class<T> cls, Consumer<T> destroy)564     private <T> void destroyDependency(Class<T> cls, Consumer<T> destroy) {
565         T dep = (T) mDependencies.remove(cls);
566         if (dep != null && destroy != null) {
567             destroy.accept(dep);
568         }
569     }
570 
571     /**
572      * Used in separate process teardown to ensure the context isn't leaked.
573      *
574      * TODO: Remove once PreferenceFragment doesn't reference getActivity()
575      * anymore and these context hacks are no longer needed.
576      */
clearDependencies()577     public static void clearDependencies() {
578         sDependency = null;
579     }
580 
581     /**
582      * Checks to see if a dependency is instantiated, if it is it removes it from
583      * the cache and calls the destroy callback.
584      */
destroy(Class<T> cls, Consumer<T> destroy)585     public static <T> void destroy(Class<T> cls, Consumer<T> destroy) {
586         sDependency.destroyDependency(cls, destroy);
587     }
588 
589     /**
590      * @deprecated see docs/dagger.md
591      */
592     @Deprecated
get(Class<T> cls)593     public static <T> T get(Class<T> cls) {
594         return sDependency.getDependency(cls);
595     }
596 
597     /**
598      * @deprecated see docs/dagger.md
599      */
600     @Deprecated
get(DependencyKey<T> cls)601     public static <T> T get(DependencyKey<T> cls) {
602         return sDependency.getDependency(cls);
603     }
604 
605     public static final class DependencyKey<V> {
606         private final String mDisplayName;
607 
DependencyKey(String displayName)608         public DependencyKey(String displayName) {
609             mDisplayName = displayName;
610         }
611 
612         @Override
toString()613         public String toString() {
614             return mDisplayName;
615         }
616     }
617 
618     @Subcomponent
619     public interface DependencyInjector {
createSystemUI(Dependency dependency)620         void createSystemUI(Dependency dependency);
621     }
622 }
623