RenderAction.java revision f2d408b51debadca830eefbf8131185ac55ce699
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 com.android.ide.common.rendering.api.HardwareConfig;
20import com.android.ide.common.rendering.api.LayoutLog;
21import com.android.ide.common.rendering.api.RenderParams;
22import com.android.ide.common.rendering.api.RenderResources;
23import com.android.ide.common.rendering.api.RenderResources.FrameworkResourceIdProvider;
24import com.android.ide.common.rendering.api.Result;
25import com.android.layoutlib.bridge.Bridge;
26import com.android.layoutlib.bridge.android.BridgeContext;
27import com.android.resources.Density;
28import com.android.resources.ResourceType;
29import com.android.resources.ScreenOrientation;
30import com.android.resources.ScreenSize;
31
32import android.content.res.Configuration;
33import android.os.HandlerThread_Delegate;
34import android.util.DisplayMetrics;
35import android.view.ViewConfiguration_Accessor;
36import android.view.inputmethod.InputMethodManager;
37import android.view.inputmethod.InputMethodManager_Accessor;
38
39import java.util.concurrent.TimeUnit;
40import java.util.concurrent.locks.ReentrantLock;
41
42import static com.android.ide.common.rendering.api.Result.Status.ERROR_LOCK_INTERRUPTED;
43import static com.android.ide.common.rendering.api.Result.Status.ERROR_TIMEOUT;
44import static com.android.ide.common.rendering.api.Result.Status.SUCCESS;
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(long)}, 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        // setup the ParserFactory
103        ParserFactory.setParserFactory(mParams.getLayoutlibCallback().getParserFactory());
104
105        HardwareConfig hardwareConfig = mParams.getHardwareConfig();
106
107        // setup the display Metrics.
108        DisplayMetrics metrics = new DisplayMetrics();
109        metrics.densityDpi = metrics.noncompatDensityDpi =
110                hardwareConfig.getDensity().getDpiValue();
111
112        metrics.density = metrics.noncompatDensity =
113                metrics.densityDpi / (float) DisplayMetrics.DENSITY_DEFAULT;
114
115        metrics.scaledDensity = metrics.noncompatScaledDensity = metrics.density;
116
117        metrics.widthPixels = metrics.noncompatWidthPixels = hardwareConfig.getScreenWidth();
118        metrics.heightPixels = metrics.noncompatHeightPixels = hardwareConfig.getScreenHeight();
119        metrics.xdpi = metrics.noncompatXdpi = hardwareConfig.getXdpi();
120        metrics.ydpi = metrics.noncompatYdpi = hardwareConfig.getYdpi();
121
122        RenderResources resources = mParams.getResources();
123
124        // build the context
125        mContext = new BridgeContext(mParams.getProjectKey(), metrics, resources,
126                mParams.getAssets(), mParams.getLayoutlibCallback(), getConfiguration(),
127                mParams.getTargetSdkVersion(), mParams.isRtlSupported());
128
129        setUp();
130
131        return SUCCESS.createResult();
132    }
133
134
135    /**
136     * Prepares the scene for action.
137     * <p>
138     * This call is blocking if another rendering/inflating is currently happening, and will return
139     * whether the preparation worked.
140     *
141     * The preparation can fail if another rendering took too long and the timeout was elapsed.
142     *
143     * More than one call to this from the same thread will have no effect and will return
144     * {@link Result.Status#SUCCESS}.
145     *
146     * After scene actions have taken place, only one call to {@link #release()} must be
147     * done.
148     *
149     * @param timeout the time to wait if another rendering is happening.
150     *
151     * @return whether the scene was prepared
152     *
153     * @see #release()
154     *
155     * @throws IllegalStateException if {@link #init(long)} was never called.
156     */
157    public Result acquire(long timeout) {
158        if (mContext == null) {
159            throw new IllegalStateException("After scene creation, #init() must be called");
160        }
161
162        // acquire the lock. if the result is null, lock was just acquired, otherwise, return
163        // the result.
164        Result result = acquireLock(timeout);
165        if (result != null) {
166            return result;
167        }
168
169        setUp();
170
171        return SUCCESS.createResult();
172    }
173
174    /**
175     * Acquire the lock so that the scene can be acted upon.
176     * <p>
177     * This returns null if the lock was just acquired, otherwise it returns
178     * {@link Result.Status#SUCCESS} if the lock already belonged to that thread, or another
179     * instance (see {@link Result#getStatus()}) if an error occurred.
180     *
181     * @param timeout the time to wait if another rendering is happening.
182     * @return null if the lock was just acquire or another result depending on the state.
183     *
184     * @throws IllegalStateException if the current context is different than the one owned by
185     *      the scene.
186     */
187    private Result acquireLock(long timeout) {
188        ReentrantLock lock = Bridge.getLock();
189        if (!lock.isHeldByCurrentThread()) {
190            try {
191                boolean acquired = lock.tryLock(timeout, TimeUnit.MILLISECONDS);
192
193                if (!acquired) {
194                    return ERROR_TIMEOUT.createResult();
195                }
196            } catch (InterruptedException e) {
197                return ERROR_LOCK_INTERRUPTED.createResult();
198            }
199        } else {
200            // This thread holds the lock already. Checks that this wasn't for a different context.
201            // If this is called by init, mContext will be null and so should sCurrentContext
202            // anyway
203            if (mContext != sCurrentContext) {
204                throw new IllegalStateException("Acquiring different scenes from same thread without releases");
205            }
206            return SUCCESS.createResult();
207        }
208
209        return null;
210    }
211
212    /**
213     * Cleans up the scene after an action.
214     */
215    public void release() {
216        ReentrantLock lock = Bridge.getLock();
217
218        // with the use of finally blocks, it is possible to find ourself calling this
219        // without a successful call to prepareScene. This test makes sure that unlock() will
220        // not throw IllegalMonitorStateException.
221        if (lock.isHeldByCurrentThread()) {
222            tearDown();
223            lock.unlock();
224        }
225    }
226
227    /**
228     * Sets up the session for rendering.
229     * <p/>
230     * The counterpart is {@link #tearDown()}.
231     */
232    private void setUp() {
233        // make sure the Resources object references the context (and other objects) for this
234        // scene
235        mContext.initResources();
236        sCurrentContext = mContext;
237
238        // create an InputMethodManager
239        InputMethodManager.getInstance();
240
241        LayoutLog currentLog = mParams.getLog();
242        Bridge.setLog(currentLog);
243        mContext.getRenderResources().setFrameworkResourceIdProvider(this);
244        mContext.getRenderResources().setLogger(currentLog);
245    }
246
247    /**
248     * Tear down the session after rendering.
249     * <p/>
250     * The counterpart is {@link #setUp()}.
251     */
252    private void tearDown() {
253        // The context may be null, if there was an error during init().
254        if (mContext != null) {
255            // Make sure to remove static references, otherwise we could not unload the lib
256            mContext.disposeResources();
257        }
258
259        if (sCurrentContext != null) {
260            // quit HandlerThread created during this session.
261            HandlerThread_Delegate.cleanUp(sCurrentContext);
262        }
263
264        // clear the stored ViewConfiguration since the map is per density and not per context.
265        ViewConfiguration_Accessor.clearConfigurations();
266
267        // remove the InputMethodManager
268        InputMethodManager_Accessor.resetInstance();
269
270        sCurrentContext = null;
271
272        Bridge.setLog(null);
273        if (mContext != null) {
274            mContext.getRenderResources().setFrameworkResourceIdProvider(null);
275            mContext.getRenderResources().setLogger(null);
276        }
277        ParserFactory.setParserFactory(null);
278
279    }
280
281    public static BridgeContext getCurrentContext() {
282        return sCurrentContext;
283    }
284
285    protected T getParams() {
286        return mParams;
287    }
288
289    protected BridgeContext getContext() {
290        return mContext;
291    }
292
293    /**
294     * Returns the log associated with the session.
295     * @return the log or null if there are none.
296     */
297    public LayoutLog getLog() {
298        if (mParams != null) {
299            return mParams.getLog();
300        }
301
302        return null;
303    }
304
305    /**
306     * Checks that the lock is owned by the current thread and that the current context is the one
307     * from this scene.
308     *
309     * @throws IllegalStateException if the current context is different than the one owned by
310     *      the scene, or if {@link #acquire(long)} was not called.
311     */
312    protected void checkLock() {
313        ReentrantLock lock = Bridge.getLock();
314        if (!lock.isHeldByCurrentThread()) {
315            throw new IllegalStateException("scene must be acquired first. see #acquire(long)");
316        }
317        if (sCurrentContext != mContext) {
318            throw new IllegalStateException("Thread acquired a scene but is rendering a different one");
319        }
320    }
321
322    private Configuration getConfiguration() {
323        Configuration config = new Configuration();
324
325        HardwareConfig hardwareConfig = mParams.getHardwareConfig();
326
327        ScreenSize screenSize = hardwareConfig.getScreenSize();
328        if (screenSize != null) {
329            switch (screenSize) {
330                case SMALL:
331                    config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_SMALL;
332                    break;
333                case NORMAL:
334                    config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_NORMAL;
335                    break;
336                case LARGE:
337                    config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_LARGE;
338                    break;
339                case XLARGE:
340                    config.screenLayout |= Configuration.SCREENLAYOUT_SIZE_XLARGE;
341                    break;
342            }
343        }
344
345        Density density = hardwareConfig.getDensity();
346        if (density == null) {
347            density = Density.MEDIUM;
348        }
349
350        config.screenWidthDp = hardwareConfig.getScreenWidth() / density.getDpiValue();
351        config.screenHeightDp = hardwareConfig.getScreenHeight() / density.getDpiValue();
352        if (config.screenHeightDp < config.screenWidthDp) {
353            //noinspection SuspiciousNameCombination
354            config.smallestScreenWidthDp = config.screenHeightDp;
355        } else {
356            config.smallestScreenWidthDp = config.screenWidthDp;
357        }
358        config.densityDpi = density.getDpiValue();
359
360        // never run in compat mode:
361        config.compatScreenWidthDp = config.screenWidthDp;
362        config.compatScreenHeightDp = config.screenHeightDp;
363
364        ScreenOrientation orientation = hardwareConfig.getOrientation();
365        if (orientation != null) {
366            switch (orientation) {
367            case PORTRAIT:
368                config.orientation = Configuration.ORIENTATION_PORTRAIT;
369                break;
370            case LANDSCAPE:
371                config.orientation = Configuration.ORIENTATION_LANDSCAPE;
372                break;
373            case SQUARE:
374                //noinspection deprecation
375                config.orientation = Configuration.ORIENTATION_SQUARE;
376                break;
377            }
378        } else {
379            config.orientation = Configuration.ORIENTATION_UNDEFINED;
380        }
381
382        // TODO: fill in more config info.
383
384        return config;
385    }
386
387
388    // --- FrameworkResourceIdProvider methods
389
390    @Override
391    public Integer getId(ResourceType resType, String resName) {
392        return Bridge.getResourceId(resType, resName);
393    }
394}
395