1/*
2 * Copyright (C) 2014 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.intensive.setup;
18
19import com.android.SdkConstants;
20import com.android.ide.common.rendering.api.ActionBarCallback;
21import com.android.ide.common.rendering.api.AdapterBinding;
22import com.android.ide.common.rendering.api.ILayoutPullParser;
23import com.android.ide.common.rendering.api.LayoutlibCallback;
24import com.android.ide.common.rendering.api.ParserFactory;
25import com.android.ide.common.rendering.api.ResourceReference;
26import com.android.ide.common.rendering.api.ResourceValue;
27import com.android.ide.common.resources.IntArrayWrapper;
28import com.android.resources.ResourceType;
29import com.android.util.Pair;
30import com.android.utils.ILogger;
31
32import org.kxml2.io.KXmlParser;
33import org.xmlpull.v1.XmlPullParser;
34import org.xmlpull.v1.XmlPullParserException;
35
36import android.annotation.NonNull;
37import android.annotation.Nullable;
38
39import java.io.File;
40import java.lang.reflect.Constructor;
41import java.lang.reflect.Field;
42import java.lang.reflect.Modifier;
43import java.util.Map;
44
45import com.google.android.collect.Maps;
46
47import static org.junit.Assert.fail;
48
49@SuppressWarnings("deprecation") // For Pair
50public class LayoutLibTestCallback extends LayoutlibCallback {
51
52    private static final String PROJECT_CLASSES_LOCATION = "/testApp/MyApplication/build/intermediates/classes/debug/";
53    private static final String PACKAGE_NAME = "com.android.layoutlib.test.myapplication";
54
55    private final Map<Integer, Pair<ResourceType, String>> mProjectResources = Maps.newHashMap();
56    private final Map<IntArrayWrapper, String> mStyleableValueToNameMap = Maps.newHashMap();
57    private final Map<ResourceType, Map<String, Integer>> mResources = Maps.newHashMap();
58    private final ILogger mLog;
59    private final ActionBarCallback mActionBarCallback = new ActionBarCallback();
60    private final ClassLoader mModuleClassLoader = new ModuleClassLoader(PROJECT_CLASSES_LOCATION);
61
62    public LayoutLibTestCallback(ILogger logger) {
63        mLog = logger;
64    }
65
66    public void initResources() throws ClassNotFoundException {
67        Class<?> rClass = mModuleClassLoader.loadClass(PACKAGE_NAME + ".R");
68        Class<?>[] nestedClasses = rClass.getDeclaredClasses();
69        for (Class<?> resClass : nestedClasses) {
70            final ResourceType resType = ResourceType.getEnum(resClass.getSimpleName());
71
72            if (resType != null) {
73                final Map<String, Integer> resName2Id = Maps.newHashMap();
74                mResources.put(resType, resName2Id);
75
76                for (Field field : resClass.getDeclaredFields()) {
77                    final int modifiers = field.getModifiers();
78                    if (Modifier.isStatic(modifiers)) { // May not be final in library projects
79                        final Class<?> type = field.getType();
80                        try {
81                            if (type.isArray() && type.getComponentType() == int.class) {
82                                mStyleableValueToNameMap.put(
83                                        new IntArrayWrapper((int[]) field.get(null)),
84                                        field.getName());
85                            } else if (type == int.class) {
86                                final Integer value = (Integer) field.get(null);
87                                mProjectResources.put(value, Pair.of(resType, field.getName()));
88                                resName2Id.put(field.getName(), value);
89                            } else {
90                                mLog.error(null, "Unknown field type in R class: %1$s", type);
91                            }
92                        } catch (IllegalAccessException ignored) {
93                            mLog.error(ignored, "Malformed R class: %1$s", PACKAGE_NAME + ".R");
94                        }
95                    }
96                }
97            }
98        }
99    }
100
101
102    @Override
103    public Object loadView(String name, Class[] constructorSignature, Object[] constructorArgs)
104            throws Exception {
105        Class<?> viewClass = mModuleClassLoader.loadClass(name);
106        Constructor<?> viewConstructor = viewClass.getConstructor(constructorSignature);
107        viewConstructor.setAccessible(true);
108        return viewConstructor.newInstance(constructorArgs);
109    }
110
111    @Override
112    public String getNamespace() {
113        return String.format(SdkConstants.NS_CUSTOM_RESOURCES_S,
114                PACKAGE_NAME);
115    }
116
117    @Override
118    public Pair<ResourceType, String> resolveResourceId(int id) {
119        return mProjectResources.get(id);
120    }
121
122    @Override
123    public String resolveResourceId(int[] id) {
124        return mStyleableValueToNameMap.get(new IntArrayWrapper(id));
125    }
126
127    @Override
128    public Integer getResourceId(ResourceType type, String name) {
129        return mResources.get(type).get(name);
130    }
131
132    @Override
133    public ILayoutPullParser getParser(String layoutName) {
134        fail("This method shouldn't be called by this version of LayoutLib.");
135        return null;
136    }
137
138    @Override
139    public ILayoutPullParser getParser(ResourceValue layoutResource) {
140        return new LayoutPullParser(new File(layoutResource.getValue()));
141    }
142
143    @Override
144    public Object getAdapterItemValue(ResourceReference adapterView, Object adapterCookie,
145            ResourceReference itemRef, int fullPosition, int positionPerType,
146            int fullParentPosition, int parentPositionPerType, ResourceReference viewRef,
147            ViewAttribute viewAttribute, Object defaultValue) {
148        return null;
149    }
150
151    @Override
152    public AdapterBinding getAdapterBinding(ResourceReference adapterViewRef, Object adapterCookie,
153            Object viewObject) {
154        return null;
155    }
156
157    @Override
158    public ActionBarCallback getActionBarCallback() {
159        return mActionBarCallback;
160    }
161
162    @Override
163    public boolean supports(int ideFeature) {
164        return false;
165    }
166
167    @NonNull
168    @Override
169    public ParserFactory getParserFactory() {
170        return new ParserFactory() {
171            @NonNull
172            @Override
173            public XmlPullParser createParser(@Nullable String debugName)
174                    throws XmlPullParserException {
175                return new KXmlParser();
176            }
177        };
178    }
179}
180