aboutsummaryrefslogtreecommitdiffstats
path: root/layoutlib_api/sample/src/com/example/android/render/RenderServiceFactory.java
blob: dffd4ec29587c37e97f17aa89301bca974cc0aec (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
314
315
316
317
318
319
320
/*
 * 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.log.ILogger;
import com.android.ide.common.rendering.LayoutLibrary;
import com.android.ide.common.rendering.api.DeclareStyleableResourceValue;
import com.android.ide.common.rendering.api.IProjectCallback;
import com.android.ide.common.rendering.api.ResourceValue;
import com.android.ide.common.resources.FrameworkResources;
import com.android.ide.common.resources.ResourceItem;
import com.android.ide.common.resources.ResourceRepository;
import com.android.ide.common.resources.ResourceResolver;
import com.android.ide.common.resources.configuration.DensityQualifier;
import com.android.ide.common.resources.configuration.FolderConfiguration;
import com.android.ide.common.resources.configuration.KeyboardStateQualifier;
import com.android.ide.common.resources.configuration.NavigationMethodQualifier;
import com.android.ide.common.resources.configuration.NavigationStateQualifier;
import com.android.ide.common.resources.configuration.ScreenDimensionQualifier;
import com.android.ide.common.resources.configuration.ScreenHeightQualifier;
import com.android.ide.common.resources.configuration.ScreenOrientationQualifier;
import com.android.ide.common.resources.configuration.ScreenRatioQualifier;
import com.android.ide.common.resources.configuration.ScreenSizeQualifier;
import com.android.ide.common.resources.configuration.ScreenWidthQualifier;
import com.android.ide.common.resources.configuration.SmallestScreenWidthQualifier;
import com.android.ide.common.resources.configuration.TextInputMethodQualifier;
import com.android.ide.common.resources.configuration.TouchScreenQualifier;
import com.android.ide.common.resources.configuration.VersionQualifier;
import com.android.ide.common.sdk.LoadStatus;
import com.android.io.FileWrapper;
import com.android.io.FolderWrapper;
import com.android.resources.Density;
import com.android.resources.Keyboard;
import com.android.resources.KeyboardState;
import com.android.resources.Navigation;
import com.android.resources.NavigationState;
import com.android.resources.ResourceType;
import com.android.resources.ScreenOrientation;
import com.android.resources.ScreenRatio;
import com.android.resources.ScreenSize;
import com.android.resources.TouchScreen;
import com.android.sdklib.SdkConstants;
import com.android.sdklib.internal.project.ProjectProperties;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * RenderService Factory. This is initialized for a given platform from the SDK.
 *
 * Also contains some utility method to create {@link FolderConfiguration} and
 * {@link ResourceResolver}
 *
 */
public class RenderServiceFactory {

    private LayoutLibrary mLibrary;
    private FrameworkResources mResources;

    public static RenderServiceFactory create(File platformFolder) {

        // create the factory
        RenderServiceFactory factory = new RenderServiceFactory();
        if (factory.loadLibrary(platformFolder)) {
            return factory;
        }

        return null;
    }

    /**
     * Creates a config. This must be a valid config like a device would return. This is to
     * prevent issues where some resources don't exist in all cases and not in the default
     * (for instance only available in hdpi and mdpi but not in default).
     *
     * @param size1
     * @param size2
     * @param screenSize
     * @param screenRatio
     * @param orientation
     * @param density
     * @param touchScreen
     * @param keyboardState
     * @param keyboard
     * @param navigationState
     * @param navigation
     * @param apiLevel
     * @return
     */
    public static FolderConfiguration createConfig(
            int size1,
            int size2,
            ScreenSize screenSize,
            ScreenRatio screenRatio,
            ScreenOrientation orientation,
            Density density,
            TouchScreen touchScreen,
            KeyboardState keyboardState,
            Keyboard keyboard,
            NavigationState navigationState,
            Navigation navigation,
            int apiLevel) {
        FolderConfiguration config = new FolderConfiguration();

        int width = size1, height = size2;
        switch (orientation) {
            case LANDSCAPE:
                width = size1 < size2 ? size2 : size1;
                height = size1 < size2 ? size1 : size2;
                break;
            case PORTRAIT:
                width = size1 < size2 ? size1 : size2;
                height = size1 < size2 ? size2 : size1;
                break;
            case SQUARE:
                width = height = size1;
                break;
        }

        int wdp = (width * Density.DEFAULT_DENSITY) / density.getDpiValue();
        int hdp = (height * Density.DEFAULT_DENSITY) / density.getDpiValue();

        config.addQualifier(new SmallestScreenWidthQualifier(wdp < hdp ? wdp : hdp));
        config.addQualifier(new ScreenWidthQualifier(wdp));
        config.addQualifier(new ScreenHeightQualifier(hdp));

        config.addQualifier(new ScreenSizeQualifier(screenSize));
        config.addQualifier(new ScreenRatioQualifier(screenRatio));
        config.addQualifier(new ScreenOrientationQualifier(orientation));
        config.addQualifier(new DensityQualifier(density));
        config.addQualifier(new TouchScreenQualifier(touchScreen));
        config.addQualifier(new KeyboardStateQualifier(keyboardState));
        config.addQualifier(new TextInputMethodQualifier(keyboard));
        config.addQualifier(new NavigationStateQualifier(navigationState));
        config.addQualifier(new NavigationMethodQualifier(navigation));
        config.addQualifier(width > height ? new ScreenDimensionQualifier(width, height) :
            new ScreenDimensionQualifier(height, width));
        config.addQualifier(new VersionQualifier(apiLevel));

        config.updateScreenWidthAndHeight();

        return config;
    }

    /**
     * Returns a {@link ResourceResolver} for a given config and project resource.
     *
     * @param config
     * @param projectResources
     * @param themeName
     * @param isProjectTheme
     * @return
     */
    public ResourceResolver createResourceResolver(
            FolderConfiguration config,
            ResourceRepository projectResources,
            String themeName,
            boolean isProjectTheme) {

        Map<ResourceType, Map<String, ResourceValue>> configedProjectRes =
                projectResources.getConfiguredResources(config);

        Map<ResourceType, Map<String, ResourceValue>> configedFrameworkRes =
                mResources.getConfiguredResources(config);

        return ResourceResolver.create(configedProjectRes, configedFrameworkRes,
                themeName, isProjectTheme);
    }

    /**
     * Creates a RenderService
     *
     * @param resources
     * @param config
     * @param projectCallback
     * @return
     */
    public RenderService createService(
            ResourceResolver resources,
            FolderConfiguration config,
            IProjectCallback projectCallback) {
        RenderService renderService = new RenderService(
                mLibrary, resources, config, projectCallback);

        return renderService;

    }

    /**
     * Creates a RenderService. This is less efficient than
     * {@link #createService(ResourceResolver, FolderConfiguration, IProjectCallback)} since the
     * {@link ResourceResolver} object is not cached by the caller.
     *
     * @param projectResources
     * @param themeName
     * @param isProjectTheme
     * @param config
     * @param projectCallback
     * @return
     */
    public RenderService createService(
            ResourceRepository projectResources,
            String themeName,
            boolean isProjectTheme,
            FolderConfiguration config,
            IProjectCallback projectCallback) {
        ResourceResolver resources = createResourceResolver(
                config, projectResources, themeName, isProjectTheme);

        RenderService renderService = new RenderService(
                mLibrary, resources, config, projectCallback);

        return renderService;
    }

    private RenderServiceFactory() {

    }

    private boolean loadLibrary(File platformFolder) {
        if (platformFolder.isDirectory() == false) {
            throw new IllegalArgumentException("platform folder does not exist.");
        }

        File dataFolder = new File(platformFolder, "data");
        if (dataFolder.isDirectory() == false) {
            throw new IllegalArgumentException("platform data folder does not exist.");
        }

        File layoutLibJar = new File(dataFolder, "layoutlib.jar");
        if (layoutLibJar.isFile() == false) {
            throw new IllegalArgumentException("platform layoutlib.jar does not exist.");
        }

        File resFolder = new File(dataFolder, "res");
        if (resFolder.isDirectory() == false) {
            throw new IllegalArgumentException("platform res folder does not exist.");
        }

        File fontFolder = new File(dataFolder, "fonts");
        if (fontFolder.isDirectory() == false) {
            throw new IllegalArgumentException("platform font folder does not exist.");
        }

        FileWrapper buildProp = new FileWrapper(platformFolder, SdkConstants.FN_BUILD_PROP);
        if (buildProp.isFile() == false) {
            throw new IllegalArgumentException("platform build.prop does not exist.");
        }

        StdOutLogger log = new StdOutLogger();

        mLibrary = LayoutLibrary.load(layoutLibJar.getAbsolutePath(), log,
                "LayoutLibRenderer");
        if (mLibrary.getStatus() != LoadStatus.LOADED) {
            throw new IllegalArgumentException(mLibrary.getLoadMessage());
        }

        // load the framework resources
        mResources = loadResources(resFolder, log);

        // need to get the styleable info to find the enum/flag map.
        List<ResourceItem> items = mResources.getResourceItemsOfType(
                ResourceType.DECLARE_STYLEABLE);

        HashMap<String, Map<String, Integer>> enumMap = new HashMap<String, Map<String, Integer>>();

        // standard default config.
        FolderConfiguration config = new FolderConfiguration();
        for (ResourceItem item : items) {
            ResourceValue value = item.getResourceValue(
                    ResourceType.DECLARE_STYLEABLE, config, true /*isFramework*/);
            if (value instanceof DeclareStyleableResourceValue) {
                DeclareStyleableResourceValue styleable = (DeclareStyleableResourceValue) value;
                Map<String, Map<String, Integer>> map = styleable.getAllAttributes();
                if (map != null) {
                    enumMap.putAll(map);
                }
            }
        }

        // we need to parse the build.prop for this
        Map<String, String> buildPropMap = ProjectProperties.parsePropertyFile(buildProp, log);

        return mLibrary.init(buildPropMap, fontFolder, enumMap, log);
    }

    private FrameworkResources loadResources(File resFolder, ILogger log) {
        FrameworkResources resources = new FrameworkResources();

        try {
            FolderWrapper path = new FolderWrapper(resFolder);
            resources.loadResources(path);
            resources.loadPublicResources(path, log);
            return resources;
        } catch (IOException e) {
            // since we test that folders are folders, and files are files, this shouldn't
            // happen. We can ignore it.
        }

        return null;
    }

}