aboutsummaryrefslogtreecommitdiffstats
path: root/layoutlib_api/sample/src/com/example/android/render/RenderService.java
blob: 33ed35fc97e4a8b21b73801966cd58ba08896964 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
/*
 * Copyright (C) 2011 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.android.render;

import com.android.ide.common.rendering.LayoutLibrary;
import com.android.ide.common.rendering.api.DrawableParams;
import com.android.ide.common.rendering.api.IImageFactory;
import com.android.ide.common.rendering.api.ILayoutPullParser;
import com.android.ide.common.rendering.api.IProjectCallback;
import com.android.ide.common.rendering.api.LayoutLog;
import com.android.ide.common.rendering.api.RenderSession;
import com.android.ide.common.rendering.api.ResourceValue;
import com.android.ide.common.rendering.api.Result;
import com.android.ide.common.rendering.api.SessionParams;
import com.android.ide.common.rendering.api.SessionParams.RenderingMode;
import com.android.ide.common.resources.ResourceResolver;
import com.android.ide.common.resources.configuration.FolderConfiguration;
import com.android.resources.ResourceType;
import com.android.resources.ScreenOrientation;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;


/**
 * The {@link RenderService} provides rendering service and easy config.
 */
public class RenderService {

    // The following fields are set through the constructor and are required.

    private final IProjectCallback mProjectCallback;
    private final ResourceResolver mResourceResolver;
    private final LayoutLibrary mLayoutLib;
    private final FolderConfiguration mConfig;

    // The following fields are optional or configurable using the various chained
    // setters:

    private int mWidth;
    private int mHeight;
    private int mMinSdkVersion = -1;
    private int mTargetSdkVersion = -1;
    private float mXdpi = -1;
    private float mYdpi = -1;
    private RenderingMode mRenderingMode = RenderingMode.NORMAL;
    private LayoutLog mLogger;
    private Integer mOverrideBgColor;
    private boolean mShowDecorations = true;
    private String mAppLabel;
    private String mAppIconName;
    private IImageFactory mImageFactory;

    /** Use the {@link RenderServiceFactory#create} factory instead */
    RenderService(LayoutLibrary layoutLibrary,
            ResourceResolver resources,
            FolderConfiguration config,
            IProjectCallback projectCallback) {
        mLayoutLib = layoutLibrary;
        mResourceResolver = resources;
        mConfig = config;
        mProjectCallback = projectCallback;
    }

    /**
     * Sets the {@link LayoutLog} to be used during rendering. If none is specified, a
     * silent logger will be used.
     *
     * @param logger the log to be used
     * @return this (such that chains of setters can be stringed together)
     */
    public RenderService setLog(LayoutLog logger) {
        mLogger = logger;
        return this;
    }

    /**
     * Sets the {@link RenderingMode} to be used during rendering. If none is specified,
     * the default is {@link RenderingMode#NORMAL}.
     *
     * @param renderingMode the rendering mode to be used
     * @return this (such that chains of setters can be stringed together)
     */
    public RenderService setRenderingMode(RenderingMode renderingMode) {
        mRenderingMode = renderingMode;
        return this;
    }

    /**
     * Sets the overriding background color to be used, if any. The color should be a
     * bitmask of AARRGGBB. The default is null.
     *
     * @param overrideBgColor the overriding background color to be used in the rendering,
     *            in the form of a AARRGGBB bitmask, or null to use no custom background.
     * @return this (such that chains of setters can be stringed together)
     */
    public RenderService setOverrideBgColor(Integer overrideBgColor) {
        mOverrideBgColor = overrideBgColor;
        return this;
    }

    /**
     * Sets whether the rendering should include decorations such as a system bar, an
     * application bar etc depending on the SDK target and theme. The default is true.
     *
     * @param showDecorations true if the rendering should include system bars etc.
     * @return this (such that chains of setters can be stringed together)
     */
    public RenderService setDecorations(boolean showDecorations) {
        mShowDecorations = showDecorations;
        return this;
    }

    public RenderService setAppInfo(String label, String icon) {
        mAppLabel = label;
        mAppIconName = icon;
        return this;
    }

    public RenderService setMinSdkVersion(int minSdkVersion) {
        mMinSdkVersion = minSdkVersion;
        return this;
    }

    public RenderService setTargetSdkVersion(int targetSdkVersion) {
        mTargetSdkVersion = targetSdkVersion;
        return this;
    }

    public RenderService setExactDeviceDpi(float xdpi, float ydpi) {
        mXdpi = xdpi;
        mYdpi = ydpi;
        return this;
    }

    public RenderService setImageFactory(IImageFactory imageFactory) {
        mImageFactory = imageFactory;
        return this;
    }

