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