WallpaperService.java revision aac0d4ed026d1cfbcf3fa81c6e4eb96f4347ca17
1/*
2 * Copyright (C) 2009 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 android.service.wallpaper;
18
19import com.android.internal.os.HandlerCaller;
20import com.android.internal.view.BaseIWindow;
21import com.android.internal.view.BaseSurfaceHolder;
22
23import android.annotation.SdkConstant;
24import android.annotation.SdkConstant.SdkConstantType;
25import android.app.Service;
26import android.app.WallpaperManager;
27import android.content.BroadcastReceiver;
28import android.content.Context;
29import android.content.Intent;
30import android.content.IntentFilter;
31import android.content.res.Configuration;
32import android.graphics.PixelFormat;
33import android.graphics.Rect;
34import android.os.Bundle;
35import android.os.IBinder;
36import android.os.Looper;
37import android.os.Message;
38import android.os.PowerManager;
39import android.os.Process;
40import android.os.RemoteException;
41import android.util.Log;
42import android.util.LogPrinter;
43import android.view.Gravity;
44import android.view.IWindowSession;
45import android.view.InputChannel;
46import android.view.InputDevice;
47import android.view.InputEvent;
48import android.view.InputEventReceiver;
49import android.view.MotionEvent;
50import android.view.SurfaceHolder;
51import android.view.View;
52import android.view.ViewGroup;
53import android.view.ViewRootImpl;
54import android.view.WindowManager;
55import android.view.WindowManagerImpl;
56
57import java.io.FileDescriptor;
58import java.io.PrintWriter;
59import java.util.ArrayList;
60
61/**
62 * A wallpaper service is responsible for showing a live wallpaper behind
63 * applications that would like to sit on top of it.  This service object
64 * itself does very little -- its only purpose is to generate instances of
65 * {@link Engine} as needed.  Implementing a wallpaper thus
66 * involves subclassing from this, subclassing an Engine implementation,
67 * and implementing {@link #onCreateEngine()} to return a new instance of
68 * your engine.
69 */
70public abstract class WallpaperService extends Service {
71    /**
72     * The {@link Intent} that must be declared as handled by the service.
73     * To be supported, the service must also require the
74     * {@link android.Manifest.permission#BIND_WALLPAPER} permission so
75     * that other applications can not abuse it.
76     */
77    @SdkConstant(SdkConstantType.SERVICE_ACTION)
78    public static final String SERVICE_INTERFACE =
79            "android.service.wallpaper.WallpaperService";
80
81    /**
82     * Name under which a WallpaperService component publishes information
83     * about itself.  This meta-data must reference an XML resource containing
84     * a <code>&lt;{@link android.R.styleable#Wallpaper wallpaper}&gt;</code>
85     * tag.
86     */
87    public static final String SERVICE_META_DATA = "android.service.wallpaper";
88
89    static final String TAG = "WallpaperService";
90    static final boolean DEBUG = false;
91
92    private static final int DO_ATTACH = 10;
93    private static final int DO_DETACH = 20;
94    private static final int DO_SET_DESIRED_SIZE = 30;
95
96    private static final int MSG_UPDATE_SURFACE = 10000;
97    private static final int MSG_VISIBILITY_CHANGED = 10010;
98    private static final int MSG_WALLPAPER_OFFSETS = 10020;
99    private static final int MSG_WALLPAPER_COMMAND = 10025;
100    private static final int MSG_WINDOW_RESIZED = 10030;
101    private static final int MSG_WINDOW_MOVED = 10035;
102    private static final int MSG_TOUCH_EVENT = 10040;
103
104    private Looper mCallbackLooper;
105    private final ArrayList<Engine> mActiveEngines
106            = new ArrayList<Engine>();
107
108    static final class WallpaperCommand {
109        String action;
110        int x;
111        int y;
112        int z;
113        Bundle extras;
114        boolean sync;
115    }
116
117    /**
118     * The actual implementation of a wallpaper.  A wallpaper service may
119     * have multiple instances running (for example as a real wallpaper
120     * and as a preview), each of which is represented by its own Engine
121     * instance.  You must implement {@link WallpaperService#onCreateEngine()}
122     * to return your concrete Engine implementation.
123     */
124    public class Engine {
125        IWallpaperEngineWrapper mIWallpaperEngine;
126
127        // Copies from mIWallpaperEngine.
128        HandlerCaller mCaller;
129        IWallpaperConnection mConnection;
130        IBinder mWindowToken;
131
132        boolean mInitializing = true;
133        boolean mVisible;
134        boolean mScreenOn = true;
135        boolean mReportedVisible;
136        boolean mDestroyed;
137
138        // Current window state.
139        boolean mCreated;
140        boolean mSurfaceCreated;
141        boolean mIsCreating;
142        boolean mDrawingAllowed;
143        boolean mOffsetsChanged;
144        boolean mFixedSizeAllowed;
145        int mWidth;
146        int mHeight;
147        int mFormat;
148        int mType;
149        int mCurWidth;
150        int mCurHeight;
151        int mWindowFlags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
152        int mWindowPrivateFlags =
153                WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS;
154        int mCurWindowFlags = mWindowFlags;
155        int mCurWindowPrivateFlags = mWindowPrivateFlags;
156        final Rect mVisibleInsets = new Rect();
157        final Rect mWinFrame = new Rect();
158        final Rect mContentInsets = new Rect();
159        final Configuration mConfiguration = new Configuration();
160
161        final WindowManager.LayoutParams mLayout
162                = new WindowManager.LayoutParams();
163        IWindowSession mSession;
164        InputChannel mInputChannel;
165
166        final Object mLock = new Object();
167        boolean mOffsetMessageEnqueued;
168        float mPendingXOffset;
169        float mPendingYOffset;
170        float mPendingXOffsetStep;
171        float mPendingYOffsetStep;
172        boolean mPendingSync;
173        MotionEvent mPendingMove;
174
175        final BroadcastReceiver mReceiver = new BroadcastReceiver() {
176            @Override
177            public void onReceive(Context context, Intent intent) {
178                if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
179                    mScreenOn = true;
180                    reportVisibility();
181                } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
182                    mScreenOn = false;
183                    reportVisibility();
184                }
185            }
186        };
187
188        final BaseSurfaceHolder mSurfaceHolder = new BaseSurfaceHolder() {
189            {
190                mRequestedFormat = PixelFormat.RGBX_8888;
191            }
192
193            @Override
194            public boolean onAllowLockCanvas() {
195                return mDrawingAllowed;
196            }
197
198            @Override
199            public void onRelayoutContainer() {
200                Message msg = mCaller.obtainMessage(MSG_UPDATE_SURFACE);
201                mCaller.sendMessage(msg);
202            }
203
204            @Override
205            public void onUpdateSurface() {
206                Message msg = mCaller.obtainMessage(MSG_UPDATE_SURFACE);
207                mCaller.sendMessage(msg);
208            }
209
210            public boolean isCreating() {
211                return mIsCreating;
212            }
213
214            @Override
215            public void setFixedSize(int width, int height) {
216                if (!mFixedSizeAllowed) {
217                    // Regular apps can't do this.  It can only work for
218                    // certain designs of window animations, so you can't
219                    // rely on it.
220                    throw new UnsupportedOperationException(
221                            "Wallpapers currently only support sizing from layout");
222                }
223                super.setFixedSize(width, height);
224            }
225
226            public void setKeepScreenOn(boolean screenOn) {
227                throw new UnsupportedOperationException(
228                        "Wallpapers do not support keep screen on");
229            }
230
231        };
232
233        final class WallpaperInputEventReceiver extends InputEventReceiver {
234            public WallpaperInputEventReceiver(InputChannel inputChannel, Looper looper) {
235                super(inputChannel, looper);
236            }
237
238            @Override
239            public void onInputEvent(InputEvent event) {
240                boolean handled = false;
241                try {
242                    if (event instanceof MotionEvent
243                            && (event.getSource() & InputDevice.SOURCE_CLASS_POINTER) != 0) {
244                        MotionEvent dup = MotionEvent.obtainNoHistory((MotionEvent)event);
245                        dispatchPointer(dup);
246                        handled = true;
247                    }
248                } finally {
249                    finishInputEvent(event, handled);
250                }
251            }
252        }
253        WallpaperInputEventReceiver mInputEventReceiver;
254
255        final BaseIWindow mWindow = new BaseIWindow() {
256            @Override
257            public void resized(int w, int h, Rect contentInsets,
258                    Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
259                Message msg = mCaller.obtainMessageI(MSG_WINDOW_RESIZED,
260                        reportDraw ? 1 : 0);
261                mCaller.sendMessage(msg);
262            }
263
264            @Override
265            public void moved(int newX, int newY) {
266                Message msg = mCaller.obtainMessageII(MSG_WINDOW_MOVED, newX, newY);
267                mCaller.sendMessage(msg);
268            }
269
270            @Override
271            public void dispatchAppVisibility(boolean visible) {
272                // We don't do this in preview mode; we'll let the preview
273                // activity tell us when to run.
274                if (!mIWallpaperEngine.mIsPreview) {
275                    Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED,
276                            visible ? 1 : 0);
277                    mCaller.sendMessage(msg);
278                }
279            }
280
281            @Override
282            public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
283                    boolean sync) {
284                synchronized (mLock) {
285                    if (DEBUG) Log.v(TAG, "Dispatch wallpaper offsets: " + x + ", " + y);
286                    mPendingXOffset = x;
287                    mPendingYOffset = y;
288                    mPendingXOffsetStep = xStep;
289                    mPendingYOffsetStep = yStep;
290                    if (sync) {
291                        mPendingSync = true;
292                    }
293                    if (!mOffsetMessageEnqueued) {
294                        mOffsetMessageEnqueued = true;
295                        Message msg = mCaller.obtainMessage(MSG_WALLPAPER_OFFSETS);
296                        mCaller.sendMessage(msg);
297                    }
298                }
299            }
300
301            @Override
302            public void dispatchWallpaperCommand(String action, int x, int y,
303                    int z, Bundle extras, boolean sync) {
304                synchronized (mLock) {
305                    if (DEBUG) Log.v(TAG, "Dispatch wallpaper command: " + x + ", " + y);
306                    WallpaperCommand cmd = new WallpaperCommand();
307                    cmd.action = action;
308                    cmd.x = x;
309                    cmd.y = y;
310                    cmd.z = z;
311                    cmd.extras = extras;
312                    cmd.sync = sync;
313                    Message msg = mCaller.obtainMessage(MSG_WALLPAPER_COMMAND);
314                    msg.obj = cmd;
315                    mCaller.sendMessage(msg);
316                }
317            }
318        };
319
320        /**
321         * Provides access to the surface in which this wallpaper is drawn.
322         */
323        public SurfaceHolder getSurfaceHolder() {
324            return mSurfaceHolder;
325        }
326
327        /**
328         * Convenience for {@link WallpaperManager#getDesiredMinimumWidth()
329         * WallpaperManager.getDesiredMinimumWidth()}, returning the width
330         * that the system would like this wallpaper to run in.
331         */
332        public int getDesiredMinimumWidth() {
333            return mIWallpaperEngine.mReqWidth;
334        }
335
336        /**
337         * Convenience for {@link WallpaperManager#getDesiredMinimumHeight()
338         * WallpaperManager.getDesiredMinimumHeight()}, returning the height
339         * that the system would like this wallpaper to run in.
340         */
341        public int getDesiredMinimumHeight() {
342            return mIWallpaperEngine.mReqHeight;
343        }
344
345        /**
346         * Return whether the wallpaper is currently visible to the user,
347         * this is the last value supplied to
348         * {@link #onVisibilityChanged(boolean)}.
349         */
350        public boolean isVisible() {
351            return mReportedVisible;
352        }
353
354        /**
355         * Returns true if this engine is running in preview mode -- that is,
356         * it is being shown to the user before they select it as the actual
357         * wallpaper.
358         */
359        public boolean isPreview() {
360            return mIWallpaperEngine.mIsPreview;
361        }
362
363        /**
364         * Control whether this wallpaper will receive raw touch events
365         * from the window manager as the user interacts with the window
366         * that is currently displaying the wallpaper.  By default they
367         * are turned off.  If enabled, the events will be received in
368         * {@link #onTouchEvent(MotionEvent)}.
369         */
370        public void setTouchEventsEnabled(boolean enabled) {
371            mWindowFlags = enabled
372                    ? (mWindowFlags&~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
373                    : (mWindowFlags|WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
374            if (mCreated) {
375                updateSurface(false, false, false);
376            }
377        }
378
379        /**
380         * Control whether this wallpaper will receive notifications when the wallpaper
381         * has been scrolled. By default, wallpapers will receive notifications, although
382         * the default static image wallpapers do not. It is a performance optimization to
383         * set this to false.
384         *
385         * @param enabled whether the wallpaper wants to receive offset notifications
386         */
387        public void setOffsetNotificationsEnabled(boolean enabled) {
388            mWindowPrivateFlags = enabled
389                    ? (mWindowPrivateFlags |
390                        WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS)
391                    : (mWindowPrivateFlags &
392                        ~WindowManager.LayoutParams.PRIVATE_FLAG_WANTS_OFFSET_NOTIFICATIONS);
393            if (mCreated) {
394                updateSurface(false, false, false);
395            }
396        }
397
398        /** {@hide} */
399        public void setFixedSizeAllowed(boolean allowed) {
400            mFixedSizeAllowed = allowed;
401        }
402
403        /**
404         * Called once to initialize the engine.  After returning, the
405         * engine's surface will be created by the framework.
406         */
407        public void onCreate(SurfaceHolder surfaceHolder) {
408        }
409
410        /**
411         * Called right before the engine is going away.  After this the
412         * surface will be destroyed and this Engine object is no longer
413         * valid.
414         */
415        public void onDestroy() {
416        }
417
418        /**
419         * Called to inform you of the wallpaper becoming visible or
420         * hidden.  <em>It is very important that a wallpaper only use
421         * CPU while it is visible.</em>.
422         */
423        public void onVisibilityChanged(boolean visible) {
424        }
425
426        /**
427         * Called as the user performs touch-screen interaction with the
428         * window that is currently showing this wallpaper.  Note that the
429         * events you receive here are driven by the actual application the
430         * user is interacting with, so if it is slow you will get fewer
431         * move events.
432         */
433        public void onTouchEvent(MotionEvent event) {
434        }
435
436        /**
437         * Called to inform you of the wallpaper's offsets changing
438         * within its contain, corresponding to the container's
439         * call to {@link WallpaperManager#setWallpaperOffsets(IBinder, float, float)
440         * WallpaperManager.setWallpaperOffsets()}.
441         */
442        public void onOffsetsChanged(float xOffset, float yOffset,
443                float xOffsetStep, float yOffsetStep,
444                int xPixelOffset, int yPixelOffset) {
445        }
446
447        /**
448         * Process a command that was sent to the wallpaper with
449         * {@link WallpaperManager#sendWallpaperCommand}.
450         * The default implementation does nothing, and always returns null
451         * as the result.
452         *
453         * @param action The name of the command to perform.  This tells you
454         * what to do and how to interpret the rest of the arguments.
455         * @param x Generic integer parameter.
456         * @param y Generic integer parameter.
457         * @param z Generic integer parameter.
458         * @param extras Any additional parameters.
459         * @param resultRequested If true, the caller is requesting that
460         * a result, appropriate for the command, be returned back.
461         * @return If returning a result, create a Bundle and place the
462         * result data in to it.  Otherwise return null.
463         */
464        public Bundle onCommand(String action, int x, int y, int z,
465                Bundle extras, boolean resultRequested) {
466            return null;
467        }
468
469        /**
470         * Called when an application has changed the desired virtual size of
471         * the wallpaper.
472         */
473        public void onDesiredSizeChanged(int desiredWidth, int desiredHeight) {
474        }
475
476        /**
477         * Convenience for {@link SurfaceHolder.Callback#surfaceChanged
478         * SurfaceHolder.Callback.surfaceChanged()}.
479         */
480        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
481        }
482
483        /**
484         * Convenience for {@link SurfaceHolder.Callback2#surfaceRedrawNeeded
485         * SurfaceHolder.Callback.surfaceRedrawNeeded()}.
486         */
487        public void onSurfaceRedrawNeeded(SurfaceHolder holder) {
488        }
489
490        /**
491         * Convenience for {@link SurfaceHolder.Callback#surfaceCreated
492         * SurfaceHolder.Callback.surfaceCreated()}.
493         */
494        public void onSurfaceCreated(SurfaceHolder holder) {
495        }
496
497        /**
498         * Convenience for {@link SurfaceHolder.Callback#surfaceDestroyed
499         * SurfaceHolder.Callback.surfaceDestroyed()}.
500         */
501        public void onSurfaceDestroyed(SurfaceHolder holder) {
502        }
503
504        protected void dump(String prefix, FileDescriptor fd, PrintWriter out, String[] args) {
505            out.print(prefix); out.print("mInitializing="); out.print(mInitializing);
506                    out.print(" mDestroyed="); out.println(mDestroyed);
507            out.print(prefix); out.print("mVisible="); out.print(mVisible);
508                    out.print(" mScreenOn="); out.print(mScreenOn);
509                    out.print(" mReportedVisible="); out.println(mReportedVisible);
510            out.print(prefix); out.print("mCreated="); out.print(mCreated);
511                    out.print(" mSurfaceCreated="); out.print(mSurfaceCreated);
512                    out.print(" mIsCreating="); out.print(mIsCreating);
513                    out.print(" mDrawingAllowed="); out.println(mDrawingAllowed);
514            out.print(prefix); out.print("mWidth="); out.print(mWidth);
515                    out.print(" mCurWidth="); out.print(mCurWidth);
516                    out.print(" mHeight="); out.print(mHeight);
517                    out.print(" mCurHeight="); out.println(mCurHeight);
518            out.print(prefix); out.print("mType="); out.print(mType);
519                    out.print(" mWindowFlags="); out.print(mWindowFlags);
520                    out.print(" mCurWindowFlags="); out.println(mCurWindowFlags);
521                    out.print(" mWindowPrivateFlags="); out.print(mWindowPrivateFlags);
522                    out.print(" mCurWindowPrivateFlags="); out.println(mCurWindowPrivateFlags);
523            out.print(prefix); out.print("mVisibleInsets=");
524                    out.print(mVisibleInsets.toShortString());
525                    out.print(" mWinFrame="); out.print(mWinFrame.toShortString());
526                    out.print(" mContentInsets="); out.println(mContentInsets.toShortString());
527            out.print(prefix); out.print("mConfiguration="); out.println(mConfiguration);
528            out.print(prefix); out.print("mLayout="); out.println(mLayout);
529            synchronized (mLock) {
530                out.print(prefix); out.print("mPendingXOffset="); out.print(mPendingXOffset);
531                        out.print(" mPendingXOffset="); out.println(mPendingXOffset);
532                out.print(prefix); out.print("mPendingXOffsetStep=");
533                        out.print(mPendingXOffsetStep);
534                        out.print(" mPendingXOffsetStep="); out.println(mPendingXOffsetStep);
535                out.print(prefix); out.print("mOffsetMessageEnqueued=");
536                        out.print(mOffsetMessageEnqueued);
537                        out.print(" mPendingSync="); out.println(mPendingSync);
538                if (mPendingMove != null) {
539                    out.print(prefix); out.print("mPendingMove="); out.println(mPendingMove);
540                }
541            }
542        }
543
544        private void dispatchPointer(MotionEvent event) {
545            if (event.isTouchEvent()) {
546                synchronized (mLock) {
547                    if (event.getAction() == MotionEvent.ACTION_MOVE) {
548                        mPendingMove = event;
549                    } else {
550                        mPendingMove = null;
551                    }
552                }
553                Message msg = mCaller.obtainMessageO(MSG_TOUCH_EVENT, event);
554                mCaller.sendMessage(msg);
555            } else {
556                event.recycle();
557            }
558        }
559
560        void updateSurface(boolean forceRelayout, boolean forceReport, boolean redrawNeeded) {
561            if (mDestroyed) {
562                Log.w(TAG, "Ignoring updateSurface: destroyed");
563            }
564
565            int myWidth = mSurfaceHolder.getRequestedWidth();
566            if (myWidth <= 0) myWidth = ViewGroup.LayoutParams.MATCH_PARENT;
567            int myHeight = mSurfaceHolder.getRequestedHeight();
568            if (myHeight <= 0) myHeight = ViewGroup.LayoutParams.MATCH_PARENT;
569
570            final boolean creating = !mCreated;
571            final boolean surfaceCreating = !mSurfaceCreated;
572            final boolean formatChanged = mFormat != mSurfaceHolder.getRequestedFormat();
573            boolean sizeChanged = mWidth != myWidth || mHeight != myHeight;
574            final boolean typeChanged = mType != mSurfaceHolder.getRequestedType();
575            final boolean flagsChanged = mCurWindowFlags != mWindowFlags ||
576                    mCurWindowPrivateFlags != mWindowPrivateFlags;
577            if (forceRelayout || creating || surfaceCreating || formatChanged || sizeChanged
578                    || typeChanged || flagsChanged || redrawNeeded) {
579
580                if (DEBUG) Log.v(TAG, "Changes: creating=" + creating
581                        + " format=" + formatChanged + " size=" + sizeChanged);
582
583                try {
584                    mWidth = myWidth;
585                    mHeight = myHeight;
586                    mFormat = mSurfaceHolder.getRequestedFormat();
587                    mType = mSurfaceHolder.getRequestedType();
588
589                    mLayout.x = 0;
590                    mLayout.y = 0;
591                    mLayout.width = myWidth;
592                    mLayout.height = myHeight;
593
594                    mLayout.format = mFormat;
595
596                    mCurWindowFlags = mWindowFlags;
597                    mLayout.flags = mWindowFlags
598                            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
599                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
600                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
601                            ;
602                    mCurWindowPrivateFlags = mWindowPrivateFlags;
603                    mLayout.privateFlags = mWindowPrivateFlags;
604
605                    mLayout.memoryType = mType;
606                    mLayout.token = mWindowToken;
607
608                    if (!mCreated) {
609                        mLayout.type = mIWallpaperEngine.mWindowType;
610                        mLayout.gravity = Gravity.START|Gravity.TOP;
611                        mLayout.setTitle(WallpaperService.this.getClass().getName());
612                        mLayout.windowAnimations =
613                                com.android.internal.R.style.Animation_Wallpaper;
614                        mInputChannel = new InputChannel();
615                        if (mSession.add(mWindow, mWindow.mSeq, mLayout, View.VISIBLE, mContentInsets,
616                                mInputChannel) < 0) {
617                            Log.w(TAG, "Failed to add window while updating wallpaper surface.");
618                            return;
619                        }
620                        mCreated = true;
621
622                        mInputEventReceiver = new WallpaperInputEventReceiver(
623                                mInputChannel, Looper.myLooper());
624                    }
625
626                    mSurfaceHolder.mSurfaceLock.lock();
627                    mDrawingAllowed = true;
628
629                    final int relayoutResult = mSession.relayout(
630                        mWindow, mWindow.mSeq, mLayout, mWidth, mHeight,
631                            View.VISIBLE, 0, mWinFrame, mContentInsets,
632                            mVisibleInsets, mConfiguration, mSurfaceHolder.mSurface);
633
634                    if (DEBUG) Log.v(TAG, "New surface: " + mSurfaceHolder.mSurface
635                            + ", frame=" + mWinFrame);
636
637                    int w = mWinFrame.width();
638                    if (mCurWidth != w) {
639                        sizeChanged = true;
640                        mCurWidth = w;
641                    }
642                    int h = mWinFrame.height();
643                    if (mCurHeight != h) {
644                        sizeChanged = true;
645                        mCurHeight = h;
646                    }
647
648                    mSurfaceHolder.setSurfaceFrameSize(w, h);
649                    mSurfaceHolder.mSurfaceLock.unlock();
650
651                    if (!mSurfaceHolder.mSurface.isValid()) {
652                        reportSurfaceDestroyed();
653                        if (DEBUG) Log.v(TAG, "Layout: Surface destroyed");
654                        return;
655                    }
656
657                    boolean didSurface = false;
658
659                    try {
660                        mSurfaceHolder.ungetCallbacks();
661
662                        if (surfaceCreating) {
663                            mIsCreating = true;
664                            didSurface = true;
665                            if (DEBUG) Log.v(TAG, "onSurfaceCreated("
666                                    + mSurfaceHolder + "): " + this);
667                            onSurfaceCreated(mSurfaceHolder);
668                            SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
669                            if (callbacks != null) {
670                                for (SurfaceHolder.Callback c : callbacks) {
671                                    c.surfaceCreated(mSurfaceHolder);
672                                }
673                            }
674                        }
675
676                        redrawNeeded |= creating
677                                || (relayoutResult&WindowManagerImpl.RELAYOUT_RES_FIRST_TIME) != 0;
678
679                        if (forceReport || creating || surfaceCreating
680                                || formatChanged || sizeChanged) {
681                            if (DEBUG) {
682                                RuntimeException e = new RuntimeException();
683                                e.fillInStackTrace();
684                                Log.w(TAG, "forceReport=" + forceReport + " creating=" + creating
685                                        + " formatChanged=" + formatChanged
686                                        + " sizeChanged=" + sizeChanged, e);
687                            }
688                            if (DEBUG) Log.v(TAG, "onSurfaceChanged("
689                                    + mSurfaceHolder + ", " + mFormat
690                                    + ", " + mCurWidth + ", " + mCurHeight
691                                    + "): " + this);
692                            didSurface = true;
693                            onSurfaceChanged(mSurfaceHolder, mFormat,
694                                    mCurWidth, mCurHeight);
695                            SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
696                            if (callbacks != null) {
697                                for (SurfaceHolder.Callback c : callbacks) {
698                                    c.surfaceChanged(mSurfaceHolder, mFormat,
699                                            mCurWidth, mCurHeight);
700                                }
701                            }
702                        }
703
704                        if (redrawNeeded) {
705                            onSurfaceRedrawNeeded(mSurfaceHolder);
706                            SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
707                            if (callbacks != null) {
708                                for (SurfaceHolder.Callback c : callbacks) {
709                                    if (c instanceof SurfaceHolder.Callback2) {
710                                        ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
711                                                mSurfaceHolder);
712                                    }
713                                }
714                            }
715                        }
716
717                        if (didSurface && !mReportedVisible) {
718                            // This wallpaper is currently invisible, but its
719                            // surface has changed.  At this point let's tell it
720                            // again that it is invisible in case the report about
721                            // the surface caused it to start running.  We really
722                            // don't want wallpapers running when not visible.
723                            if (mIsCreating) {
724                                // Some wallpapers will ignore this call if they
725                                // had previously been told they were invisble,
726                                // so if we are creating a new surface then toggle
727                                // the state to get them to notice.
728                                if (DEBUG) Log.v(TAG, "onVisibilityChanged(true) at surface: "
729                                        + this);
730                                onVisibilityChanged(true);
731                            }
732                            if (DEBUG) Log.v(TAG, "onVisibilityChanged(false) at surface: "
733                                        + this);
734                            onVisibilityChanged(false);
735                        }
736
737                    } finally {
738                        mIsCreating = false;
739                        mSurfaceCreated = true;
740                        if (redrawNeeded) {
741                            mSession.finishDrawing(mWindow);
742                        }
743                    }
744                } catch (RemoteException ex) {
745                }
746                if (DEBUG) Log.v(
747                    TAG, "Layout: x=" + mLayout.x + " y=" + mLayout.y +
748                    " w=" + mLayout.width + " h=" + mLayout.height);
749            }
750        }
751
752        void attach(IWallpaperEngineWrapper wrapper) {
753            if (DEBUG) Log.v(TAG, "attach: " + this + " wrapper=" + wrapper);
754            if (mDestroyed) {
755                return;
756            }
757
758            mIWallpaperEngine = wrapper;
759            mCaller = wrapper.mCaller;
760            mConnection = wrapper.mConnection;
761            mWindowToken = wrapper.mWindowToken;
762            mSurfaceHolder.setSizeFromLayout();
763            mInitializing = true;
764            mSession = ViewRootImpl.getWindowSession(getMainLooper());
765
766            mWindow.setSession(mSession);
767
768            mScreenOn = ((PowerManager)getSystemService(Context.POWER_SERVICE)).isScreenOn();
769
770            IntentFilter filter = new IntentFilter();
771            filter.addAction(Intent.ACTION_SCREEN_ON);
772            filter.addAction(Intent.ACTION_SCREEN_OFF);
773            registerReceiver(mReceiver, filter);
774
775            if (DEBUG) Log.v(TAG, "onCreate(): " + this);
776            onCreate(mSurfaceHolder);
777
778            mInitializing = false;
779            mReportedVisible = false;
780            updateSurface(false, false, false);
781        }
782
783        void doDesiredSizeChanged(int desiredWidth, int desiredHeight) {
784            if (!mDestroyed) {
785                if (DEBUG) Log.v(TAG, "onDesiredSizeChanged("
786                        + desiredWidth + "," + desiredHeight + "): " + this);
787                mIWallpaperEngine.mReqWidth = desiredWidth;
788                mIWallpaperEngine.mReqHeight = desiredHeight;
789                onDesiredSizeChanged(desiredWidth, desiredHeight);
790                doOffsetsChanged(true);
791            }
792        }
793
794        void doVisibilityChanged(boolean visible) {
795            if (!mDestroyed) {
796                mVisible = visible;
797                reportVisibility();
798            }
799        }
800
801        void reportVisibility() {
802            if (!mDestroyed) {
803                boolean visible = mVisible && mScreenOn;
804                if (mReportedVisible != visible) {
805                    mReportedVisible = visible;
806                    if (DEBUG) Log.v(TAG, "onVisibilityChanged(" + visible
807                            + "): " + this);
808                    if (visible) {
809                        // If becoming visible, in preview mode the surface
810                        // may have been destroyed so now we need to make
811                        // sure it is re-created.
812                        doOffsetsChanged(false);
813                        updateSurface(false, false, false);
814                    }
815                    onVisibilityChanged(visible);
816                }
817            }
818        }
819
820        void doOffsetsChanged(boolean always) {
821            if (mDestroyed) {
822                return;
823            }
824
825            if (!always && !mOffsetsChanged) {
826                return;
827            }
828
829            float xOffset;
830            float yOffset;
831            float xOffsetStep;
832            float yOffsetStep;
833            boolean sync;
834            synchronized (mLock) {
835                xOffset = mPendingXOffset;
836                yOffset = mPendingYOffset;
837                xOffsetStep = mPendingXOffsetStep;
838                yOffsetStep = mPendingYOffsetStep;
839                sync = mPendingSync;
840                mPendingSync = false;
841                mOffsetMessageEnqueued = false;
842            }
843
844            if (mSurfaceCreated) {
845                if (mReportedVisible) {
846                    if (DEBUG) Log.v(TAG, "Offsets change in " + this
847                            + ": " + xOffset + "," + yOffset);
848                    final int availw = mIWallpaperEngine.mReqWidth-mCurWidth;
849                    final int xPixels = availw > 0 ? -(int)(availw*xOffset+.5f) : 0;
850                    final int availh = mIWallpaperEngine.mReqHeight-mCurHeight;
851                    final int yPixels = availh > 0 ? -(int)(availh*yOffset+.5f) : 0;
852                    onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixels, yPixels);
853                } else {
854                    mOffsetsChanged = true;
855                }
856            }
857
858            if (sync) {
859                try {
860                    if (DEBUG) Log.v(TAG, "Reporting offsets change complete");
861                    mSession.wallpaperOffsetsComplete(mWindow.asBinder());
862                } catch (RemoteException e) {
863                }
864            }
865        }
866
867        void doCommand(WallpaperCommand cmd) {
868            Bundle result;
869            if (!mDestroyed) {
870                result = onCommand(cmd.action, cmd.x, cmd.y, cmd.z,
871                        cmd.extras, cmd.sync);
872            } else {
873                result = null;
874            }
875            if (cmd.sync) {
876                try {
877                    if (DEBUG) Log.v(TAG, "Reporting command complete");
878                    mSession.wallpaperCommandComplete(mWindow.asBinder(), result);
879                } catch (RemoteException e) {
880                }
881            }
882        }
883
884        void reportSurfaceDestroyed() {
885            if (mSurfaceCreated) {
886                mSurfaceCreated = false;
887                mSurfaceHolder.ungetCallbacks();
888                SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
889                if (callbacks != null) {
890                    for (SurfaceHolder.Callback c : callbacks) {
891                        c.surfaceDestroyed(mSurfaceHolder);
892                    }
893                }
894                if (DEBUG) Log.v(TAG, "onSurfaceDestroyed("
895                        + mSurfaceHolder + "): " + this);
896                onSurfaceDestroyed(mSurfaceHolder);
897            }
898        }
899
900        void detach() {
901            if (mDestroyed) {
902                return;
903            }
904
905            mDestroyed = true;
906
907            if (mVisible) {
908                mVisible = false;
909                if (DEBUG) Log.v(TAG, "onVisibilityChanged(false): " + this);
910                onVisibilityChanged(false);
911            }
912
913            reportSurfaceDestroyed();
914
915            if (DEBUG) Log.v(TAG, "onDestroy(): " + this);
916            onDestroy();
917
918            unregisterReceiver(mReceiver);
919
920            if (mCreated) {
921                try {
922                    if (DEBUG) Log.v(TAG, "Removing window and destroying surface "
923                            + mSurfaceHolder.getSurface() + " of: " + this);
924
925                    if (mInputEventReceiver != null) {
926                        mInputEventReceiver.dispose();
927                        mInputEventReceiver = null;
928                    }
929
930                    mSession.remove(mWindow);
931                } catch (RemoteException e) {
932                }
933                mSurfaceHolder.mSurface.release();
934                mCreated = false;
935
936                // Dispose the input channel after removing the window so the Window Manager
937                // doesn't interpret the input channel being closed as an abnormal termination.
938                if (mInputChannel != null) {
939                    mInputChannel.dispose();
940                    mInputChannel = null;
941                }
942            }
943        }
944    }
945
946    class IWallpaperEngineWrapper extends IWallpaperEngine.Stub
947            implements HandlerCaller.Callback {
948        private final HandlerCaller mCaller;
949
950        final IWallpaperConnection mConnection;
951        final IBinder mWindowToken;
952        final int mWindowType;
953        final boolean mIsPreview;
954        int mReqWidth;
955        int mReqHeight;
956
957        Engine mEngine;
958
959        IWallpaperEngineWrapper(WallpaperService context,
960                IWallpaperConnection conn, IBinder windowToken,
961                int windowType, boolean isPreview, int reqWidth, int reqHeight) {
962            if (DEBUG && mCallbackLooper != null) {
963                mCallbackLooper.setMessageLogging(new LogPrinter(Log.VERBOSE, TAG));
964            }
965            mCaller = new HandlerCaller(context,
966                    mCallbackLooper != null
967                            ? mCallbackLooper : context.getMainLooper(),
968                    this);
969            mConnection = conn;
970            mWindowToken = windowToken;
971            mWindowType = windowType;
972            mIsPreview = isPreview;
973            mReqWidth = reqWidth;
974            mReqHeight = reqHeight;
975
976            Message msg = mCaller.obtainMessage(DO_ATTACH);
977            mCaller.sendMessage(msg);
978        }
979
980        public void setDesiredSize(int width, int height) {
981            Message msg = mCaller.obtainMessageII(DO_SET_DESIRED_SIZE, width, height);
982            mCaller.sendMessage(msg);
983        }
984
985        public void setVisibility(boolean visible) {
986            Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED,
987                    visible ? 1 : 0);
988            mCaller.sendMessage(msg);
989        }
990
991        public void dispatchPointer(MotionEvent event) {
992            if (mEngine != null) {
993                mEngine.dispatchPointer(event);
994            } else {
995                event.recycle();
996            }
997        }
998
999        public void dispatchWallpaperCommand(String action, int x, int y,
1000                int z, Bundle extras) {
1001            if (mEngine != null) {
1002                mEngine.mWindow.dispatchWallpaperCommand(action, x, y, z, extras, false);
1003            }
1004        }
1005
1006        public void destroy() {
1007            Message msg = mCaller.obtainMessage(DO_DETACH);
1008            mCaller.sendMessage(msg);
1009        }
1010
1011        public void executeMessage(Message message) {
1012            switch (message.what) {
1013                case DO_ATTACH: {
1014                    try {
1015                        mConnection.attachEngine(this);
1016                    } catch (RemoteException e) {
1017                        Log.w(TAG, "Wallpaper host disappeared", e);
1018                        return;
1019                    }
1020                    Engine engine = onCreateEngine();
1021                    mEngine = engine;
1022                    mActiveEngines.add(engine);
1023                    engine.attach(this);
1024                    return;
1025                }
1026                case DO_DETACH: {
1027                    mActiveEngines.remove(mEngine);
1028                    mEngine.detach();
1029                    return;
1030                }
1031                case DO_SET_DESIRED_SIZE: {
1032                    mEngine.doDesiredSizeChanged(message.arg1, message.arg2);
1033                    return;
1034                }
1035                case MSG_UPDATE_SURFACE:
1036                    mEngine.updateSurface(true, false, false);
1037                    break;
1038                case MSG_VISIBILITY_CHANGED:
1039                    if (DEBUG) Log.v(TAG, "Visibility change in " + mEngine
1040                            + ": " + message.arg1);
1041                    mEngine.doVisibilityChanged(message.arg1 != 0);
1042                    break;
1043                case MSG_WALLPAPER_OFFSETS: {
1044                    mEngine.doOffsetsChanged(true);
1045                } break;
1046                case MSG_WALLPAPER_COMMAND: {
1047                    WallpaperCommand cmd = (WallpaperCommand)message.obj;
1048                    mEngine.doCommand(cmd);
1049                } break;
1050                case MSG_WINDOW_RESIZED: {
1051                    final boolean reportDraw = message.arg1 != 0;
1052                    mEngine.updateSurface(true, false, reportDraw);
1053                    mEngine.doOffsetsChanged(true);
1054                } break;
1055                case MSG_WINDOW_MOVED: {
1056                    // Do nothing. What does it mean for a Wallpaper to move?
1057                } break;
1058                case MSG_TOUCH_EVENT: {
1059                    boolean skip = false;
1060                    MotionEvent ev = (MotionEvent)message.obj;
1061                    if (ev.getAction() == MotionEvent.ACTION_MOVE) {
1062                        synchronized (mEngine.mLock) {
1063                            if (mEngine.mPendingMove == ev) {
1064                                mEngine.mPendingMove = null;
1065                            } else {
1066                                // this is not the motion event we are looking for....
1067                                skip = true;
1068                            }
1069                        }
1070                    }
1071                    if (!skip) {
1072                        if (DEBUG) Log.v(TAG, "Delivering touch event: " + ev);
1073                        mEngine.onTouchEvent(ev);
1074                    }
1075                    ev.recycle();
1076                } break;
1077                default :
1078                    Log.w(TAG, "Unknown message type " + message.what);
1079            }
1080        }
1081    }
1082
1083    /**
1084     * Implements the internal {@link IWallpaperService} interface to convert
1085     * incoming calls to it back to calls on an {@link WallpaperService}.
1086     */
1087    class IWallpaperServiceWrapper extends IWallpaperService.Stub {
1088        private final WallpaperService mTarget;
1089
1090        public IWallpaperServiceWrapper(WallpaperService context) {
1091            mTarget = context;
1092        }
1093
1094        public void attach(IWallpaperConnection conn, IBinder windowToken,
1095                int windowType, boolean isPreview, int reqWidth, int reqHeight) {
1096            new IWallpaperEngineWrapper(mTarget, conn, windowToken,
1097                    windowType, isPreview, reqWidth, reqHeight);
1098        }
1099    }
1100
1101    @Override
1102    public void onCreate() {
1103        super.onCreate();
1104    }
1105
1106    @Override
1107    public void onDestroy() {
1108        super.onDestroy();
1109        for (int i=0; i<mActiveEngines.size(); i++) {
1110            mActiveEngines.get(i).detach();
1111        }
1112        mActiveEngines.clear();
1113    }
1114
1115    /**
1116     * Implement to return the implementation of the internal accessibility
1117     * service interface.  Subclasses should not override.
1118     */
1119    @Override
1120    public final IBinder onBind(Intent intent) {
1121        return new IWallpaperServiceWrapper(this);
1122    }
1123
1124    /**
1125     * This allows subclasses to change the thread that most callbacks
1126     * occur on.  Currently hidden because it is mostly needed for the
1127     * image wallpaper (which runs in the system process and doesn't want
1128     * to get stuck running on that seriously in use main thread).  Not
1129     * exposed right now because the semantics of this are not totally
1130     * well defined and some callbacks can still happen on the main thread).
1131     * @hide
1132     */
1133    public void setCallbackLooper(Looper looper) {
1134        mCallbackLooper = looper;
1135    }
1136
1137    /**
1138     * Must be implemented to return a new instance of the wallpaper's engine.
1139     * Note that multiple instances may be active at the same time, such as
1140     * when the wallpaper is currently set as the active wallpaper and the user
1141     * is in the wallpaper picker viewing a preview of it as well.
1142     */
1143    public abstract Engine onCreateEngine();
1144
1145    @Override
1146    protected void dump(FileDescriptor fd, PrintWriter out, String[] args) {
1147        out.print("State of wallpaper "); out.print(this); out.println(":");
1148        for (int i=0; i<mActiveEngines.size(); i++) {
1149            Engine engine = mActiveEngines.get(i);
1150            out.print("  Engine "); out.print(engine); out.println(":");
1151            engine.dump("    ", fd, out, args);
1152        }
1153    }
1154}
1155