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