1/*
2 * Copyright (C) 2010 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 com.android.layoutlib.bridge.impl;
18
19import static com.android.ide.common.rendering.api.Result.Status.ERROR_LOCK_INTERRUPTED;
20import static com.android.ide.common.rendering.api.Result.Status.ERROR_TIMEOUT;
21import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
22
23import com.android.ide.common.rendering.api.HardwareConfig;
24import com.android.ide.common.rendering.api.LayoutLog;
25import com.android.ide.common.rendering.api.RenderParams;
26import com.android.ide.common.rendering.api.RenderResources;
27import com.android.ide.common.rendering.api.RenderResources.FrameworkResourceIdProvider;
28import com.android.ide.common.rendering.api.Result;
29import com.android.layoutlib.bridge.Bridge;
30import com.android.layoutlib.bridge.android.BridgeContext;
31import com.android.resources.Density;
32import com.android.resources.ResourceType;
33import com.android.resources.ScreenSize;
34
35import android.content.res.Configuration;
36import android.os.HandlerThread_Delegate;
37import android.os.Looper;
38import android.util.DisplayMetrics;
39import android.view.ViewConfiguration_Accessor;
40import android.view.inputmethod.InputMethodManager;
41import android.view.inputmethod.InputMethodManager_Accessor;
42
43import java.util.concurrent.TimeUnit;
44import java.util.concurrent.locks.ReentrantLock;
45
46/**
47 * Base class for rendering action.
48 *
49 * It provides life-cycle methods to init and stop the rendering.
50 * The most important methods are:
51 * {@link #init(long)} and {@link #acquire(long)} to start a rendering and {@link #release()}
52 * after the rendering.
53 *
54 *
55 * @param <T> the {@link RenderParams} implementation
56 *
57 */
58public abstract class RenderAction<T extends RenderParams> extends FrameworkResourceIdProvider {
59
60    /**
61     * The current context being rendered. This is set through {@link #acquire(long)} and
62     * {@link #init(long)}, and unset in {@link #release()}.
63     */
64    private static BridgeContext sCurrentContext = null;
65
66    private final T mParams;
67
68    private BridgeContext mContext;
69
70    /**
71     * Creates a renderAction.
72     * <p>
73     * This <b>must</b> be followed by a call to {@link RenderAction#init()}, which act as a
74     * call to {@link RenderAction#acquire(long)}
75     *
76     * @param params the RenderParams. This must be a copy that the action can keep
77     *
78     */
79    protected RenderAction(T params) {
80        mParams = params;
81    }
82
83    /**
84     * Initializes and acquires the scene, creating various Android objects such as context,
85     * inflater, and parser.
86     *
87     * @param timeout the time to wait if another rendering is happening.
88     *
89     * @return whether the scene was prepared
90     *
91     * @see #acquire(long)
92     * @see #release()
93     */
94    public Result init(long timeout) {
95        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
96        // the result.
97        Result result = acquireLock(timeout);
98        if (result != null) {
99            return result;
100        }
101
102        HardwareConfig hardwareConfig = mParams.getHardwareConfig();
103
104        // setup the display Metrics.
105        DisplayMetrics metrics = new DisplayMetrics();
106        metrics.densityDpi = metrics.noncompatDensityDpi =
107                hardwareConfig.getDensity().getDpiValue();
108
109        metrics.density = metrics.noncompatDensity =
110                metrics.densityDpi / (float) DisplayMetrics.DENSITY_DEFAULT;
111
112        metrics.scaledDensity = metrics.noncompatScaledDensity = metrics.density;
113
114        metrics.widthPixels = metrics.noncompatWidthPixels = hardwareConfig.getScreenWidth();
115        metrics.heightPixels = metrics.noncompatHeightPixels = hardwareConfig.getScreenHeight();
116        metrics.xdpi = metrics.noncompatXdpi = hardwareConfig.getXdpi();
117        metrics.ydpi = metrics.noncompatYdpi = hardwareConfig.getYdpi();
118
119        RenderResources resources = mParams.getResources();
120
121        // build the context
122        mContext = new BridgeContext(mParams.getProjectKey(), metrics, resources,
123                mParams.getProjectCallback(), getConfiguration(), mParams.getTargetSdkVersion());
124
125        setUp();
126
127        return SUCCESS.createResult();
128    }
129
130
131    /**
132     * Prepares the scene for action.
133     * <p>
134     * This call is blocking if another rendering/inflating is currently happening, and will return
135     * whether the preparation worked.
136     *
137     * The preparation can fail if another rendering took too long and the timeout was elapsed.
138     *
139     * More than one call to this from the same thread will have no effect and will return
140     * {@link Result#SUCCESS}.
141     *
142     * After scene actions have taken place, only one call to {@link #release()} must be
143     * done.
144     *
145     * @param timeout the time to wait if another rendering is happening.
146     *
147     * @return whether the scene was prepared
148     *
149     * @see #release()
150     *
151     * @throws IllegalStateException if {@link #init(long)} was never called.
152     */
153    public Result acquire(long timeout) {
154        if (mContext == null) {
155            throw new IllegalStateException("After scene creation, #init() must be called");
156        }
157
158        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
159        // the result.
160        Result result = acquireLock(timeout);
161        if (result != null) {
162            return result;
163        }
164
165        setUp();
166
167        return SUCCESS.createResult();
168    }
169
170    /**
171     * Acquire the lock so that the scene can be acted upon.
172     * <p>
173     * This returns null if the lock was just acquired, otherwise it returns
174     * {@link Result#SUCCESS} if the lock already belonged to that thread, or another
175     * instance (see {@link Result#getStatus()}) if an error occurred.
176     *
177     * @param timeout the time to wait if another rendering is happening.
178     * @return null if the lock was just acquire or another result depending on the state.
179     *
180     * @throws IllegalStateException if the current context is different than the one owned by
181     *      the scene.
182     */
183    private Result acquireLock(long timeout) {
184        ReentrantLock lock = Bridge.getLock();
185        if (lock.isHeldByCurrentThread() == false) {
186            try {
187                boolean acquired = lock.tryLock(timeout, TimeUnit.MILLISECONDS);
188
189                if (acquired == false) {
190                    return ERROR_TIMEOUT.createResult();
191                }
192            } catch (InterruptedException e) {
193                return ERROR_LOCK_INTERRUPTED.createResult();
194            }
195        } else {
196            // This thread holds the lock already. Checks that this wasn't for a different context.
197            // If this is called by init, mContext will be null and so should sCurrentContext
198            // anyway
199            if (mContext != sCurrentContext) {
200                throw new IllegalStateException("Acquiring different scenes from same thread without releases");
201            }
202            return SUCCESS.createResult();
203        }
204
205        return null;
206    }
207
208    /**
209     * Cleans up the scene after an action.
210     */
211    public void release() {
212        ReentrantLock lock = Bridge.getLock();
213
214        // with the use of finally blocks, it is possible to find ourself calling this
215        // without a successful call to prepareScene. This test makes sure that unlock() will
216        // not throw IllegalMonitorStateException.
217        if (lock.isHeldByCurrentThread()) {
218            tearDown();
219            lock.unlock();
220        }
221    }
222
223    /**
224     * Sets up the session for rendering.
225     * <p/>
226     * The counterpart is {@link #tearDown()}.
227     */
228    private void setUp() {
229        // make sure the Resources object references the context (and other objects) for this
230        // scene
231        mContext.initResources();
232        sCurrentContext = mContext;
233
234        // create an InputMethodManager
235        InputMethodManager.getInstance(Looper.myLooper());
236
237        LayoutLog currentLog = mParams.getLog();
238        Bridge.setLog(currentLog);
239        mContext.getRenderResources().setFrameworkResourceIdProvider(this);
240        mContext.getRenderResources().setLogger(currentLog);
241    }
242
243    /**
244     * Tear down the session after rendering.
245     * <p/>
246     * The counterpart is {@link #setUp()}.
247     */
248    private void tearDown() {
249        // Make sure to remove static references, otherwise we could not unload the lib
250        mContext.disposeResources();
251
252        // quit HandlerThread created during this session.
253        HandlerThread_Delegate.cleanUp(sCurrentContext);
254
255        // clear the stored ViewConfiguration since the map is per density and not per context.
256        ViewConfiguration_Accessor.clearConfigurations();
257
258        // remove the InputMethodManager
259        InputMethodManager_Accessor.resetInstance();
260
261        sCurrentContext = null;
262
263        Bridge.setLog(null);
264        mContext.getRenderResources().setFrameworkResourceIdProvider(null);
265        mContext.getRenderResources().setLogger(null);
266    }
267
268    public static BridgeContext getCurrentContext() {
269        return sCurrentContext;
270    }
271
272    protected T getParams() {
273        return mParams;
274    }
275
276    protected BridgeContext getContext() {
277        return mContext;
278    }
279
280    /**
281     * Returns the log associated with the session.
282     * @return the log or null if there are none.
283     */
284    public LayoutLog getLog() {
285        if (mParams != null) {
286            return mParams.getLog();
287        }
288
289        return null;
290    }
291
292    /**
293     * Checks that the lock is owned by the current thread and that the current context is the one
294     * from this scene.
295     *
296     * @throws IllegalStateException if the current context is different than the one owned by
297     *      the scene, or if {@link #acquire(long)} was not called.
298     */
299    protected void checkLock() {
300        ReentrantLock lock = Bridge.getLock();
301        if (lock.isHeldByCurrentThread() == false) {
302            throw new IllegalStateException("scene must be acquired first. see #acquire(long)");
303        }
304        if (sCurrentContext != mContext) {
305            throw new IllegalStateException("Thread acquired a scene but is rendering a different one");
306        }
307    }
308
309    private Configuration getConfiguration() {
310        Configuration config = new Configuration();
311
312        HardwareConfig hardwareConfig = mParams.getHardwareConfig();
313
314        ScreenSize screenSize = hardwareConfig.getScreenSize();
315        if (screenSize != null) {
316            switch (screenSize) {
317                case SMALL:
318                    config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_SMALL;
319                    break;
320                case NORMAL:
321                    config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_NORMAL;
322                    break;
323                case LARGE:
324                    config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_LARGE;
325                    break;
326                case XLARGE:
327                    config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_XLARGE;
328                    break;
329            }
330        }
331
332        Density density = hardwareConfig.getDensity();
333        if (density == null) {
334            density = Density.MEDIUM;
335        }
336
337        config.screenWidthDp = hardwareConfig.getScreenWidth() / density.getDpiValue();
338        config.screenHeightDp = hardwareConfig.getScreenHeight() / density.getDpiValue();
339        if (config.screenHeightDp < config.screenWidthDp) {
340            config.smallestScreenWidthDp = config.screenHeightDp;
341        } else {
342            config.smallestScreenWidthDp = config.screenWidthDp;
343        }
344        config.densityDpi = density.getDpiValue();
345
346        // never run in compat mode:
347        config.compatScreenWidthDp = config.screenWidthDp;
348        config.compatScreenHeightDp = config.screenHeightDp;
349
350        // TODO: fill in more config info.
351
352        return config;
353    }
354
355
356    // --- FrameworkResourceIdProvider methods
357
358    @Override
359    public Integer getId(ResourceType resType, String resName) {
360        return Bridge.getResourceId(resType, resName);
361    }
362}
363