    /** Initializes any remaining optional fields after all setters have been called */
    private void finishConfiguration() {
        if (mLogger == null) {
            // Silent logging
            mLogger = new LayoutLog();
        }
    }

    /**
     * Renders the model and returns the result as a {@link RenderSession}.
     * @return the {@link RenderSession} resulting from rendering the current model
     * @throws XmlPullParserException
     * @throws FileNotFoundException
     */
    public RenderSession createRenderSession(String layoutName) throws FileNotFoundException,
            XmlPullParserException {
        finishConfiguration();

        if (mResourceResolver == null) {
            // Abort the rendering if the resources are not found.
            return null;
        }

        // find the layout to run
        ResourceValue value = mResourceResolver.getProjectResource(ResourceType.LAYOUT, layoutName);
        if (value == null || value.getValue() == null) {
            throw new IllegalArgumentException("layout does not exist");
        }

        File layoutFile = new File(value.getValue());

        ILayoutPullParser parser = null;
        parser = new XmlParser();
        parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true);
        parser.setInput(new FileInputStream(layoutFile), "UTF-8"); //$NON-NLS-1$

        figureSomeValuesOut();

        SessionParams params = new SessionParams(
                parser,
                mRenderingMode,
                this /* projectKey */,
                mWidth, mHeight,
                mConfig.getDensityQualifier().getValue(),
                mXdpi, mYdpi,
                mResourceResolver,
                mProjectCallback,
                mMinSdkVersion,
                mTargetSdkVersion,
                mLogger);

        // Request margin and baseline information.
        // TODO: Be smarter about setting this; start without it, and on the first request
        // for an extended view info, re-render in the same session, and then set a flag
        // which will cause this to create extended view info each time from then on in the
        // same session
        params.setExtendedViewInfoMode(true);

        if (!mShowDecorations) {
            params.setForceNoDecor();
        } else {
            if (mAppLabel == null) {
                mAppLabel = "Random App";
            }

            params.setAppLabel(mAppLabel);
            params.setAppIcon(mAppIconName); // ok to be null
        }

        params.setConfigScreenSize(mConfig.getScreenSizeQualifier().getValue());

        if (mOverrideBgColor != null) {
            params.setOverrideBgColor(mOverrideBgColor.intValue());
        }

        // set the Image Overlay as the image factory.
        params.setImageFactory(mImageFactory);

        try {
            return mLayoutLib.createSession(params);
        } catch (RuntimeException t) {
            // Exceptions from the bridge
            mLogger.error(null, t.getLocalizedMessage(), t, null);
            throw t;
        }
    }

    private void figureSomeValuesOut() {
        int size1 = mConfig.getScreenDimensionQualifier().getValue1();
        int size2 = mConfig.getScreenDimensionQualifier().getValue2();
        ScreenOrientation orientation = mConfig.getScreenOrientationQualifier().getValue();
        switch (orientation) {
            case LANDSCAPE:
                mWidth = size1 < size2 ? size2 : size1;
                mHeight = size1 < size2 ? size1 : size2;
                break;
            case PORTRAIT:
                mWidth = size1 < size2 ? size1 : size2;
                mHeight = size1 < size2 ? size2 : size1;
                break;
            case SQUARE:
                mWidth = mHeight = size1;
                break;
        }

        if (mMinSdkVersion == -1) {
            mMinSdkVersion = mConfig.getVersionQualifier().getVersion();
        }

        if (mTargetSdkVersion == -1) {
            mTargetSdkVersion = mConfig.getVersionQualifier().getVersion();
        }

        if (mXdpi == -1) {
            mXdpi = mConfig.getDensityQualifier().getValue().getDpiValue();
        }

        if (mYdpi == -1) {
            mYdpi = mConfig.getDensityQualifier().getValue().getDpiValue();
        }
    }

    /**
     * Renders the given resource value (which should refer to a drawable) and returns it
     * as an image
     *
     * @param drawableResourceValue the drawable resource value to be rendered, or null
     * @return the image, or null if something went wrong
     */
    public BufferedImage renderDrawable(ResourceValue drawableResourceValue) {
        if (drawableResourceValue == null) {
            return null;
        }

        finishConfiguration();

        figureSomeValuesOut();

        DrawableParams params = new DrawableParams(drawableResourceValue, this, mWidth, mHeight,
                mConfig.getDensityQualifier().getValue(),
                mXdpi, mYdpi, mResourceResolver, mProjectCallback, mMinSdkVersion,
                mTargetSdkVersion, mLogger);
        params.setForceNoDecor();
        Result result = mLayoutLib.renderDrawable(params);
        if (result != null && result.isSuccess()) {
            Object data = result.getData();
            if (data instanceof BufferedImage) {
                return (BufferedImage) data;
            }
        }

        return null;
    }
}