DreamService.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 */
16package android.service.dreams;
17
18import java.io.FileDescriptor;
19import java.io.PrintWriter;
20
21import android.annotation.SdkConstant;
22import android.annotation.SdkConstant.SdkConstantType;
23import android.app.AlarmManager;
24import android.app.Service;
25import android.content.Intent;
26import android.graphics.PixelFormat;
27import android.graphics.drawable.ColorDrawable;
28import android.os.Handler;
29import android.os.IBinder;
30import android.os.PowerManager;
31import android.os.RemoteException;
32import android.os.RemoteException;
33import android.os.ServiceManager;
34import android.util.Slog;
35import android.view.ActionMode;
36import android.view.Display;
37import android.view.KeyEvent;
38import android.view.Menu;
39import android.view.MenuItem;
40import android.view.MotionEvent;
41import android.view.View;
42import android.view.ViewGroup;
43import android.view.Window;
44import android.view.WindowManager;
45import android.view.WindowManagerGlobal;
46import android.view.WindowManager.LayoutParams;
47import android.view.accessibility.AccessibilityEvent;
48import android.util.MathUtils;
49
50import com.android.internal.policy.PolicyManager;
51import com.android.internal.util.DumpUtils;
52import com.android.internal.util.DumpUtils.Dump;
53
54/**
55 * Extend this class to implement a custom dream (available to the user as a "Daydream").
56 *
57 * <p>Dreams are interactive screensavers launched when a charging device is idle, or docked in a
58 * desk dock. Dreams provide another modality for apps to express themselves, tailored for
59 * an exhibition/lean-back experience.</p>
60 *
61 * <p>The {@code DreamService} lifecycle is as follows:</p>
62 * <ol>
63 *   <li>{@link #onAttachedToWindow}
64 *     <p>Use this for initial setup, such as calling {@link #setContentView setContentView()}.</li>
65 *   <li>{@link #onDreamingStarted}
66 *     <p>Your dream has started, so you should begin animations or other behaviors here.</li>
67 *   <li>{@link #onDreamingStopped}
68 *     <p>Use this to stop the things you started in {@link #onDreamingStarted}.</li>
69 *   <li>{@link #onDetachedFromWindow}
70 *     <p>Use this to dismantle resources (for example, detach from handlers
71 *        and listeners).</li>
72 * </ol>
73 *
74 * <p>In addition, onCreate and onDestroy (from the Service interface) will also be called, but
75 * initialization and teardown should be done by overriding the hooks above.</p>
76 *
77 * <p>To be available to the system, your {@code DreamService} should be declared in the
78 * manifest as follows:</p>
79 * <pre>
80 * &lt;service
81 *     android:name=".MyDream"
82 *     android:exported="true"
83 *     android:icon="@drawable/my_icon"
84 *     android:label="@string/my_dream_label" >
85 *
86 *     &lt;intent-filter>
87 *         &lt;action android:name="android.service.dreams.DreamService" />
88 *         &lt;category android:name="android.intent.category.DEFAULT" />
89 *     &lt;/intent-filter>
90 *
91 *     &lt;!-- Point to additional information for this dream (optional) -->
92 *     &lt;meta-data
93 *         android:name="android.service.dream"
94 *         android:resource="@xml/my_dream" />
95 * &lt;/service>
96 * </pre>
97 *
98 * <p>If specified with the {@code &lt;meta-data&gt;} element,
99 * additional information for the dream is defined using the
100 * {@link android.R.styleable#Dream &lt;dream&gt;} element in a separate XML file.
101 * Currently, the only addtional
102 * information you can provide is for a settings activity that allows the user to configure
103 * the dream behavior. For example:</p>
104 * <p class="code-caption">res/xml/my_dream.xml</p>
105 * <pre>
106 * &lt;dream xmlns:android="http://schemas.android.com/apk/res/android"
107 *     android:settingsActivity="com.example.app/.MyDreamSettingsActivity" />
108 * </pre>
109 * <p>This makes a Settings button available alongside your dream's listing in the
110 * system settings, which when pressed opens the specified activity.</p>
111 *
112 *
113 * <p>To specify your dream layout, call {@link #setContentView}, typically during the
114 * {@link #onAttachedToWindow} callback. For example:</p>
115 * <pre>
116 * public class MyDream extends DreamService {
117 *
118 *     &#64;Override
119 *     public void onAttachedToWindow() {
120 *         super.onAttachedToWindow();
121 *
122 *         // Exit dream upon user touch
123 *         setInteractive(false);
124 *         // Hide system UI
125 *         setFullscreen(true);
126 *         // Set the dream layout
127 *         setContentView(R.layout.dream);
128 *     }
129 * }
130 * </pre>
131 *
132 * <p>When targeting api level 21 and above, you must declare the service in your manifest file
133 * with the {@link android.Manifest.permission#BIND_DREAM_SERVICE} permission. For example:</p>
134 * <pre>
135 * &lt;service
136 *     android:name=".MyDream"
137 *     android:exported="true"
138 *     android:icon="@drawable/my_icon"
139 *     android:label="@string/my_dream_label"
140 *     android:permission="android.permission.BIND_DREAM_SERVICE">
141 *   &lt;intent-filter>
142 *     &lt;action android:name=”android.service.dreams.DreamService” />
143 *     &lt;category android:name=”android.intent.category.DEFAULT” />
144 *   &lt;/intent-filter>
145 * &lt;/service>
146 * </pre>
147 */
148public class DreamService extends Service implements Window.Callback {
149    private final String TAG = DreamService.class.getSimpleName() + "[" + getClass().getSimpleName() + "]";
150
151    /**
152     * The name of the dream manager service.
153     * @hide
154     */
155    public static final String DREAM_SERVICE = "dreams";
156
157    /**
158     * The {@link Intent} that must be declared as handled by the service.
159     */
160    @SdkConstant(SdkConstantType.SERVICE_ACTION)
161    public static final String SERVICE_INTERFACE =
162            "android.service.dreams.DreamService";
163
164    /**
165     * Name under which a Dream publishes information about itself.
166     * This meta-data must reference an XML resource containing
167     * a <code>&lt;{@link android.R.styleable#Dream dream}&gt;</code>
168     * tag.
169     */
170    public static final String DREAM_META_DATA = "android.service.dream";
171
172    private final IDreamManager mSandman;
173    private final Handler mHandler = new Handler();
174    private IBinder mWindowToken;
175    private Window mWindow;
176    private boolean mInteractive;
177    private boolean mLowProfile = true;
178    private boolean mFullscreen;
179    private boolean mScreenBright = true;
180    private boolean mStarted;
181    private boolean mWaking;
182    private boolean mFinished;
183    private boolean mCanDoze;
184    private boolean mDozing;
185    private boolean mWindowless;
186    private int mDozeScreenState = Display.STATE_UNKNOWN;
187    private int mDozeScreenBrightness = PowerManager.BRIGHTNESS_DEFAULT;
188
189    private boolean mDebug = false;
190
191    public DreamService() {
192        mSandman = IDreamManager.Stub.asInterface(ServiceManager.getService(DREAM_SERVICE));
193    }
194
195    /**
196     * @hide
197     */
198    public void setDebug(boolean dbg) {
199        mDebug = dbg;
200    }
201
202    // begin Window.Callback methods
203    /** {@inheritDoc} */
204    @Override
205    public boolean dispatchKeyEvent(KeyEvent event) {
206        // TODO: create more flexible version of mInteractive that allows use of KEYCODE_BACK
207        if (!mInteractive) {
208            if (mDebug) Slog.v(TAG, "Waking up on keyEvent");
209            wakeUp();
210            return true;
211        } else if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
212            if (mDebug) Slog.v(TAG, "Waking up on back key");
213            wakeUp();
214            return true;
215        }
216        return mWindow.superDispatchKeyEvent(event);
217    }
218
219    /** {@inheritDoc} */
220    @Override
221    public boolean dispatchKeyShortcutEvent(KeyEvent event) {
222        if (!mInteractive) {
223            if (mDebug) Slog.v(TAG, "Waking up on keyShortcutEvent");
224            wakeUp();
225            return true;
226        }
227        return mWindow.superDispatchKeyShortcutEvent(event);
228    }
229
230    /** {@inheritDoc} */
231    @Override
232    public boolean dispatchTouchEvent(MotionEvent event) {
233        // TODO: create more flexible version of mInteractive that allows clicks
234        // but finish()es on any other kind of activity
235        if (!mInteractive) {
236            if (mDebug) Slog.v(TAG, "Waking up on touchEvent");
237            wakeUp();
238            return true;
239        }
240        return mWindow.superDispatchTouchEvent(event);
241    }
242
243    /** {@inheritDoc} */
244    @Override
245    public boolean dispatchTrackballEvent(MotionEvent event) {
246        if (!mInteractive) {
247            if (mDebug) Slog.v(TAG, "Waking up on trackballEvent");
248            wakeUp();
249            return true;
250        }
251        return mWindow.superDispatchTrackballEvent(event);
252    }
253
254    /** {@inheritDoc} */
255    @Override
256    public boolean dispatchGenericMotionEvent(MotionEvent event) {
257        if (!mInteractive) {
258            if (mDebug) Slog.v(TAG, "Waking up on genericMotionEvent");
259            wakeUp();
260            return true;
261        }
262        return mWindow.superDispatchGenericMotionEvent(event);
263    }
264
265    /** {@inheritDoc} */
266    @Override
267    public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
268        return false;
269    }
270
271    /** {@inheritDoc} */
272    @Override
273    public View onCreatePanelView(int featureId) {
274        return null;
275    }
276
277    /** {@inheritDoc} */
278    @Override
279    public boolean onCreatePanelMenu(int featureId, Menu menu) {
280        return false;
281    }
282
283    /** {@inheritDoc} */
284    @Override
285    public boolean onPreparePanel(int featureId, View view, Menu menu) {
286        return false;
287    }
288
289    /** {@inheritDoc} */
290    @Override
291    public boolean onMenuOpened(int featureId, Menu menu) {
292        return false;
293    }
294
295    /** {@inheritDoc} */
296    @Override
297    public boolean onMenuItemSelected(int featureId, MenuItem item) {
298        return false;
299    }
300
301    /** {@inheritDoc} */
302    @Override
303    public void onWindowAttributesChanged(LayoutParams attrs) {
304    }
305
306    /** {@inheritDoc} */
307    @Override
308    public void onContentChanged() {
309    }
310
311    /** {@inheritDoc} */
312    @Override
313    public void onWindowFocusChanged(boolean hasFocus) {
314    }
315
316    /** {@inheritDoc} */
317    @Override
318    public void onAttachedToWindow() {
319    }
320
321    /** {@inheritDoc} */
322    @Override
323    public void onDetachedFromWindow() {
324    }
325
326    /** {@inheritDoc} */
327    @Override
328    public void onPanelClosed(int featureId, Menu menu) {
329    }
330
331    /** {@inheritDoc} */
332    @Override
333    public boolean onSearchRequested() {
334        return false;
335    }
336
337    /** {@inheritDoc} */
338    @Override
339    public ActionMode onWindowStartingActionMode(android.view.ActionMode.Callback callback) {
340        return null;
341    }
342
343    /** {@inheritDoc} */
344    @Override
345    public void onActionModeStarted(ActionMode mode) {
346    }
347
348    /** {@inheritDoc} */
349    @Override
350    public void onActionModeFinished(ActionMode mode) {
351    }
352    // end Window.Callback methods
353
354    // begin public api
355    /**
356     * Retrieves the current {@link android.view.WindowManager} for the dream.
357     * Behaves similarly to {@link android.app.Activity#getWindowManager()}.
358     *
359     * @return The current window manager, or null if the dream is not started.
360     */
361    public WindowManager getWindowManager() {
362        return mWindow != null ? mWindow.getWindowManager() : null;
363    }
364
365    /**
366     * Retrieves the current {@link android.view.Window} for the dream.
367     * Behaves similarly to {@link android.app.Activity#getWindow()}.
368     *
369     * @return The current window, or null if the dream is not started.
370     */
371    public Window getWindow() {
372        return mWindow;
373    }
374
375   /**
376     * Inflates a layout resource and set it to be the content view for this Dream.
377     * Behaves similarly to {@link android.app.Activity#setContentView(int)}.
378     *
379     * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p>
380     *
381     * @param layoutResID Resource ID to be inflated.
382     *
383     * @see #setContentView(android.view.View)
384     * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
385     */
386    public void setContentView(int layoutResID) {
387        getWindow().setContentView(layoutResID);
388    }
389
390    /**
391     * Sets a view to be the content view for this Dream.
392     * Behaves similarly to {@link android.app.Activity#setContentView(android.view.View)} in an activity,
393     * including using {@link ViewGroup.LayoutParams#MATCH_PARENT} as the layout height and width of the view.
394     *
395     * <p>Note: This requires a window, so you should usually call it during
396     * {@link #onAttachedToWindow()} and never earlier (you <strong>cannot</strong> call it
397     * during {@link #onCreate}).</p>
398     *
399     * @see #setContentView(int)
400     * @see #setContentView(android.view.View, android.view.ViewGroup.LayoutParams)
401     */
402    public void setContentView(View view) {
403        getWindow().setContentView(view);
404    }
405
406    /**
407     * Sets a view to be the content view for this Dream.
408     * Behaves similarly to
409     * {@link android.app.Activity#setContentView(android.view.View, android.view.ViewGroup.LayoutParams)}
410     * in an activity.
411     *
412     * <p>Note: This requires a window, so you should usually call it during
413     * {@link #onAttachedToWindow()} and never earlier (you <strong>cannot</strong> call it
414     * during {@link #onCreate}).</p>
415     *
416     * @param view The desired content to display.
417     * @param params Layout parameters for the view.
418     *
419     * @see #setContentView(android.view.View)
420     * @see #setContentView(int)
421     */
422    public void setContentView(View view, ViewGroup.LayoutParams params) {
423        getWindow().setContentView(view, params);
424    }
425
426    /**
427     * Adds a view to the Dream's window, leaving other content views in place.
428     *
429     * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p>
430     *
431     * @param view The desired content to display.
432     * @param params Layout parameters for the view.
433     */
434    public void addContentView(View view, ViewGroup.LayoutParams params) {
435        getWindow().addContentView(view, params);
436    }
437
438    /**
439     * Finds a view that was identified by the id attribute from the XML that
440     * was processed in {@link #onCreate}.
441     *
442     * <p>Note: Requires a window, do not call before {@link #onAttachedToWindow()}</p>
443     *
444     * @return The view if found or null otherwise.
445     */
446    public View findViewById(int id) {
447        return getWindow().findViewById(id);
448    }
449
450    /**
451     * Marks this dream as interactive to receive input events.
452     *
453     * <p>Non-interactive dreams (default) will dismiss on the first input event.</p>
454     *
455     * <p>Interactive dreams should call {@link #finish()} to dismiss themselves.</p>
456     *
457     * @param interactive True if this dream will handle input events.
458     */
459    public void setInteractive(boolean interactive) {
460        mInteractive = interactive;
461    }
462
463    /**
464     * Returns whether or not this dream is interactive.  Defaults to false.
465     *
466     * @see #setInteractive(boolean)
467     */
468    public boolean isInteractive() {
469        return mInteractive;
470    }
471
472    /**
473     * Sets View.SYSTEM_UI_FLAG_LOW_PROFILE on the content view.
474     *
475     * @param lowProfile True to set View.SYSTEM_UI_FLAG_LOW_PROFILE
476     * @hide There is no reason to have this -- dreams can set this flag
477     * on their own content view, and from there can actually do the
478     * correct interactions with it (seeing when it is cleared etc).
479     */
480    public void setLowProfile(boolean lowProfile) {
481        if (mLowProfile != lowProfile) {
482            mLowProfile = lowProfile;
483            int flag = View.SYSTEM_UI_FLAG_LOW_PROFILE;
484            applySystemUiVisibilityFlags(mLowProfile ? flag : 0, flag);
485        }
486    }
487
488    /**
489     * Returns whether or not this dream is in low profile mode. Defaults to true.
490     *
491     * @see #setLowProfile(boolean)
492     * @hide
493     */
494    public boolean isLowProfile() {
495        return getSystemUiVisibilityFlagValue(View.SYSTEM_UI_FLAG_LOW_PROFILE, mLowProfile);
496    }
497
498    /**
499     * Controls {@link android.view.WindowManager.LayoutParams#FLAG_FULLSCREEN}
500     * on the dream's window.
501     *
502     * @param fullscreen If true, the fullscreen flag will be set; else it
503     * will be cleared.
504     */
505    public void setFullscreen(boolean fullscreen) {
506        if (mFullscreen != fullscreen) {
507            mFullscreen = fullscreen;
508            int flag = WindowManager.LayoutParams.FLAG_FULLSCREEN;
509            applyWindowFlags(mFullscreen ? flag : 0, flag);
510        }
511    }
512
513    /**
514     * Returns whether or not this dream is in fullscreen mode. Defaults to false.
515     *
516     * @see #setFullscreen(boolean)
517     */
518    public boolean isFullscreen() {
519        return mFullscreen;
520    }
521
522    /**
523     * Marks this dream as keeping the screen bright while dreaming.
524     *
525     * @param screenBright True to keep the screen bright while dreaming.
526     */
527    public void setScreenBright(boolean screenBright) {
528        if (mScreenBright != screenBright) {
529            mScreenBright = screenBright;
530            int flag = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
531            applyWindowFlags(mScreenBright ? flag : 0, flag);
532        }
533    }
534
535    /**
536     * Returns whether or not this dream keeps the screen bright while dreaming.
537     * Defaults to false, allowing the screen to dim if necessary.
538     *
539     * @see #setScreenBright(boolean)
540     */
541    public boolean isScreenBright() {
542        return getWindowFlagValue(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, mScreenBright);
543    }
544
545    /**
546     * Marks this dream as windowless.  Only available to doze dreams.
547     *
548     * @hide
549     */
550    public void setWindowless(boolean windowless) {
551        mWindowless = windowless;
552    }
553
554    /**
555     * Returns whether or not this dream is windowless.  Only available to doze dreams.
556     *
557     * @hide
558     */
559    public boolean isWindowless() {
560        return mWindowless;
561    }
562
563    /**
564     * Returns true if this dream is allowed to doze.
565     * <p>
566     * The value returned by this method is only meaningful when the dream has started.
567     * </p>
568     *
569     * @return True if this dream can doze.
570     * @see #startDozing
571     * @hide For use by system UI components only.
572     */
573    public boolean canDoze() {
574        return mCanDoze;
575    }
576
577    /**
578     * Starts dozing, entering a deep dreamy sleep.
579     * <p>
580     * Dozing enables the system to conserve power while the user is not actively interacting
581     * with the device.  While dozing, the display will remain on in a low-power state
582     * and will continue to show its previous contents but the application processor and
583     * other system components will be allowed to suspend when possible.
584     * </p><p>
585     * While the application processor is suspended, the dream may stop executing code
586     * for long periods of time.  Prior to being suspended, the dream may schedule periodic
587     * wake-ups to render new content by scheduling an alarm with the {@link AlarmManager}.
588     * The dream may also keep the CPU awake by acquiring a
589     * {@link android.os.PowerManager#PARTIAL_WAKE_LOCK partial wake lock} when necessary.
590     * Note that since the purpose of doze mode is to conserve power (especially when
591     * running on battery), the dream should not wake the CPU very often or keep it
592     * awake for very long.
593     * </p><p>
594     * It is a good idea to call this method some time after the dream's entry animation
595     * has completed and the dream is ready to doze.  It is important to completely
596     * finish all of the work needed before dozing since the application processor may
597     * be suspended at any moment once this method is called unless other wake locks
598     * are being held.
599     * </p><p>
600     * Call {@link #stopDozing} or {@link #finish} to stop dozing.
601     * </p>
602     *
603     * @see #stopDozing
604     * @hide For use by system UI components only.
605     */
606    public void startDozing() {
607        if (mCanDoze && !mDozing) {
608            mDozing = true;
609            updateDoze();
610        }
611    }
612
613    private void updateDoze() {
614        if (mDozing) {
615            try {
616                mSandman.startDozing(mWindowToken, mDozeScreenState, mDozeScreenBrightness);
617            } catch (RemoteException ex) {
618                // system server died
619            }
620        }
621    }
622
623    /**
624     * Stops dozing, returns to active dreaming.
625     * <p>
626     * This method reverses the effect of {@link #startDozing}.  From this moment onward,
627     * the application processor will be kept awake as long as the dream is running
628     * or until the dream starts dozing again.
629     * </p>
630     *
631     * @see #startDozing
632     * @hide For use by system UI components only.
633     */
634    public void stopDozing() {
635        if (mDozing) {
636            mDozing = false;
637            try {
638                mSandman.stopDozing(mWindowToken);
639            } catch (RemoteException ex) {
640                // system server died
641            }
642        }
643    }
644
645    /**
646     * Returns true if the dream will allow the system to enter a low-power state while
647     * it is running without actually turning off the screen.  Defaults to false,
648     * keeping the application processor awake while the dream is running.
649     *
650     * @return True if the dream is dozing.
651     *
652     * @see #setDozing(boolean)
653     * @hide For use by system UI components only.
654     */
655    public boolean isDozing() {
656        return mDozing;
657    }
658
659    /**
660     * Gets the screen state to use while dozing.
661     *
662     * @return The screen state to use while dozing, such as {@link Display#STATE_ON},
663     * {@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND},
664     * or {@link Display#STATE_OFF}, or {@link Display#STATE_UNKNOWN} for the default
665     * behavior.
666     *
667     * @see #setDozeScreenState
668     * @hide For use by system UI components only.
669     */
670    public int getDozeScreenState() {
671        return mDozeScreenState;
672    }
673
674    /**
675     * Sets the screen state to use while dozing.
676     * <p>
677     * The value of this property determines the power state of the primary display
678     * once {@link #startDozing} has been called.  The default value is
679     * {@link Display#STATE_UNKNOWN} which lets the system decide.
680     * The dream may set a different state before starting to doze and may
681     * perform transitions between states while dozing to conserve power and
682     * achieve various effects.
683     * </p><p>
684     * It is recommended that the state be set to {@link Display#STATE_DOZE_SUSPEND}
685     * once the dream has completely finished drawing and before it releases its wakelock
686     * to allow the display hardware to be fully suspended.  While suspended, the
687     * display will preserve its on-screen contents or hand off control to dedicated
688     * doze hardware if the devices supports it.  If the doze suspend state is
689     * used, the dream must make sure to set the mode back
690     * to {@link Display#STATE_DOZE} or {@link Display#STATE_ON} before drawing again
691     * since the display updates may be ignored and not seen by the user otherwise.
692     * </p><p>
693     * The set of available display power states and their behavior while dozing is
694     * hardware dependent and may vary across devices.  The dream may therefore
695     * need to be modified or configured to correctly support the hardware.
696     * </p>
697     *
698     * @param state The screen state to use while dozing, such as {@link Display#STATE_ON},
699     * {@link Display#STATE_DOZE}, {@link Display#STATE_DOZE_SUSPEND},
700     * or {@link Display#STATE_OFF}, or {@link Display#STATE_UNKNOWN} for the default
701     * behavior.
702     *
703     * @hide For use by system UI components only.
704     */
705    public void setDozeScreenState(int state) {
706        if (mDozeScreenState != state) {
707            mDozeScreenState = state;
708            updateDoze();
709        }
710    }
711
712    /**
713     * Gets the screen brightness to use while dozing.
714     *
715     * @return The screen brightness while dozing as a value between
716     * {@link PowerManager#BRIGHTNESS_OFF} (0) and {@link PowerManager#BRIGHTNESS_ON} (255),
717     * or {@link PowerManager#BRIGHTNESS_DEFAULT} (-1) to ask the system to apply
718     * its default policy based on the screen state.
719     *
720     * @see #setDozeScreenBrightness
721     * @hide For use by system UI components only.
722     */
723    public int getDozeScreenBrightness() {
724        return mDozeScreenBrightness;
725    }
726
727    /**
728     * Sets the screen brightness to use while dozing.
729     * <p>
730     * The value of this property determines the power state of the primary display
731     * once {@link #startDozing} has been called.  The default value is
732     * {@link PowerManager#BRIGHTNESS_DEFAULT} which lets the system decide.
733     * The dream may set a different brightness before starting to doze and may adjust
734     * the brightness while dozing to conserve power and achieve various effects.
735     * </p><p>
736     * Note that dream may specify any brightness in the full 0-255 range, including
737     * values that are less than the minimum value for manual screen brightness
738     * adjustments by the user.  In particular, the value may be set to 0 which may
739     * turn off the backlight entirely while still leaving the screen on although
740     * this behavior is device dependent and not guaranteed.
741     * </p><p>
742     * The available range of display brightness values and their behavior while dozing is
743     * hardware dependent and may vary across devices.  The dream may therefore
744     * need to be modified or configured to correctly support the hardware.
745     * </p>
746     *
747     * @param brightness The screen brightness while dozing as a value between
748     * {@link PowerManager#BRIGHTNESS_OFF} (0) and {@link PowerManager#BRIGHTNESS_ON} (255),
749     * or {@link PowerManager#BRIGHTNESS_DEFAULT} (-1) to ask the system to apply
750     * its default policy based on the screen state.
751     *
752     * @hide For use by system UI components only.
753     */
754    public void setDozeScreenBrightness(int brightness) {
755        if (brightness != PowerManager.BRIGHTNESS_DEFAULT) {
756            brightness = clampAbsoluteBrightness(brightness);
757        }
758        if (mDozeScreenBrightness != brightness) {
759            mDozeScreenBrightness = brightness;
760            updateDoze();
761        }
762    }
763
764    /**
765     * Called when this Dream is constructed.
766     */
767    @Override
768    public void onCreate() {
769        if (mDebug) Slog.v(TAG, "onCreate()");
770        super.onCreate();
771    }
772
773    /**
774     * Called when the dream's window has been created and is visible and animation may now begin.
775     */
776    public void onDreamingStarted() {
777        if (mDebug) Slog.v(TAG, "onDreamingStarted()");
778        // hook for subclasses
779    }
780
781    /**
782     * Called when this Dream is stopped, either by external request or by calling finish(),
783     * before the window has been removed.
784     */
785    public void onDreamingStopped() {
786        if (mDebug) Slog.v(TAG, "onDreamingStopped()");
787        // hook for subclasses
788    }
789
790    /**
791     * Called when the dream is being asked to stop itself and wake.
792     * <p>
793     * The default implementation simply calls {@link #finish} which ends the dream
794     * immediately.  Subclasses may override this function to perform a smooth exit
795     * transition then call {@link #finish} afterwards.
796     * </p><p>
797     * Note that the dream will only be given a short period of time (currently about
798     * five seconds) to wake up.  If the dream does not finish itself in a timely manner
799     * then the system will forcibly finish it once the time allowance is up.
800     * </p>
801     */
802    public void onWakeUp() {
803        finish();
804    }
805
806    /** {@inheritDoc} */
807    @Override
808    public final IBinder onBind(Intent intent) {
809        if (mDebug) Slog.v(TAG, "onBind() intent = " + intent);
810        return new DreamServiceWrapper();
811    }
812
813    /**
814     * Stops the dream and detaches from the window.
815     * <p>
816     * When the dream ends, the system will be allowed to go to sleep fully unless there
817     * is a reason for it to be awake such as recent user activity or wake locks being held.
818     * </p>
819     */
820    public final void finish() {
821        if (mDebug) Slog.v(TAG, "finish(): mFinished=" + mFinished);
822
823        if (!mFinished) {
824            mFinished = true;
825
826            if (mWindowToken == null) {
827                Slog.w(TAG, "Finish was called before the dream was attached.");
828            } else {
829                try {
830                    mSandman.finishSelf(mWindowToken, true /*immediate*/);
831                } catch (RemoteException ex) {
832                    // system server died
833                }
834            }
835
836            stopSelf(); // if launched via any other means
837        }
838    }
839
840    /**
841     * Wakes the dream up gently.
842     * <p>
843     * Calls {@link #onWakeUp} to give the dream a chance to perform an exit transition.
844     * When the transition is over, the dream should call {@link #finish}.
845     * </p>
846     */
847    public final void wakeUp() {
848        wakeUp(false);
849    }
850
851    private void wakeUp(boolean fromSystem) {
852        if (mDebug) Slog.v(TAG, "wakeUp(): fromSystem=" + fromSystem
853                + ", mWaking=" + mWaking + ", mFinished=" + mFinished);
854
855        if (!mWaking && !mFinished) {
856            mWaking = true;
857
858            // As a minor optimization, invoke the callback first in case it simply
859            // calls finish() immediately so there wouldn't be much point in telling
860            // the system that we are finishing the dream gently.
861            onWakeUp();
862
863            // Now tell the system we are waking gently, unless we already told
864            // it we were finishing immediately.
865            if (!fromSystem && !mFinished) {
866                if (mWindowToken == null) {
867                    Slog.w(TAG, "WakeUp was called before the dream was attached.");
868                } else {
869                    try {
870                        mSandman.finishSelf(mWindowToken, false /*immediate*/);
871                    } catch (RemoteException ex) {
872                        // system server died
873                    }
874                }
875            }
876        }
877    }
878
879    /** {@inheritDoc} */
880    @Override
881    public void onDestroy() {
882        if (mDebug) Slog.v(TAG, "onDestroy()");
883        // hook for subclasses
884
885        // Just in case destroy came in before detach, let's take care of that now
886        detach();
887
888        super.onDestroy();
889    }
890
891    // end public api
892
893    /**
894     * Called by DreamController.stopDream() when the Dream is about to be unbound and destroyed.
895     *
896     * Must run on mHandler.
897     */
898    private final void detach() {
899        if (mStarted) {
900            if (mDebug) Slog.v(TAG, "detach(): Calling onDreamingStopped()");
901            mStarted = false;
902            onDreamingStopped();
903        }
904
905        if (mWindow != null) {
906            // force our window to be removed synchronously
907            if (mDebug) Slog.v(TAG, "detach(): Removing window from window manager");
908            mWindow.getWindowManager().removeViewImmediate(mWindow.getDecorView());
909            mWindow = null;
910        }
911
912        if (mWindowToken != null) {
913            // the following will print a log message if it finds any other leaked windows
914            WindowManagerGlobal.getInstance().closeAll(mWindowToken,
915                    this.getClass().getName(), "Dream");
916            mWindowToken = null;
917            mCanDoze = false;
918        }
919    }
920
921    /**
922     * Called when the Dream is ready to be shown.
923     *
924     * Must run on mHandler.
925     *
926     * @param windowToken A window token that will allow a window to be created in the correct layer.
927     */
928    private final void attach(IBinder windowToken, boolean canDoze) {
929        if (mWindowToken != null) {
930            Slog.e(TAG, "attach() called when already attached with token=" + mWindowToken);
931            return;
932        }
933        if (mFinished || mWaking) {
934            Slog.w(TAG, "attach() called after dream already finished");
935            try {
936                mSandman.finishSelf(windowToken, true /*immediate*/);
937            } catch (RemoteException ex) {
938                // system server died
939            }
940            return;
941        }
942
943        mWindowToken = windowToken;
944        mCanDoze = canDoze;
945        if (mWindowless && !mCanDoze) {
946            throw new IllegalStateException("Only doze dreams can be windowless");
947        }
948        if (!mWindowless) {
949            mWindow = PolicyManager.makeNewWindow(this);
950            mWindow.setCallback(this);
951            mWindow.requestFeature(Window.FEATURE_NO_TITLE);
952            mWindow.setBackgroundDrawable(new ColorDrawable(0xFF000000));
953            mWindow.setFormat(PixelFormat.OPAQUE);
954
955            if (mDebug) Slog.v(TAG, String.format("Attaching window token: %s to window of type %s",
956                    windowToken, WindowManager.LayoutParams.TYPE_DREAM));
957
958            WindowManager.LayoutParams lp = mWindow.getAttributes();
959            lp.type = WindowManager.LayoutParams.TYPE_DREAM;
960            lp.token = windowToken;
961            lp.windowAnimations = com.android.internal.R.style.Animation_Dream;
962            lp.flags |= ( WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
963                        | WindowManager.LayoutParams.FLAG_LAYOUT_INSET_DECOR
964                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
965                        | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
966                        | WindowManager.LayoutParams.FLAG_ALLOW_LOCK_WHILE_SCREEN_ON
967                        | (mFullscreen ? WindowManager.LayoutParams.FLAG_FULLSCREEN : 0)
968                        | (mScreenBright ? WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON : 0)
969                        );
970            mWindow.setAttributes(lp);
971            mWindow.setWindowManager(null, windowToken, "dream", true);
972
973            applySystemUiVisibilityFlags(
974                    (mLowProfile ? View.SYSTEM_UI_FLAG_LOW_PROFILE : 0),
975                    View.SYSTEM_UI_FLAG_LOW_PROFILE);
976
977            try {
978                getWindowManager().addView(mWindow.getDecorView(), mWindow.getAttributes());
979            } catch (WindowManager.BadTokenException ex) {
980                // This can happen because the dream manager service will remove the token
981                // immediately without necessarily waiting for the dream to start.
982                // We should receive a finish message soon.
983                Slog.i(TAG, "attach() called after window token already removed, dream will "
984                        + "finish soon");
985                mWindow = null;
986                return;
987            }
988        }
989        // We need to defer calling onDreamingStarted until after onWindowAttached,
990        // which is posted to the handler by addView, so we post onDreamingStarted
991        // to the handler also.  Need to watch out here in case detach occurs before
992        // this callback is invoked.
993        mHandler.post(new Runnable() {
994            @Override
995            public void run() {
996                if (mWindow != null || mWindowless) {
997                    if (mDebug) Slog.v(TAG, "Calling onDreamingStarted()");
998                    mStarted = true;
999                    onDreamingStarted();
1000                }
1001            }
1002        });
1003    }
1004
1005    private boolean getWindowFlagValue(int flag, boolean defaultValue) {
1006        return mWindow == null ? defaultValue : (mWindow.getAttributes().flags & flag) != 0;
1007    }
1008
1009    private void applyWindowFlags(int flags, int mask) {
1010        if (mWindow != null) {
1011            WindowManager.LayoutParams lp = mWindow.getAttributes();
1012            lp.flags = applyFlags(lp.flags, flags, mask);
1013            mWindow.setAttributes(lp);
1014            mWindow.getWindowManager().updateViewLayout(mWindow.getDecorView(), lp);
1015        }
1016    }
1017
1018    private boolean getSystemUiVisibilityFlagValue(int flag, boolean defaultValue) {
1019        View v = mWindow == null ? null : mWindow.getDecorView();
1020        return v == null ? defaultValue : (v.getSystemUiVisibility() & flag) != 0;
1021    }
1022
1023    private void applySystemUiVisibilityFlags(int flags, int mask) {
1024        View v = mWindow == null ? null : mWindow.getDecorView();
1025        if (v != null) {
1026            v.setSystemUiVisibility(applyFlags(v.getSystemUiVisibility(), flags, mask));
1027        }
1028    }
1029
1030    private int applyFlags(int oldFlags, int flags, int mask) {
1031        return (oldFlags&~mask) | (flags&mask);
1032    }
1033
1034    @Override
1035    protected void dump(final FileDescriptor fd, PrintWriter pw, final String[] args) {
1036        DumpUtils.dumpAsync(mHandler, new Dump() {
1037            @Override
1038            public void dump(PrintWriter pw) {
1039                dumpOnHandler(fd, pw, args);
1040            }
1041        }, pw, 1000);
1042    }
1043
1044    /** @hide */
1045    protected void dumpOnHandler(FileDescriptor fd, PrintWriter pw, String[] args) {
1046        pw.print(TAG + ": ");
1047        if (mWindowToken == null) {
1048            pw.println("stopped");
1049        } else {
1050            pw.println("running (token=" + mWindowToken + ")");
1051        }
1052        pw.println("  window: " + mWindow);
1053        pw.print("  flags:");
1054        if (isInteractive()) pw.print(" interactive");
1055        if (isLowProfile()) pw.print(" lowprofile");
1056        if (isFullscreen()) pw.print(" fullscreen");
1057        if (isScreenBright()) pw.print(" bright");
1058        if (isWindowless()) pw.print(" windowless");
1059        if (isDozing()) pw.print(" dozing");
1060        else if (canDoze()) pw.print(" candoze");
1061        pw.println();
1062        if (canDoze()) {
1063            pw.println("  doze screen state: " + Display.stateToString(mDozeScreenState));
1064            pw.println("  doze screen brightness: " + mDozeScreenBrightness);
1065        }
1066    }
1067
1068    private static int clampAbsoluteBrightness(int value) {
1069        return MathUtils.constrain(value, PowerManager.BRIGHTNESS_OFF, PowerManager.BRIGHTNESS_ON);
1070    }
1071
1072    private final class DreamServiceWrapper extends IDreamService.Stub {
1073        @Override
1074        public void attach(final IBinder windowToken, final boolean canDoze) {
1075            mHandler.post(new Runnable() {
1076                @Override
1077                public void run() {
1078                    DreamService.this.attach(windowToken, canDoze);
1079                }
1080            });
1081        }
1082
1083        @Override
1084        public void detach() {
1085            mHandler.post(new Runnable() {
1086                @Override
1087                public void run() {
1088                    DreamService.this.detach();
1089                }
1090            });
1091        }
1092
1093        @Override
1094        public void wakeUp() {
1095            mHandler.post(new Runnable() {
1096                @Override
1097                public void run() {
1098                    DreamService.this.wakeUp(true /*fromSystem*/);
1099                }
1100            });
1101        }
1102    }
1103}
1104