WallpaperService.java revision ba3e31d9eed67291a51b501d12fdc27625af688e
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.Rect;
33import android.os.Bundle;
34import android.os.IBinder;
35import android.os.Looper;
36import android.os.Message;
37import android.os.RemoteException;
38import android.util.Log;
39import android.util.LogPrinter;
40import android.view.Gravity;
41import android.view.IWindowSession;
42import android.view.MotionEvent;
43import android.view.SurfaceHolder;
44import android.view.View;
45import android.view.ViewGroup;
46import android.view.ViewRoot;
47import android.view.WindowManager;
48import android.view.WindowManagerImpl;
49
50import java.util.ArrayList;
51
52/**
53 * A wallpaper service is responsible for showing a live wallpaper behind
54 * applications that would like to sit on top of it.  This service object
55 * itself does very little -- its only purpose is to generate instances of
56 * {@link Engine} as needed.  Implementing a wallpaper thus
57 * involves subclassing from this, subclassing an Engine implementation,
58 * and implementing {@link #onCreateEngine()} to return a new instance of
59 * your engine.
60 */
61public abstract class WallpaperService extends Service {
62    /**
63     * The {@link Intent} that must be declared as handled by the service.
64     * To be supported, the service must also require the
65     * {@link android.Manifest.permission#BIND_WALLPAPER} permission so
66     * that other applications can not abuse it.
67     */
68    @SdkConstant(SdkConstantType.SERVICE_ACTION)
69    public static final String SERVICE_INTERFACE =
70            "android.service.wallpaper.WallpaperService";
71
72    /**
73     * Name under which a WallpaperService component publishes information
74     * about itself.  This meta-data must reference an XML resource containing
75     * a <code>&lt;{@link android.R.styleable#Wallpaper wallpaper}&gt;</code>
76     * tag.
77     */
78    public static final String SERVICE_META_DATA = "android.service.wallpaper";
79
80    static final String TAG = "WallpaperService";
81    static final boolean DEBUG = false;
82
83    private static final int DO_ATTACH = 10;
84    private static final int DO_DETACH = 20;
85    private static final int DO_SET_DESIRED_SIZE = 30;
86
87    private static final int MSG_UPDATE_SURFACE = 10000;
88    private static final int MSG_VISIBILITY_CHANGED = 10010;
89    private static final int MSG_WALLPAPER_OFFSETS = 10020;
90    private static final int MSG_WALLPAPER_COMMAND = 10025;
91    private static final int MSG_WINDOW_RESIZED = 10030;
92    private static final int MSG_TOUCH_EVENT = 10040;
93
94    private Looper mCallbackLooper;
95    private final ArrayList<Engine> mActiveEngines
96            = new ArrayList<Engine>();
97
98    static final class WallpaperCommand {
99        String action;
100        int x;
101        int y;
102        int z;
103        Bundle extras;
104        boolean sync;
105    }
106
107    /**
108     * The actual implementation of a wallpaper.  A wallpaper service may
109     * have multiple instances running (for example as a real wallpaper
110     * and as a preview), each of which is represented by its own Engine
111     * instance.  You must implement {@link WallpaperService#onCreateEngine()}
112     * to return your concrete Engine implementation.
113     */
114    public class Engine {
115        IWallpaperEngineWrapper mIWallpaperEngine;
116
117        // Copies from mIWallpaperEngine.
118        HandlerCaller mCaller;
119        IWallpaperConnection mConnection;
120        IBinder mWindowToken;
121
122        boolean mInitializing = true;
123        boolean mVisible;
124        boolean mScreenOn = true;
125        boolean mReportedVisible;
126        boolean mDestroyed;
127
128        // Current window state.
129        boolean mCreated;
130        boolean mIsCreating;
131        boolean mDrawingAllowed;
132        int mWidth;
133        int mHeight;
134        int mFormat;
135        int mType;
136        int mCurWidth;
137        int mCurHeight;
138        int mWindowFlags = WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE;
139        int mCurWindowFlags = mWindowFlags;
140        boolean mDestroyReportNeeded;
141        final Rect mVisibleInsets = new Rect();
142        final Rect mWinFrame = new Rect();
143        final Rect mContentInsets = new Rect();
144        final Configuration mConfiguration = new Configuration();
145
146        final WindowManager.LayoutParams mLayout
147                = new WindowManager.LayoutParams();
148        IWindowSession mSession;
149
150        final Object mLock = new Object();
151        boolean mOffsetMessageEnqueued;
152        float mPendingXOffset;
153        float mPendingYOffset;
154        float mPendingXOffsetStep;
155        float mPendingYOffsetStep;
156        boolean mPendingSync;
157        MotionEvent mPendingMove;
158
159        final BroadcastReceiver mReceiver = new BroadcastReceiver() {
160            @Override
161            public void onReceive(Context context, Intent intent) {
162                if (Intent.ACTION_SCREEN_ON.equals(intent.getAction())) {
163                    mScreenOn = true;
164                    reportVisibility();
165                } else if (Intent.ACTION_SCREEN_OFF.equals(intent.getAction())) {
166                    mScreenOn = false;
167                    reportVisibility();
168                }
169            }
170        };
171
172        final BaseSurfaceHolder mSurfaceHolder = new BaseSurfaceHolder() {
173
174            @Override
175            public boolean onAllowLockCanvas() {
176                return mDrawingAllowed;
177            }
178
179            @Override
180            public void onRelayoutContainer() {
181                Message msg = mCaller.obtainMessage(MSG_UPDATE_SURFACE);
182                mCaller.sendMessage(msg);
183            }
184
185            @Override
186            public void onUpdateSurface() {
187                Message msg = mCaller.obtainMessage(MSG_UPDATE_SURFACE);
188                mCaller.sendMessage(msg);
189            }
190
191            public boolean isCreating() {
192                return mIsCreating;
193            }
194
195            @Override
196            public void setFixedSize(int width, int height) {
197                throw new UnsupportedOperationException(
198                        "Wallpapers currently only support sizing from layout");
199            }
200
201            public void setKeepScreenOn(boolean screenOn) {
202                throw new UnsupportedOperationException(
203                        "Wallpapers do not support keep screen on");
204            }
205
206        };
207
208        final BaseIWindow mWindow = new BaseIWindow() {
209            @Override
210            public boolean onDispatchPointer(MotionEvent event, long eventTime,
211                    boolean callWhenDone) {
212                synchronized (mLock) {
213                    if (event.getAction() == MotionEvent.ACTION_MOVE) {
214                        if (mPendingMove != null) {
215                            mCaller.removeMessages(MSG_TOUCH_EVENT, mPendingMove);
216                            mPendingMove.recycle();
217                        }
218                        mPendingMove = event;
219                    } else {
220                        mPendingMove = null;
221                    }
222                    Message msg = mCaller.obtainMessageO(MSG_TOUCH_EVENT,
223                            event);
224                    mCaller.sendMessage(msg);
225                }
226                return false;
227            }
228
229            @Override
230            public void resized(int w, int h, Rect coveredInsets,
231                    Rect visibleInsets, boolean reportDraw, Configuration newConfig) {
232                Message msg = mCaller.obtainMessageI(MSG_WINDOW_RESIZED,
233                        reportDraw ? 1 : 0);
234                mCaller.sendMessage(msg);
235            }
236
237            @Override
238            public void dispatchAppVisibility(boolean visible) {
239                // We don't do this in preview mode; we'll let the preview
240                // activity tell us when to run.
241                if (!mIWallpaperEngine.mIsPreview) {
242                    Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED,
243                            visible ? 1 : 0);
244                    mCaller.sendMessage(msg);
245                }
246            }
247
248            @Override
249            public void dispatchWallpaperOffsets(float x, float y, float xStep, float yStep,
250                    boolean sync) {
251                synchronized (mLock) {
252                    if (DEBUG) Log.v(TAG, "Dispatch wallpaper offsets: " + x + ", " + y);
253                    mPendingXOffset = x;
254                    mPendingYOffset = y;
255                    mPendingXOffsetStep = xStep;
256                    mPendingYOffsetStep = yStep;
257                    if (sync) {
258                        mPendingSync = true;
259                    }
260                    if (!mOffsetMessageEnqueued) {
261                        mOffsetMessageEnqueued = true;
262                        Message msg = mCaller.obtainMessage(MSG_WALLPAPER_OFFSETS);
263                        mCaller.sendMessage(msg);
264                    }
265                }
266            }
267
268            public void dispatchWallpaperCommand(String action, int x, int y,
269                    int z, Bundle extras, boolean sync) {
270                synchronized (mLock) {
271                    if (DEBUG) Log.v(TAG, "Dispatch wallpaper command: " + x + ", " + y);
272                    WallpaperCommand cmd = new WallpaperCommand();
273                    cmd.action = action;
274                    cmd.x = x;
275                    cmd.y = y;
276                    cmd.z = z;
277                    cmd.extras = extras;
278                    cmd.sync = sync;
279                    Message msg = mCaller.obtainMessage(MSG_WALLPAPER_COMMAND);
280                    msg.obj = cmd;
281                    mCaller.sendMessage(msg);
282                }
283            }
284        };
285
286        /**
287         * Provides access to the surface in which this wallpaper is drawn.
288         */
289        public SurfaceHolder getSurfaceHolder() {
290            return mSurfaceHolder;
291        }
292
293        /**
294         * Convenience for {@link WallpaperManager#getDesiredMinimumWidth()
295         * WallpaperManager.getDesiredMinimumWidth()}, returning the width
296         * that the system would like this wallpaper to run in.
297         */
298        public int getDesiredMinimumWidth() {
299            return mIWallpaperEngine.mReqWidth;
300        }
301
302        /**
303         * Convenience for {@link WallpaperManager#getDesiredMinimumHeight()
304         * WallpaperManager.getDesiredMinimumHeight()}, returning the height
305         * that the system would like this wallpaper to run in.
306         */
307        public int getDesiredMinimumHeight() {
308            return mIWallpaperEngine.mReqHeight;
309        }
310
311        /**
312         * Return whether the wallpaper is currently visible to the user,
313         * this is the last value supplied to
314         * {@link #onVisibilityChanged(boolean)}.
315         */
316        public boolean isVisible() {
317            return mReportedVisible;
318        }
319
320        /**
321         * Returns true if this engine is running in preview mode -- that is,
322         * it is being shown to the user before they select it as the actual
323         * wallpaper.
324         */
325        public boolean isPreview() {
326            return mIWallpaperEngine.mIsPreview;
327        }
328
329        /**
330         * Control whether this wallpaper will receive raw touch events
331         * from the window manager as the user interacts with the window
332         * that is currently displaying the wallpaper.  By default they
333         * are turned off.  If enabled, the events will be received in
334         * {@link #onTouchEvent(MotionEvent)}.
335         */
336        public void setTouchEventsEnabled(boolean enabled) {
337            mWindowFlags = enabled
338                    ? (mWindowFlags&~WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE)
339                    : (mWindowFlags|WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
340            if (mCreated) {
341                updateSurface(false, false);
342            }
343        }
344
345        /**
346         * Called once to initialize the engine.  After returning, the
347         * engine's surface will be created by the framework.
348         */
349        public void onCreate(SurfaceHolder surfaceHolder) {
350        }
351
352        /**
353         * Called right before the engine is going away.  After this the
354         * surface will be destroyed and this Engine object is no longer
355         * valid.
356         */
357        public void onDestroy() {
358        }
359
360        /**
361         * Called to inform you of the wallpaper becoming visible or
362         * hidden.  <em>It is very important that a wallpaper only use
363         * CPU while it is visible.</em>.
364         */
365        public void onVisibilityChanged(boolean visible) {
366        }
367
368        /**
369         * Called as the user performs touch-screen interaction with the
370         * window that is currently showing this wallpaper.  Note that the
371         * events you receive here are driven by the actual application the
372         * user is interacting with, so if it is slow you will get fewer
373         * move events.
374         */
375        public void onTouchEvent(MotionEvent event) {
376        }
377
378        /**
379         * Called to inform you of the wallpaper's offsets changing
380         * within its contain, corresponding to the container's
381         * call to {@link WallpaperManager#setWallpaperOffsets(IBinder, float, float)
382         * WallpaperManager.setWallpaperOffsets()}.
383         */
384        public void onOffsetsChanged(float xOffset, float yOffset,
385                float xOffsetStep, float yOffsetStep,
386                int xPixelOffset, int yPixelOffset) {
387        }
388
389        /**
390         * Process a command that was sent to the wallpaper with
391         * {@link WallpaperManager#sendWallpaperCommand}.
392         * The default implementation does nothing, and always returns null
393         * as the result.
394         *
395         * @param action The name of the command to perform.  This tells you
396         * what to do and how to interpret the rest of the arguments.
397         * @param x Generic integer parameter.
398         * @param y Generic integer parameter.
399         * @param z Generic integer parameter.
400         * @param extras Any additional parameters.
401         * @param resultRequested If true, the caller is requesting that
402         * a result, appropriate for the command, be returned back.
403         * @return If returning a result, create a Bundle and place the
404         * result data in to it.  Otherwise return null.
405         */
406        public Bundle onCommand(String action, int x, int y, int z,
407                Bundle extras, boolean resultRequested) {
408            return null;
409        }
410
411        /**
412         * Called when an application has changed the desired virtual size of
413         * the wallpaper.
414         */
415        public void onDesiredSizeChanged(int desiredWidth, int desiredHeight) {
416        }
417
418        /**
419         * Convenience for {@link SurfaceHolder.Callback#surfaceChanged
420         * SurfaceHolder.Callback.surfaceChanged()}.
421         */
422        public void onSurfaceChanged(SurfaceHolder holder, int format, int width, int height) {
423        }
424
425        /**
426         * Convenience for {@link SurfaceHolder.Callback#surfaceCreated
427         * SurfaceHolder.Callback.surfaceCreated()}.
428         */
429        public void onSurfaceCreated(SurfaceHolder holder) {
430        }
431
432        /**
433         * Convenience for {@link SurfaceHolder.Callback#surfaceDestroyed
434         * SurfaceHolder.Callback.surfaceDestroyed()}.
435         */
436        public void onSurfaceDestroyed(SurfaceHolder holder) {
437        }
438
439        void updateSurface(boolean forceRelayout, boolean forceReport) {
440            if (mDestroyed) {
441                Log.w(TAG, "Ignoring updateSurface: destroyed");
442            }
443
444            int myWidth = mSurfaceHolder.getRequestedWidth();
445            if (myWidth <= 0) myWidth = ViewGroup.LayoutParams.MATCH_PARENT;
446            int myHeight = mSurfaceHolder.getRequestedHeight();
447            if (myHeight <= 0) myHeight = ViewGroup.LayoutParams.MATCH_PARENT;
448
449            final boolean creating = !mCreated;
450            final boolean formatChanged = mFormat != mSurfaceHolder.getRequestedFormat();
451            boolean sizeChanged = mWidth != myWidth || mHeight != myHeight;
452            final boolean typeChanged = mType != mSurfaceHolder.getRequestedType();
453            final boolean flagsChanged = mCurWindowFlags != mWindowFlags;
454            if (forceRelayout || creating || formatChanged || sizeChanged
455                    || typeChanged || flagsChanged) {
456
457                if (DEBUG) Log.v(TAG, "Changes: creating=" + creating
458                        + " format=" + formatChanged + " size=" + sizeChanged);
459
460                try {
461                    mWidth = myWidth;
462                    mHeight = myHeight;
463                    mFormat = mSurfaceHolder.getRequestedFormat();
464                    mType = mSurfaceHolder.getRequestedType();
465
466                    mLayout.x = 0;
467                    mLayout.y = 0;
468                    mLayout.width = myWidth;
469                    mLayout.height = myHeight;
470
471                    mLayout.format = mFormat;
472
473                    mCurWindowFlags = mWindowFlags;
474                    mLayout.flags = mWindowFlags
475                            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
476                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
477                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
478                            ;
479
480                    mLayout.memoryType = mType;
481                    mLayout.token = mWindowToken;
482
483                    if (!mCreated) {
484                        mLayout.type = mIWallpaperEngine.mWindowType;
485                        mLayout.gravity = Gravity.LEFT|Gravity.TOP;
486                        mLayout.setTitle(WallpaperService.this.getClass().getName());
487                        mLayout.windowAnimations =
488                                com.android.internal.R.style.Animation_Wallpaper;
489                        mSession.add(mWindow, mLayout, View.VISIBLE, mContentInsets);
490                    }
491
492                    mSurfaceHolder.mSurfaceLock.lock();
493                    mDrawingAllowed = true;
494
495                    final int relayoutResult = mSession.relayout(
496                        mWindow, mLayout, mWidth, mHeight,
497                            View.VISIBLE, false, mWinFrame, mContentInsets,
498                            mVisibleInsets, mConfiguration, mSurfaceHolder.mSurface);
499
500                    if (DEBUG) Log.v(TAG, "New surface: " + mSurfaceHolder.mSurface
501                            + ", frame=" + mWinFrame);
502
503                    int w = mWinFrame.width();
504                    if (mCurWidth != w) {
505                        sizeChanged = true;
506                        mCurWidth = w;
507                    }
508                    int h = mWinFrame.height();
509                    if (mCurHeight != h) {
510                        sizeChanged = true;
511                        mCurHeight = h;
512                    }
513
514                    mSurfaceHolder.mSurfaceLock.unlock();
515
516                    try {
517                        mDestroyReportNeeded = true;
518
519                        SurfaceHolder.Callback callbacks[] = null;
520                        synchronized (mSurfaceHolder.mCallbacks) {
521                            final int N = mSurfaceHolder.mCallbacks.size();
522                            if (N > 0) {
523                                callbacks = new SurfaceHolder.Callback[N];
524                                mSurfaceHolder.mCallbacks.toArray(callbacks);
525                            }
526                        }
527
528                        if (!mCreated) {
529                            mIsCreating = true;
530                            if (DEBUG) Log.v(TAG, "onSurfaceCreated("
531                                    + mSurfaceHolder + "): " + this);
532                            onSurfaceCreated(mSurfaceHolder);
533                            if (callbacks != null) {
534                                for (SurfaceHolder.Callback c : callbacks) {
535                                    c.surfaceCreated(mSurfaceHolder);
536                                }
537                            }
538                        }
539                        if (forceReport || creating || formatChanged || sizeChanged) {
540                            if (DEBUG) {
541                                RuntimeException e = new RuntimeException();
542                                e.fillInStackTrace();
543                                Log.w(TAG, "forceReport=" + forceReport + " creating=" + creating
544                                        + " formatChanged=" + formatChanged
545                                        + " sizeChanged=" + sizeChanged, e);
546                            }
547                            if (DEBUG) Log.v(TAG, "onSurfaceChanged("
548                                    + mSurfaceHolder + ", " + mFormat
549                                    + ", " + mCurWidth + ", " + mCurHeight
550                                    + "): " + this);
551                            onSurfaceChanged(mSurfaceHolder, mFormat,
552                                    mCurWidth, mCurHeight);
553                            if (callbacks != null) {
554                                for (SurfaceHolder.Callback c : callbacks) {
555                                    c.surfaceChanged(mSurfaceHolder, mFormat,
556                                            mCurWidth, mCurHeight);
557                                }
558                            }
559                        }
560                    } finally {
561                        mIsCreating = false;
562                        mCreated = true;
563                        if (creating || (relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0) {
564                            mSession.finishDrawing(mWindow);
565                        }
566                    }
567                } catch (RemoteException ex) {
568                }
569                if (DEBUG) Log.v(
570                    TAG, "Layout: x=" + mLayout.x + " y=" + mLayout.y +
571                    " w=" + mLayout.width + " h=" + mLayout.height);
572            }
573        }
574
575        void attach(IWallpaperEngineWrapper wrapper) {
576            if (DEBUG) Log.v(TAG, "attach: " + this + " wrapper=" + wrapper);
577            if (mDestroyed) {
578                return;
579            }
580
581            mIWallpaperEngine = wrapper;
582            mCaller = wrapper.mCaller;
583            mConnection = wrapper.mConnection;
584            mWindowToken = wrapper.mWindowToken;
585            mSurfaceHolder.setSizeFromLayout();
586            mInitializing = true;
587            mSession = ViewRoot.getWindowSession(getMainLooper());
588            mWindow.setSession(mSession);
589
590            IntentFilter filter = new IntentFilter();
591            filter.addAction(Intent.ACTION_SCREEN_ON);
592            filter.addAction(Intent.ACTION_SCREEN_OFF);
593            registerReceiver(mReceiver, filter);
594
595            if (DEBUG) Log.v(TAG, "onCreate(): " + this);
596            onCreate(mSurfaceHolder);
597
598            mInitializing = false;
599            updateSurface(false, false);
600        }
601
602        void doDesiredSizeChanged(int desiredWidth, int desiredHeight) {
603            if (!mDestroyed) {
604                if (DEBUG) Log.v(TAG, "onDesiredSizeChanged("
605                        + desiredWidth + "," + desiredHeight + "): " + this);
606                onDesiredSizeChanged(desiredWidth, desiredHeight);
607            }
608        }
609
610        void doVisibilityChanged(boolean visible) {
611            if (!mDestroyed) {
612                mVisible = visible;
613                reportVisibility();
614            }
615        }
616
617        void reportVisibility() {
618            if (!mDestroyed) {
619                boolean visible = mVisible && mScreenOn;
620                if (mReportedVisible != visible) {
621                    mReportedVisible = visible;
622                    if (DEBUG) Log.v(TAG, "onVisibilityChanged(" + visible
623                            + "): " + this);
624                    onVisibilityChanged(visible);
625                }
626            }
627        }
628
629        void doOffsetsChanged() {
630            if (mDestroyed) {
631                return;
632            }
633
634            float xOffset;
635            float yOffset;
636            float xOffsetStep;
637            float yOffsetStep;
638            boolean sync;
639            synchronized (mLock) {
640                xOffset = mPendingXOffset;
641                yOffset = mPendingYOffset;
642                xOffsetStep = mPendingXOffsetStep;
643                yOffsetStep = mPendingYOffsetStep;
644                sync = mPendingSync;
645                mPendingSync = false;
646                mOffsetMessageEnqueued = false;
647            }
648            if (DEBUG) Log.v(TAG, "Offsets change in " + this
649                    + ": " + xOffset + "," + yOffset);
650            final int availw = mIWallpaperEngine.mReqWidth-mCurWidth;
651            final int xPixels = availw > 0 ? -(int)(availw*xOffset+.5f) : 0;
652            final int availh = mIWallpaperEngine.mReqHeight-mCurHeight;
653            final int yPixels = availh > 0 ? -(int)(availh*yOffset+.5f) : 0;
654            onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixels, yPixels);
655
656            if (sync) {
657                try {
658                    if (DEBUG) Log.v(TAG, "Reporting offsets change complete");
659                    mSession.wallpaperOffsetsComplete(mWindow.asBinder());
660                } catch (RemoteException e) {
661                }
662            }
663        }
664
665        void doCommand(WallpaperCommand cmd) {
666            Bundle result;
667            if (!mDestroyed) {
668                result = onCommand(cmd.action, cmd.x, cmd.y, cmd.z,
669                        cmd.extras, cmd.sync);
670            } else {
671                result = null;
672            }
673            if (cmd.sync) {
674                try {
675                    if (DEBUG) Log.v(TAG, "Reporting command complete");
676                    mSession.wallpaperCommandComplete(mWindow.asBinder(), result);
677                } catch (RemoteException e) {
678                }
679            }
680        }
681
682        void detach() {
683            if (mDestroyed) {
684                return;
685            }
686
687            mDestroyed = true;
688
689            if (mVisible) {
690                mVisible = false;
691                if (DEBUG) Log.v(TAG, "onVisibilityChanged(false): " + this);
692                onVisibilityChanged(false);
693            }
694
695            if (mDestroyReportNeeded) {
696                mDestroyReportNeeded = false;
697                SurfaceHolder.Callback callbacks[];
698                synchronized (mSurfaceHolder.mCallbacks) {
699                    callbacks = new SurfaceHolder.Callback[
700                            mSurfaceHolder.mCallbacks.size()];
701                    mSurfaceHolder.mCallbacks.toArray(callbacks);
702                }
703                for (SurfaceHolder.Callback c : callbacks) {
704                    c.surfaceDestroyed(mSurfaceHolder);
705                }
706                if (DEBUG) Log.v(TAG, "onSurfaceDestroyed("
707                        + mSurfaceHolder + "): " + this);
708                onSurfaceDestroyed(mSurfaceHolder);
709            }
710
711            if (DEBUG) Log.v(TAG, "onDestroy(): " + this);
712            onDestroy();
713
714            unregisterReceiver(mReceiver);
715
716            if (mCreated) {
717                try {
718                    if (DEBUG) Log.v(TAG, "Removing window and destroying surface "
719                            + mSurfaceHolder.getSurface() + " of: " + this);
720                    mSession.remove(mWindow);
721                } catch (RemoteException e) {
722                }
723                mSurfaceHolder.mSurface.release();
724                mCreated = false;
725            }
726        }
727    }
728
729    class IWallpaperEngineWrapper extends IWallpaperEngine.Stub
730            implements HandlerCaller.Callback {
731        private final HandlerCaller mCaller;
732
733        final IWallpaperConnection mConnection;
734        final IBinder mWindowToken;
735        final int mWindowType;
736        final boolean mIsPreview;
737        int mReqWidth;
738        int mReqHeight;
739
740        Engine mEngine;
741
742        IWallpaperEngineWrapper(WallpaperService context,
743                IWallpaperConnection conn, IBinder windowToken,
744                int windowType, boolean isPreview, int reqWidth, int reqHeight) {
745            if (DEBUG && mCallbackLooper != null) {
746                mCallbackLooper.setMessageLogging(new LogPrinter(Log.VERBOSE, TAG));
747            }
748            mCaller = new HandlerCaller(context,
749                    mCallbackLooper != null
750                            ? mCallbackLooper : context.getMainLooper(),
751                    this);
752            mConnection = conn;
753            mWindowToken = windowToken;
754            mWindowType = windowType;
755            mIsPreview = isPreview;
756            mReqWidth = reqWidth;
757            mReqHeight = reqHeight;
758
759            Message msg = mCaller.obtainMessage(DO_ATTACH);
760            mCaller.sendMessage(msg);
761        }
762
763        public void setDesiredSize(int width, int height) {
764            Message msg = mCaller.obtainMessageII(DO_SET_DESIRED_SIZE, width, height);
765            mCaller.sendMessage(msg);
766        }
767
768        public void setVisibility(boolean visible) {
769            Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED,
770                    visible ? 1 : 0);
771            mCaller.sendMessage(msg);
772        }
773
774        public void dispatchPointer(MotionEvent event) {
775            if (mEngine != null) {
776                mEngine.mWindow.onDispatchPointer(event, event.getEventTime(), false);
777            }
778        }
779
780        public void destroy() {
781            Message msg = mCaller.obtainMessage(DO_DETACH);
782            mCaller.sendMessage(msg);
783        }
784
785        public void executeMessage(Message message) {
786            switch (message.what) {
787                case DO_ATTACH: {
788                    try {
789                        mConnection.attachEngine(this);
790                    } catch (RemoteException e) {
791                        Log.w(TAG, "Wallpaper host disappeared", e);
792                        return;
793                    }
794                    Engine engine = onCreateEngine();
795                    mEngine = engine;
796                    mActiveEngines.add(engine);
797                    engine.attach(this);
798                    return;
799                }
800                case DO_DETACH: {
801                    mActiveEngines.remove(mEngine);
802                    mEngine.detach();
803                    return;
804                }
805                case DO_SET_DESIRED_SIZE: {
806                    mEngine.doDesiredSizeChanged(message.arg1, message.arg2);
807                    return;
808                }
809                case MSG_UPDATE_SURFACE:
810                    mEngine.updateSurface(true, false);
811                    break;
812                case MSG_VISIBILITY_CHANGED:
813                    if (DEBUG) Log.v(TAG, "Visibility change in " + mEngine
814                            + ": " + message.arg1);
815                    mEngine.doVisibilityChanged(message.arg1 != 0);
816                    break;
817                case MSG_WALLPAPER_OFFSETS: {
818                    mEngine.doOffsetsChanged();
819                } break;
820                case MSG_WALLPAPER_COMMAND: {
821                    WallpaperCommand cmd = (WallpaperCommand)message.obj;
822                    mEngine.doCommand(cmd);
823                } break;
824                case MSG_WINDOW_RESIZED: {
825                    final boolean reportDraw = message.arg1 != 0;
826                    mEngine.updateSurface(true, false);
827                    mEngine.doOffsetsChanged();
828                    if (reportDraw) {
829                        try {
830                            mEngine.mSession.finishDrawing(mEngine.mWindow);
831                        } catch (RemoteException e) {
832                        }
833                    }
834                } break;
835                case MSG_TOUCH_EVENT: {
836                    MotionEvent ev = (MotionEvent)message.obj;
837                    synchronized (mEngine.mLock) {
838                        if (mEngine.mPendingMove == ev) {
839                            mEngine.mPendingMove = null;
840                        }
841                    }
842                    if (DEBUG) Log.v(TAG, "Delivering touch event: " + ev);
843                    mEngine.onTouchEvent(ev);
844                    ev.recycle();
845                } break;
846                default :
847                    Log.w(TAG, "Unknown message type " + message.what);
848            }
849        }
850    }
851
852    /**
853     * Implements the internal {@link IWallpaperService} interface to convert
854     * incoming calls to it back to calls on an {@link WallpaperService}.
855     */
856    class IWallpaperServiceWrapper extends IWallpaperService.Stub {
857        private final WallpaperService mTarget;
858
859        public IWallpaperServiceWrapper(WallpaperService context) {
860            mTarget = context;
861        }
862
863        public void attach(IWallpaperConnection conn, IBinder windowToken,
864                int windowType, boolean isPreview, int reqWidth, int reqHeight) {
865            new IWallpaperEngineWrapper(mTarget, conn, windowToken,
866                    windowType, isPreview, reqWidth, reqHeight);
867        }
868    }
869
870    @Override
871    public void onCreate() {
872        super.onCreate();
873    }
874
875    @Override
876    public void onDestroy() {
877        super.onDestroy();
878        for (int i=0; i<mActiveEngines.size(); i++) {
879            mActiveEngines.get(i).detach();
880        }
881        mActiveEngines.clear();
882    }
883
884    /**
885     * Implement to return the implementation of the internal accessibility
886     * service interface.  Subclasses should not override.
887     */
888    @Override
889    public final IBinder onBind(Intent intent) {
890        return new IWallpaperServiceWrapper(this);
891    }
892
893    /**
894     * This allows subclasses to change the thread that most callbacks
895     * occur on.  Currently hidden because it is mostly needed for the
896     * image wallpaper (which runs in the system process and doesn't want
897     * to get stuck running on that seriously in use main thread).  Not
898     * exposed right now because the semantics of this are not totally
899     * well defined and some callbacks can still happen on the main thread).
900     * @hide
901     */
902    public void setCallbackLooper(Looper looper) {
903        mCallbackLooper = looper;
904    }
905
906    /**
907     * Must be implemented to return a new instance of the wallpaper's engine.
908     * Note that multiple instances may be active at the same time, such as
909     * when the wallpaper is currently set as the active wallpaper and the user
910     * is in the wallpaper picker viewing a preview of it as well.
911     */
912    public abstract Engine onCreateEngine();
913}
914