DreamManagerService.java revision 0f208eb707926f0afc1ce073be866bedd4955aa2
1/*
2 * Copyright (C) 2012 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server.dreams;
18
19import static android.Manifest.permission.BIND_DREAM_SERVICE;
20
21import com.android.internal.util.DumpUtils;
22import com.android.server.FgThread;
23import com.android.server.SystemService;
24
25import android.Manifest;
26import android.app.ActivityManager;
27import android.content.BroadcastReceiver;
28import android.content.ComponentName;
29import android.content.Context;
30import android.content.Intent;
31import android.content.IntentFilter;
32import android.content.pm.PackageManager;
33import android.content.pm.PackageManager.NameNotFoundException;
34import android.content.pm.ServiceInfo;
35import android.os.Binder;
36import android.os.Build;
37import android.os.Handler;
38import android.os.IBinder;
39import android.os.Looper;
40import android.os.PowerManager;
41import android.os.PowerManagerInternal;
42import android.os.SystemClock;
43import android.os.SystemProperties;
44import android.os.UserHandle;
45import android.provider.Settings;
46import android.service.dreams.DreamManagerInternal;
47import android.service.dreams.DreamService;
48import android.service.dreams.IDreamManager;
49import android.text.TextUtils;
50import android.util.Slog;
51import android.view.Display;
52
53import java.io.FileDescriptor;
54import java.io.PrintWriter;
55import java.util.ArrayList;
56import java.util.List;
57
58import libcore.util.Objects;
59
60/**
61 * Service api for managing dreams.
62 *
63 * @hide
64 */
65public final class DreamManagerService extends SystemService {
66    private static final boolean DEBUG = false;
67    private static final String TAG = "DreamManagerService";
68
69    private final Object mLock = new Object();
70
71    private final Context mContext;
72    private final DreamHandler mHandler;
73    private final DreamController mController;
74    private final PowerManager mPowerManager;
75    private final PowerManagerInternal mPowerManagerInternal;
76    private final PowerManager.WakeLock mDozeWakeLock;
77
78    private Binder mCurrentDreamToken;
79    private ComponentName mCurrentDreamName;
80    private int mCurrentDreamUserId;
81    private boolean mCurrentDreamIsTest;
82    private boolean mCurrentDreamCanDoze;
83    private boolean mCurrentDreamIsDozing;
84    private boolean mCurrentDreamIsWaking;
85    private int mCurrentDreamDozeScreenState = Display.STATE_UNKNOWN;
86    private int mCurrentDreamDozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
87
88    public DreamManagerService(Context context) {
89        super(context);
90        mContext = context;
91        mHandler = new DreamHandler(FgThread.get().getLooper());
92        mController = new DreamController(context, mHandler, mControllerListener);
93
94        mPowerManager = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
95        mPowerManagerInternal = getLocalService(PowerManagerInternal.class);
96        mDozeWakeLock = mPowerManager.newWakeLock(PowerManager.DOZE_WAKE_LOCK, TAG);
97    }
98
99    @Override
100    public void onStart() {
101        publishBinderService(DreamService.DREAM_SERVICE, new BinderService());
102        publishLocalService(DreamManagerInternal.class, new LocalService());
103    }
104
105    @Override
106    public void onBootPhase(int phase) {
107        if (phase == SystemService.PHASE_THIRD_PARTY_APPS_CAN_START) {
108            if (Build.IS_DEBUGGABLE) {
109                SystemProperties.addChangeCallback(mSystemPropertiesChanged);
110            }
111            mContext.registerReceiver(new BroadcastReceiver() {
112                @Override
113                public void onReceive(Context context, Intent intent) {
114                    synchronized (mLock) {
115                        stopDreamLocked(false /*immediate*/);
116                    }
117                }
118            }, new IntentFilter(Intent.ACTION_USER_SWITCHED), null, mHandler);
119        }
120    }
121
122    private void dumpInternal(PrintWriter pw) {
123        pw.println("DREAM MANAGER (dumpsys dreams)");
124        pw.println();
125        pw.println("mCurrentDreamToken=" + mCurrentDreamToken);
126        pw.println("mCurrentDreamName=" + mCurrentDreamName);
127        pw.println("mCurrentDreamUserId=" + mCurrentDreamUserId);
128        pw.println("mCurrentDreamIsTest=" + mCurrentDreamIsTest);
129        pw.println("mCurrentDreamCanDoze=" + mCurrentDreamCanDoze);
130        pw.println("mCurrentDreamIsDozing=" + mCurrentDreamIsDozing);
131        pw.println("mCurrentDreamIsWaking=" + mCurrentDreamIsWaking);
132        pw.println("mCurrentDreamDozeScreenState="
133                + Display.stateToString(mCurrentDreamDozeScreenState));
134        pw.println("mCurrentDreamDozeScreenBrightness=" + mCurrentDreamDozeScreenBrightness);
135        pw.println("getDozeComponent()=" + getDozeComponent());
136        pw.println();
137
138        DumpUtils.dumpAsync(mHandler, new DumpUtils.Dump() {
139            @Override
140            public void dump(PrintWriter pw) {
141                mController.dump(pw);
142            }
143        }, pw, 200);
144    }
145
146    private boolean isDreamingInternal() {
147        synchronized (mLock) {
148            return mCurrentDreamToken != null && !mCurrentDreamIsTest
149                    && !mCurrentDreamIsWaking;
150        }
151    }
152
153    private void requestDreamInternal() {
154        // Ask the power manager to nap.  It will eventually call back into
155        // startDream() if/when it is appropriate to start dreaming.
156        // Because napping could cause the screen to turn off immediately if the dream
157        // cannot be started, we keep one eye open and gently poke user activity.
158        long time = SystemClock.uptimeMillis();
159        mPowerManager.userActivity(time, true /*noChangeLights*/);
160        mPowerManager.nap(time);
161    }
162
163    private void requestAwakenInternal() {
164        // Treat an explicit request to awaken as user activity so that the
165        // device doesn't immediately go to sleep if the timeout expired,
166        // for example when being undocked.
167        long time = SystemClock.uptimeMillis();
168        mPowerManager.userActivity(time, false /*noChangeLights*/);
169        stopDreamInternal(false /*immediate*/);
170    }
171
172    private void finishSelfInternal(IBinder token, boolean immediate) {
173        if (DEBUG) {
174            Slog.d(TAG, "Dream finished: " + token + ", immediate=" + immediate);
175        }
176
177        // Note that a dream finishing and self-terminating is not
178        // itself considered user activity.  If the dream is ending because
179        // the user interacted with the device then user activity will already
180        // have been poked so the device will stay awake a bit longer.
181        // If the dream is ending on its own for other reasons and no wake
182        // locks are held and the user activity timeout has expired then the
183        // device may simply go to sleep.
184        synchronized (mLock) {
185            if (mCurrentDreamToken == token) {
186                stopDreamLocked(immediate);
187            }
188        }
189    }
190
191    private void testDreamInternal(ComponentName dream, int userId) {
192        synchronized (mLock) {
193            startDreamLocked(dream, true /*isTest*/, false /*canDoze*/, userId);
194        }
195    }
196
197    private void startDreamInternal(boolean doze) {
198        final int userId = ActivityManager.getCurrentUser();
199        final ComponentName dream = chooseDreamForUser(doze, userId);
200        if (dream != null) {
201            synchronized (mLock) {
202                startDreamLocked(dream, false /*isTest*/, doze, userId);
203            }
204        }
205    }
206
207    private void stopDreamInternal(boolean immediate) {
208        synchronized (mLock) {
209            stopDreamLocked(immediate);
210        }
211    }
212
213    private void startDozingInternal(IBinder token, int screenState,
214            int screenBrightness) {
215        if (DEBUG) {
216            Slog.d(TAG, "Dream requested to start dozing: " + token
217                    + ", screenState=" + screenState
218                    + ", screenBrightness=" + screenBrightness);
219        }
220
221        synchronized (mLock) {
222            if (mCurrentDreamToken == token && mCurrentDreamCanDoze) {
223                mCurrentDreamDozeScreenState = screenState;
224                mCurrentDreamDozeScreenBrightness = screenBrightness;
225                mPowerManagerInternal.setDozeOverrideFromDreamManager(
226                        screenState, screenBrightness);
227                if (!mCurrentDreamIsDozing) {
228                    mCurrentDreamIsDozing = true;
229                    mDozeWakeLock.acquire();
230                }
231            }
232        }
233    }
234
235    private void stopDozingInternal(IBinder token) {
236        if (DEBUG) {
237            Slog.d(TAG, "Dream requested to stop dozing: " + token);
238        }
239
240        synchronized (mLock) {
241            if (mCurrentDreamToken == token && mCurrentDreamIsDozing) {
242                mCurrentDreamIsDozing = false;
243                mDozeWakeLock.release();
244                mPowerManagerInternal.setDozeOverrideFromDreamManager(
245                        Display.STATE_UNKNOWN, PowerManager.BRIGHTNESS_DEFAULT);
246            }
247        }
248    }
249
250    private ComponentName chooseDreamForUser(boolean doze, int userId) {
251        if (doze) {
252            ComponentName dozeComponent = getDozeComponent();
253            return validateDream(dozeComponent) ? dozeComponent : null;
254        }
255        ComponentName[] dreams = getDreamComponentsForUser(userId);
256        return dreams != null && dreams.length != 0 ? dreams[0] : null;
257    }
258
259    private boolean validateDream(ComponentName component) {
260        if (component == null) return false;
261        final ServiceInfo serviceInfo = getServiceInfo(component);
262        if (serviceInfo == null) {
263            Slog.w(TAG, "Dream " + component + " does not exist");
264            return false;
265        } else if (serviceInfo.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.L
266                && !BIND_DREAM_SERVICE.equals(serviceInfo.permission)) {
267            Slog.w(TAG, "Dream " + component
268                    + " is not available because its manifest is missing the " + BIND_DREAM_SERVICE
269                    + " permission on the dream service declaration.");
270            return false;
271        }
272        return true;
273    }
274
275    private ComponentName[] getDreamComponentsForUser(int userId) {
276        String names = Settings.Secure.getStringForUser(mContext.getContentResolver(),
277                Settings.Secure.SCREENSAVER_COMPONENTS,
278                userId);
279        ComponentName[] components = componentsFromString(names);
280
281        // first, ensure components point to valid services
282        List<ComponentName> validComponents = new ArrayList<ComponentName>();
283        if (components != null) {
284            for (ComponentName component : components) {
285                if (validateDream(component)) {
286                    validComponents.add(component);
287                }
288            }
289        }
290
291        // fallback to the default dream component if necessary
292        if (validComponents.isEmpty()) {
293            ComponentName defaultDream = getDefaultDreamComponentForUser(userId);
294            if (defaultDream != null) {
295                Slog.w(TAG, "Falling back to default dream " + defaultDream);
296                validComponents.add(defaultDream);
297            }
298        }
299        return validComponents.toArray(new ComponentName[validComponents.size()]);
300    }
301
302    private void setDreamComponentsForUser(int userId, ComponentName[] componentNames) {
303        Settings.Secure.putStringForUser(mContext.getContentResolver(),
304                Settings.Secure.SCREENSAVER_COMPONENTS,
305                componentsToString(componentNames),
306                userId);
307    }
308
309    private ComponentName getDefaultDreamComponentForUser(int userId) {
310        String name = Settings.Secure.getStringForUser(mContext.getContentResolver(),
311                Settings.Secure.SCREENSAVER_DEFAULT_COMPONENT,
312                userId);
313        return name == null ? null : ComponentName.unflattenFromString(name);
314    }
315
316    private ComponentName getDozeComponent() {
317        // Read the component from a system property to facilitate debugging.
318        // Note that for production devices, the dream should actually be declared in
319        // a config.xml resource.
320        String name = Build.IS_DEBUGGABLE ? SystemProperties.get("debug.doze.component") : null;
321        if (TextUtils.isEmpty(name)) {
322            // Read the component from a config.xml resource.
323            // The value should be specified in a resource overlay for the product.
324            name = mContext.getResources().getString(
325                    com.android.internal.R.string.config_dozeComponent);
326        }
327        return TextUtils.isEmpty(name) ? null : ComponentName.unflattenFromString(name);
328    }
329
330    private ServiceInfo getServiceInfo(ComponentName name) {
331        try {
332            return name != null ? mContext.getPackageManager().getServiceInfo(name, 0) : null;
333        } catch (NameNotFoundException e) {
334            return null;
335        }
336    }
337
338    private void startDreamLocked(final ComponentName name,
339            final boolean isTest, final boolean canDoze, final int userId) {
340        if (Objects.equal(mCurrentDreamName, name)
341                && mCurrentDreamIsTest == isTest
342                && mCurrentDreamCanDoze == canDoze
343                && mCurrentDreamUserId == userId) {
344            return;
345        }
346
347        stopDreamLocked(true /*immediate*/);
348
349        Slog.i(TAG, "Entering dreamland.");
350
351        final Binder newToken = new Binder();
352        mCurrentDreamToken = newToken;
353        mCurrentDreamName = name;
354        mCurrentDreamIsTest = isTest;
355        mCurrentDreamCanDoze = canDoze;
356        mCurrentDreamUserId = userId;
357
358        mHandler.post(new Runnable() {
359            @Override
360            public void run() {
361                mController.startDream(newToken, name, isTest, canDoze, userId);
362            }
363        });
364    }
365
366    private void stopDreamLocked(final boolean immediate) {
367        if (mCurrentDreamToken != null) {
368            if (immediate) {
369                Slog.i(TAG, "Leaving dreamland.");
370                cleanupDreamLocked();
371            } else if (mCurrentDreamIsWaking) {
372                return; // already waking
373            } else {
374                Slog.i(TAG, "Gently waking up from dream.");
375                mCurrentDreamIsWaking = true;
376            }
377
378            mHandler.post(new Runnable() {
379                @Override
380                public void run() {
381                    mController.stopDream(immediate);
382                }
383            });
384        }
385    }
386
387    private void cleanupDreamLocked() {
388        mCurrentDreamToken = null;
389        mCurrentDreamName = null;
390        mCurrentDreamIsTest = false;
391        mCurrentDreamCanDoze = false;
392        mCurrentDreamUserId = 0;
393        mCurrentDreamIsWaking = false;
394        if (mCurrentDreamIsDozing) {
395            mCurrentDreamIsDozing = false;
396            mDozeWakeLock.release();
397        }
398        mCurrentDreamDozeScreenState = Display.STATE_UNKNOWN;
399        mCurrentDreamDozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
400    }
401
402    private void checkPermission(String permission) {
403        if (mContext.checkCallingOrSelfPermission(permission)
404                != PackageManager.PERMISSION_GRANTED) {
405            throw new SecurityException("Access denied to process: " + Binder.getCallingPid()
406                    + ", must have permission " + permission);
407        }
408    }
409
410    private static String componentsToString(ComponentName[] componentNames) {
411        StringBuilder names = new StringBuilder();
412        if (componentNames != null) {
413            for (ComponentName componentName : componentNames) {
414                if (names.length() > 0) {
415                    names.append(',');
416                }
417                names.append(componentName.flattenToString());
418            }
419        }
420        return names.toString();
421    }
422
423    private static ComponentName[] componentsFromString(String names) {
424        if (names == null) {
425            return null;
426        }
427        String[] namesArray = names.split(",");
428        ComponentName[] componentNames = new ComponentName[namesArray.length];
429        for (int i = 0; i < namesArray.length; i++) {
430            componentNames[i] = ComponentName.unflattenFromString(namesArray[i]);
431        }
432        return componentNames;
433    }
434
435    private final DreamController.Listener mControllerListener = new DreamController.Listener() {
436        @Override
437        public void onDreamStopped(Binder token) {
438            synchronized (mLock) {
439                if (mCurrentDreamToken == token) {
440                    cleanupDreamLocked();
441                }
442            }
443        }
444    };
445
446    /**
447     * Handler for asynchronous operations performed by the dream manager.
448     * Ensures operations to {@link DreamController} are single-threaded.
449     */
450    private final class DreamHandler extends Handler {
451        public DreamHandler(Looper looper) {
452            super(looper, null, true /*async*/);
453        }
454    }
455
456    private final class BinderService extends IDreamManager.Stub {
457        @Override // Binder call
458        protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) {
459            if (mContext.checkCallingOrSelfPermission(Manifest.permission.DUMP)
460                    != PackageManager.PERMISSION_GRANTED) {
461                pw.println("Permission Denial: can't dump DreamManager from from pid="
462                        + Binder.getCallingPid()
463                        + ", uid=" + Binder.getCallingUid());
464                return;
465            }
466
467            final long ident = Binder.clearCallingIdentity();
468            try {
469                dumpInternal(pw);
470            } finally {
471                Binder.restoreCallingIdentity(ident);
472            }
473        }
474
475        @Override // Binder call
476        public ComponentName[] getDreamComponents() {
477            checkPermission(android.Manifest.permission.READ_DREAM_STATE);
478
479            final int userId = UserHandle.getCallingUserId();
480            final long ident = Binder.clearCallingIdentity();
481            try {
482                return getDreamComponentsForUser(userId);
483            } finally {
484                Binder.restoreCallingIdentity(ident);
485            }
486        }
487
488        @Override // Binder call
489        public void setDreamComponents(ComponentName[] componentNames) {
490            checkPermission(android.Manifest.permission.WRITE_DREAM_STATE);
491
492            final int userId = UserHandle.getCallingUserId();
493            final long ident = Binder.clearCallingIdentity();
494            try {
495                setDreamComponentsForUser(userId, componentNames);
496            } finally {
497                Binder.restoreCallingIdentity(ident);
498            }
499        }
500
501        @Override // Binder call
502        public ComponentName getDefaultDreamComponent() {
503            checkPermission(android.Manifest.permission.READ_DREAM_STATE);
504
505            final int userId = UserHandle.getCallingUserId();
506            final long ident = Binder.clearCallingIdentity();
507            try {
508                return getDefaultDreamComponentForUser(userId);
509            } finally {
510                Binder.restoreCallingIdentity(ident);
511            }
512        }
513
514        @Override // Binder call
515        public boolean isDreaming() {
516            checkPermission(android.Manifest.permission.READ_DREAM_STATE);
517
518            final long ident = Binder.clearCallingIdentity();
519            try {
520                return isDreamingInternal();
521            } finally {
522                Binder.restoreCallingIdentity(ident);
523            }
524        }
525
526        @Override // Binder call
527        public void dream() {
528            checkPermission(android.Manifest.permission.WRITE_DREAM_STATE);
529
530            final long ident = Binder.clearCallingIdentity();
531            try {
532                requestDreamInternal();
533            } finally {
534                Binder.restoreCallingIdentity(ident);
535            }
536        }
537
538        @Override // Binder call
539        public void testDream(ComponentName dream) {
540            if (dream == null) {
541                throw new IllegalArgumentException("dream must not be null");
542            }
543            checkPermission(android.Manifest.permission.WRITE_DREAM_STATE);
544
545            final int callingUserId = UserHandle.getCallingUserId();
546            final int currentUserId = ActivityManager.getCurrentUser();
547            if (callingUserId != currentUserId) {
548                // This check is inherently prone to races but at least it's something.
549                Slog.w(TAG, "Aborted attempt to start a test dream while a different "
550                        + " user is active: callingUserId=" + callingUserId
551                        + ", currentUserId=" + currentUserId);
552                return;
553            }
554            final long ident = Binder.clearCallingIdentity();
555            try {
556                testDreamInternal(dream, callingUserId);
557            } finally {
558                Binder.restoreCallingIdentity(ident);
559            }
560        }
561
562        @Override // Binder call
563        public void awaken() {
564            checkPermission(android.Manifest.permission.WRITE_DREAM_STATE);
565
566            final long ident = Binder.clearCallingIdentity();
567            try {
568                requestAwakenInternal();
569            } finally {
570                Binder.restoreCallingIdentity(ident);
571            }
572        }
573
574        @Override // Binder call
575        public void finishSelf(IBinder token, boolean immediate) {
576            // Requires no permission, called by Dream from an arbitrary process.
577            if (token == null) {
578                throw new IllegalArgumentException("token must not be null");
579            }
580
581            final long ident = Binder.clearCallingIdentity();
582            try {
583                finishSelfInternal(token, immediate);
584            } finally {
585                Binder.restoreCallingIdentity(ident);
586            }
587        }
588
589        @Override // Binder call
590        public void startDozing(IBinder token, int screenState, int screenBrightness) {
591            // Requires no permission, called by Dream from an arbitrary process.
592            if (token == null) {
593                throw new IllegalArgumentException("token must not be null");
594            }
595
596            final long ident = Binder.clearCallingIdentity();
597            try {
598                startDozingInternal(token, screenState, screenBrightness);
599            } finally {
600                Binder.restoreCallingIdentity(ident);
601            }
602        }
603
604        @Override // Binder call
605        public void stopDozing(IBinder token) {
606            // Requires no permission, called by Dream from an arbitrary process.
607            if (token == null) {
608                throw new IllegalArgumentException("token must not be null");
609            }
610
611            final long ident = Binder.clearCallingIdentity();
612            try {
613                stopDozingInternal(token);
614            } finally {
615                Binder.restoreCallingIdentity(ident);
616            }
617        }
618    }
619
620    private final class LocalService extends DreamManagerInternal {
621        @Override
622        public void startDream(boolean doze) {
623            startDreamInternal(doze);
624        }
625
626        @Override
627        public void stopDream(boolean immediate) {
628            stopDreamInternal(immediate);
629        }
630
631        @Override
632        public boolean isDreaming() {
633            return isDreamingInternal();
634        }
635    }
636
637    private final Runnable mSystemPropertiesChanged = new Runnable() {
638        @Override
639        public void run() {
640            if (DEBUG) Slog.d(TAG, "System properties changed");
641            synchronized (mLock) {
642                if (mCurrentDreamName != null && mCurrentDreamCanDoze
643                        && !mCurrentDreamName.equals(getDozeComponent())) {
644                    // May have updated the doze component, wake up
645                    mPowerManager.wakeUp(SystemClock.uptimeMillis());
646                }
647            }
648        }
649    };
650}
651