WallpaperService.java revision b8f939fb5759fc25fced8df3304d6288b0c25430
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.ViewRoot;
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.RGB_565;
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            synchronized (mLock) {
464                if (event.getAction() == MotionEvent.ACTION_MOVE) {
465                    mPendingMove = event;
466                } else {
467                    mPendingMove = null;
468                }
469            }
470
471            Message msg = mCaller.obtainMessageO(MSG_TOUCH_EVENT, event);
472            mCaller.sendMessage(msg);
473        }
474
475        void updateSurface(boolean forceRelayout, boolean forceReport, boolean redrawNeeded) {
476            if (mDestroyed) {
477                Log.w(TAG, "Ignoring updateSurface: destroyed");
478            }
479
480            int myWidth = mSurfaceHolder.getRequestedWidth();
481            if (myWidth <= 0) myWidth = ViewGroup.LayoutParams.MATCH_PARENT;
482            int myHeight = mSurfaceHolder.getRequestedHeight();
483            if (myHeight <= 0) myHeight = ViewGroup.LayoutParams.MATCH_PARENT;
484
485            final boolean creating = !mCreated;
486            final boolean surfaceCreating = !mSurfaceCreated;
487            final boolean formatChanged = mFormat != mSurfaceHolder.getRequestedFormat();
488            boolean sizeChanged = mWidth != myWidth || mHeight != myHeight;
489            final boolean typeChanged = mType != mSurfaceHolder.getRequestedType();
490            final boolean flagsChanged = mCurWindowFlags != mWindowFlags;
491            if (forceRelayout || creating || surfaceCreating || formatChanged || sizeChanged
492                    || typeChanged || flagsChanged || redrawNeeded) {
493
494                if (DEBUG) Log.v(TAG, "Changes: creating=" + creating
495                        + " format=" + formatChanged + " size=" + sizeChanged);
496
497                try {
498                    mWidth = myWidth;
499                    mHeight = myHeight;
500                    mFormat = mSurfaceHolder.getRequestedFormat();
501                    mType = mSurfaceHolder.getRequestedType();
502
503                    mLayout.x = 0;
504                    mLayout.y = 0;
505                    mLayout.width = myWidth;
506                    mLayout.height = myHeight;
507
508                    mLayout.format = mFormat;
509
510                    mCurWindowFlags = mWindowFlags;
511                    mLayout.flags = mWindowFlags
512                            | WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
513                            | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
514                            | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
515                            ;
516
517                    mLayout.memoryType = mType;
518                    mLayout.token = mWindowToken;
519
520                    if (!mCreated) {
521                        mLayout.type = mIWallpaperEngine.mWindowType;
522                        mLayout.gravity = Gravity.LEFT|Gravity.TOP;
523                        mLayout.setTitle(WallpaperService.this.getClass().getName());
524                        mLayout.windowAnimations =
525                                com.android.internal.R.style.Animation_Wallpaper;
526                        mInputChannel = new InputChannel();
527                        mSession.add(mWindow, mLayout, View.VISIBLE, mContentInsets,
528                                mInputChannel);
529                        mCreated = true;
530
531                        InputQueue.registerInputChannel(mInputChannel, mInputHandler,
532                                Looper.myQueue());
533                    }
534
535                    mSurfaceHolder.mSurfaceLock.lock();
536                    mDrawingAllowed = true;
537
538                    final int relayoutResult = mSession.relayout(
539                        mWindow, mLayout, mWidth, mHeight,
540                            View.VISIBLE, false, mWinFrame, mContentInsets,
541                            mVisibleInsets, mConfiguration, mSurfaceHolder.mSurface);
542
543                    if (DEBUG) Log.v(TAG, "New surface: " + mSurfaceHolder.mSurface
544                            + ", frame=" + mWinFrame);
545
546                    int w = mWinFrame.width();
547                    if (mCurWidth != w) {
548                        sizeChanged = true;
549                        mCurWidth = w;
550                    }
551                    int h = mWinFrame.height();
552                    if (mCurHeight != h) {
553                        sizeChanged = true;
554                        mCurHeight = h;
555                    }
556
557                    mSurfaceHolder.setSurfaceFrameSize(w, h);
558                    mSurfaceHolder.mSurfaceLock.unlock();
559
560                    if (!mSurfaceHolder.mSurface.isValid()) {
561                        reportSurfaceDestroyed();
562                        if (DEBUG) Log.v(TAG, "Layout: Surface destroyed");
563                        return;
564                    }
565
566                    try {
567                        mSurfaceHolder.ungetCallbacks();
568
569                        if (surfaceCreating) {
570                            mIsCreating = true;
571                            if (DEBUG) Log.v(TAG, "onSurfaceCreated("
572                                    + mSurfaceHolder + "): " + this);
573                            onSurfaceCreated(mSurfaceHolder);
574                            SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
575                            if (callbacks != null) {
576                                for (SurfaceHolder.Callback c : callbacks) {
577                                    c.surfaceCreated(mSurfaceHolder);
578                                }
579                            }
580                        }
581
582                        redrawNeeded |= creating
583                                || (relayoutResult&WindowManagerImpl.RELAYOUT_FIRST_TIME) != 0;
584
585                        if (forceReport || creating || surfaceCreating
586                                || formatChanged || sizeChanged) {
587                            if (DEBUG) {
588                                RuntimeException e = new RuntimeException();
589                                e.fillInStackTrace();
590                                Log.w(TAG, "forceReport=" + forceReport + " creating=" + creating
591                                        + " formatChanged=" + formatChanged
592                                        + " sizeChanged=" + sizeChanged, e);
593                            }
594                            if (DEBUG) Log.v(TAG, "onSurfaceChanged("
595                                    + mSurfaceHolder + ", " + mFormat
596                                    + ", " + mCurWidth + ", " + mCurHeight
597                                    + "): " + this);
598                            onSurfaceChanged(mSurfaceHolder, mFormat,
599                                    mCurWidth, mCurHeight);
600                            SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
601                            if (callbacks != null) {
602                                for (SurfaceHolder.Callback c : callbacks) {
603                                    c.surfaceChanged(mSurfaceHolder, mFormat,
604                                            mCurWidth, mCurHeight);
605                                }
606                            }
607                        }
608
609                        if (redrawNeeded) {
610                            onSurfaceRedrawNeeded(mSurfaceHolder);
611                            SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
612                            if (callbacks != null) {
613                                for (SurfaceHolder.Callback c : callbacks) {
614                                    if (c instanceof SurfaceHolder.Callback2) {
615                                        ((SurfaceHolder.Callback2)c).surfaceRedrawNeeded(
616                                                mSurfaceHolder);
617                                    }
618                                }
619                            }
620                        }
621
622                    } finally {
623                        mIsCreating = false;
624                        mSurfaceCreated = true;
625                        if (redrawNeeded) {
626                            mSession.finishDrawing(mWindow);
627                        }
628                    }
629                } catch (RemoteException ex) {
630                }
631                if (DEBUG) Log.v(
632                    TAG, "Layout: x=" + mLayout.x + " y=" + mLayout.y +
633                    " w=" + mLayout.width + " h=" + mLayout.height);
634            }
635        }
636
637        void attach(IWallpaperEngineWrapper wrapper) {
638            if (DEBUG) Log.v(TAG, "attach: " + this + " wrapper=" + wrapper);
639            if (mDestroyed) {
640                return;
641            }
642
643            mIWallpaperEngine = wrapper;
644            mCaller = wrapper.mCaller;
645            mConnection = wrapper.mConnection;
646            mWindowToken = wrapper.mWindowToken;
647            mSurfaceHolder.setSizeFromLayout();
648            mInitializing = true;
649            mSession = ViewRoot.getWindowSession(getMainLooper());
650
651            mWindow.setSession(mSession);
652
653            IntentFilter filter = new IntentFilter();
654            filter.addAction(Intent.ACTION_SCREEN_ON);
655            filter.addAction(Intent.ACTION_SCREEN_OFF);
656            registerReceiver(mReceiver, filter);
657
658            if (DEBUG) Log.v(TAG, "onCreate(): " + this);
659            onCreate(mSurfaceHolder);
660
661            mInitializing = false;
662            updateSurface(false, false, false);
663        }
664
665        void doDesiredSizeChanged(int desiredWidth, int desiredHeight) {
666            if (!mDestroyed) {
667                if (DEBUG) Log.v(TAG, "onDesiredSizeChanged("
668                        + desiredWidth + "," + desiredHeight + "): " + this);
669                mIWallpaperEngine.mReqWidth = desiredWidth;
670                mIWallpaperEngine.mReqHeight = desiredHeight;
671                onDesiredSizeChanged(desiredWidth, desiredHeight);
672                doOffsetsChanged();
673            }
674        }
675
676        void doVisibilityChanged(boolean visible) {
677            if (!mDestroyed) {
678                mVisible = visible;
679                reportVisibility();
680            }
681        }
682
683        void reportVisibility() {
684            if (!mDestroyed) {
685                boolean visible = mVisible && mScreenOn;
686                if (mReportedVisible != visible) {
687                    mReportedVisible = visible;
688                    if (DEBUG) Log.v(TAG, "onVisibilityChanged(" + visible
689                            + "): " + this);
690                    if (visible) {
691                        // If becoming visible, in preview mode the surface
692                        // may have been destroyed so now we need to make
693                        // sure it is re-created.
694                        updateSurface(false, false, false);
695                    }
696                    onVisibilityChanged(visible);
697                }
698            }
699        }
700
701        void doOffsetsChanged() {
702            if (mDestroyed) {
703                return;
704            }
705
706            float xOffset;
707            float yOffset;
708            float xOffsetStep;
709            float yOffsetStep;
710            boolean sync;
711            synchronized (mLock) {
712                xOffset = mPendingXOffset;
713                yOffset = mPendingYOffset;
714                xOffsetStep = mPendingXOffsetStep;
715                yOffsetStep = mPendingYOffsetStep;
716                sync = mPendingSync;
717                mPendingSync = false;
718                mOffsetMessageEnqueued = false;
719            }
720
721            if (mSurfaceCreated) {
722                if (DEBUG) Log.v(TAG, "Offsets change in " + this
723                        + ": " + xOffset + "," + yOffset);
724                final int availw = mIWallpaperEngine.mReqWidth-mCurWidth;
725                final int xPixels = availw > 0 ? -(int)(availw*xOffset+.5f) : 0;
726                final int availh = mIWallpaperEngine.mReqHeight-mCurHeight;
727                final int yPixels = availh > 0 ? -(int)(availh*yOffset+.5f) : 0;
728                onOffsetsChanged(xOffset, yOffset, xOffsetStep, yOffsetStep, xPixels, yPixels);
729            }
730
731            if (sync) {
732                try {
733                    if (DEBUG) Log.v(TAG, "Reporting offsets change complete");
734                    mSession.wallpaperOffsetsComplete(mWindow.asBinder());
735                } catch (RemoteException e) {
736                }
737            }
738        }
739
740        void doCommand(WallpaperCommand cmd) {
741            Bundle result;
742            if (!mDestroyed) {
743                result = onCommand(cmd.action, cmd.x, cmd.y, cmd.z,
744                        cmd.extras, cmd.sync);
745            } else {
746                result = null;
747            }
748            if (cmd.sync) {
749                try {
750                    if (DEBUG) Log.v(TAG, "Reporting command complete");
751                    mSession.wallpaperCommandComplete(mWindow.asBinder(), result);
752                } catch (RemoteException e) {
753                }
754            }
755        }
756
757        void reportSurfaceDestroyed() {
758            if (mSurfaceCreated) {
759                mSurfaceCreated = false;
760                mSurfaceHolder.ungetCallbacks();
761                SurfaceHolder.Callback callbacks[] = mSurfaceHolder.getCallbacks();
762                if (callbacks != null) {
763                    for (SurfaceHolder.Callback c : callbacks) {
764                        c.surfaceDestroyed(mSurfaceHolder);
765                    }
766                }
767                if (DEBUG) Log.v(TAG, "onSurfaceDestroyed("
768                        + mSurfaceHolder + "): " + this);
769                onSurfaceDestroyed(mSurfaceHolder);
770            }
771        }
772
773        void detach() {
774            if (mDestroyed) {
775                return;
776            }
777
778            mDestroyed = true;
779
780            if (mVisible) {
781                mVisible = false;
782                if (DEBUG) Log.v(TAG, "onVisibilityChanged(false): " + this);
783                onVisibilityChanged(false);
784            }
785
786            reportSurfaceDestroyed();
787
788            if (DEBUG) Log.v(TAG, "onDestroy(): " + this);
789            onDestroy();
790
791            unregisterReceiver(mReceiver);
792
793            if (mCreated) {
794                try {
795                    if (DEBUG) Log.v(TAG, "Removing window and destroying surface "
796                            + mSurfaceHolder.getSurface() + " of: " + this);
797
798                    if (mInputChannel != null) {
799                        InputQueue.unregisterInputChannel(mInputChannel);
800                    }
801
802                    mSession.remove(mWindow);
803                } catch (RemoteException e) {
804                }
805                mSurfaceHolder.mSurface.release();
806                mCreated = false;
807
808                // Dispose the input channel after removing the window so the Window Manager
809                // doesn't interpret the input channel being closed as an abnormal termination.
810                if (mInputChannel != null) {
811                    mInputChannel.dispose();
812                    mInputChannel = null;
813                }
814            }
815        }
816    }
817
818    class IWallpaperEngineWrapper extends IWallpaperEngine.Stub
819            implements HandlerCaller.Callback {
820        private final HandlerCaller mCaller;
821
822        final IWallpaperConnection mConnection;
823        final IBinder mWindowToken;
824        final int mWindowType;
825        final boolean mIsPreview;
826        int mReqWidth;
827        int mReqHeight;
828
829        Engine mEngine;
830
831        IWallpaperEngineWrapper(WallpaperService context,
832                IWallpaperConnection conn, IBinder windowToken,
833                int windowType, boolean isPreview, int reqWidth, int reqHeight) {
834            if (DEBUG && mCallbackLooper != null) {
835                mCallbackLooper.setMessageLogging(new LogPrinter(Log.VERBOSE, TAG));
836            }
837            mCaller = new HandlerCaller(context,
838                    mCallbackLooper != null
839                            ? mCallbackLooper : context.getMainLooper(),
840                    this);
841            mConnection = conn;
842            mWindowToken = windowToken;
843            mWindowType = windowType;
844            mIsPreview = isPreview;
845            mReqWidth = reqWidth;
846            mReqHeight = reqHeight;
847
848            Message msg = mCaller.obtainMessage(DO_ATTACH);
849            mCaller.sendMessage(msg);
850        }
851
852        public void setDesiredSize(int width, int height) {
853            Message msg = mCaller.obtainMessageII(DO_SET_DESIRED_SIZE, width, height);
854            mCaller.sendMessage(msg);
855        }
856
857        public void setVisibility(boolean visible) {
858            Message msg = mCaller.obtainMessageI(MSG_VISIBILITY_CHANGED,
859                    visible ? 1 : 0);
860            mCaller.sendMessage(msg);
861        }
862
863        public void dispatchPointer(MotionEvent event) {
864            if (mEngine != null) {
865                mEngine.dispatchPointer(event);
866            }
867        }
868
869        public void dispatchWallpaperCommand(String action, int x, int y,
870                int z, Bundle extras) {
871            if (mEngine != null) {
872                mEngine.mWindow.dispatchWallpaperCommand(action, x, y, z, extras, false);
873            }
874        }
875
876        public void destroy() {
877            Message msg = mCaller.obtainMessage(DO_DETACH);
878            mCaller.sendMessage(msg);
879        }
880
881        public void executeMessage(Message message) {
882            switch (message.what) {
883                case DO_ATTACH: {
884                    try {
885                        mConnection.attachEngine(this);
886                    } catch (RemoteException e) {
887                        Log.w(TAG, "Wallpaper host disappeared", e);
888                        return;
889                    }
890                    Engine engine = onCreateEngine();
891                    mEngine = engine;
892                    mActiveEngines.add(engine);
893                    engine.attach(this);
894                    return;
895                }
896                case DO_DETACH: {
897                    mActiveEngines.remove(mEngine);
898                    mEngine.detach();
899                    return;
900                }
901                case DO_SET_DESIRED_SIZE: {
902                    mEngine.doDesiredSizeChanged(message.arg1, message.arg2);
903                    return;
904                }
905                case MSG_UPDATE_SURFACE:
906                    mEngine.updateSurface(true, false, false);
907                    break;
908                case MSG_VISIBILITY_CHANGED:
909                    if (DEBUG) Log.v(TAG, "Visibility change in " + mEngine
910                            + ": " + message.arg1);
911                    mEngine.doVisibilityChanged(message.arg1 != 0);
912                    break;
913                case MSG_WALLPAPER_OFFSETS: {
914                    mEngine.doOffsetsChanged();
915                } break;
916                case MSG_WALLPAPER_COMMAND: {
917                    WallpaperCommand cmd = (WallpaperCommand)message.obj;
918                    mEngine.doCommand(cmd);
919                } break;
920                case MSG_WINDOW_RESIZED: {
921                    final boolean reportDraw = message.arg1 != 0;
922                    mEngine.updateSurface(true, false, reportDraw);
923                    mEngine.doOffsetsChanged();
924                } break;
925                case MSG_TOUCH_EVENT: {
926                    boolean skip = false;
927                    MotionEvent ev = (MotionEvent)message.obj;
928                    if (ev.getAction() == MotionEvent.ACTION_MOVE) {
929                        synchronized (mEngine.mLock) {
930                            if (mEngine.mPendingMove == ev) {
931                                mEngine.mPendingMove = null;
932                            } else {
933                                // this is not the motion event we are looking for....
934                                skip = true;
935                            }
936                        }
937                    }
938                    if (!skip) {
939                        if (DEBUG) Log.v(TAG, "Delivering touch event: " + ev);
940                        mEngine.onTouchEvent(ev);
941                    }
942                    ev.recycle();
943                } break;
944                default :
945                    Log.w(TAG, "Unknown message type " + message.what);
946            }
947        }
948    }
949
950    /**
951     * Implements the internal {@link IWallpaperService} interface to convert
952     * incoming calls to it back to calls on an {@link WallpaperService}.
953     */
954    class IWallpaperServiceWrapper extends IWallpaperService.Stub {
955        private final WallpaperService mTarget;
956
957        public IWallpaperServiceWrapper(WallpaperService context) {
958            mTarget = context;
959        }
960
961        public void attach(IWallpaperConnection conn, IBinder windowToken,
962                int windowType, boolean isPreview, int reqWidth, int reqHeight) {
963            new IWallpaperEngineWrapper(mTarget, conn, windowToken,
964                    windowType, isPreview, reqWidth, reqHeight);
965        }
966    }
967
968    @Override
969    public void onCreate() {
970        super.onCreate();
971    }
972
973    @Override
974    public void onDestroy() {
975        super.onDestroy();
976        for (int i=0; i<mActiveEngines.size(); i++) {
977            mActiveEngines.get(i).detach();
978        }
979        mActiveEngines.clear();
980    }
981
982    /**
983     * Implement to return the implementation of the internal accessibility
984     * service interface.  Subclasses should not override.
985     */
986    @Override
987    public final IBinder onBind(Intent intent) {
988        return new IWallpaperServiceWrapper(this);
989    }
990
991    /**
992     * This allows subclasses to change the thread that most callbacks
993     * occur on.  Currently hidden because it is mostly needed for the
994     * image wallpaper (which runs in the system process and doesn't want
995     * to get stuck running on that seriously in use main thread).  Not
996     * exposed right now because the semantics of this are not totally
997     * well defined and some callbacks can still happen on the main thread).
998     * @hide
999     */
1000    public void setCallbackLooper(Looper looper) {
1001        mCallbackLooper = looper;
1002    }
1003
1004    /**
1005     * Must be implemented to return a new instance of the wallpaper's engine.
1006     * Note that multiple instances may be active at the same time, such as
1007     * when the wallpaper is currently set as the active wallpaper and the user
1008     * is in the wallpaper picker viewing a preview of it as well.
1009     */
1010    public abstract Engine onCreateEngine();
1011}
1012