summaryrefslogtreecommitdiff
path: root/compiler/src/main/java/android/databinding/annotationprocessor/ProcessExpressions.java
blob: 9c65f5c18cf3f279f7004c537a1d140ce2e6d209 (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
/*
 * Copyright (C) 2015 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 android.databinding.annotationprocessor;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.SystemUtils;

import android.databinding.BindingBuildInfo;
import android.databinding.tool.CompilerChef;
import android.databinding.tool.LayoutXmlProcessor;
import android.databinding.tool.reflection.SdkUtil;
import android.databinding.tool.store.ResourceBundle;
import android.databinding.tool.util.GenerationalClassUtil;
import android.databinding.tool.util.L;
import android.databinding.tool.util.Preconditions;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.processing.ProcessingEnvironment;
import javax.annotation.processing.RoundEnvironment;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;

public class ProcessExpressions extends ProcessDataBinding.ProcessingStep {
    public ProcessExpressions() {
    }

    @Override
    public boolean onHandleStep(RoundEnvironment roundEnvironment,
            ProcessingEnvironment processingEnvironment, BindingBuildInfo buildInfo)
            throws JAXBException {
        ResourceBundle resourceBundle;
        SdkUtil.initialize(buildInfo.minSdk(), new File(buildInfo.sdkRoot()));
        resourceBundle = new ResourceBundle(buildInfo.modulePackage());
        List<IntermediateV2> intermediateList = loadDependencyIntermediates();
        for (Intermediate intermediate : intermediateList) {
            try {
                intermediate.appendTo(resourceBundle);
            } catch (Throwable throwable) {
                L.e(throwable, "unable to prepare resource bundle");
            }
        }

        IntermediateV2 mine = createIntermediateFromLayouts(buildInfo.layoutInfoDir(),
                intermediateList);
        if (mine != null) {
            mine.updateOverridden(resourceBundle);
            intermediateList.add(mine);
            saveIntermediate(processingEnvironment, buildInfo, mine);
            mine.appendTo(resourceBundle);
        }
        // generate them here so that bindable parser can read
        try {
            writeResourceBundle(resourceBundle, buildInfo.isLibrary(), buildInfo.minSdk(),
                    buildInfo.exportClassListTo());
        } catch (Throwable t) {
            L.e(t, "cannot generate view binders");
        }
        return true;
    }

    private List<IntermediateV2> loadDependencyIntermediates() {
        final List<Intermediate> original = GenerationalClassUtil.loadObjects(
                GenerationalClassUtil.ExtensionFilter.LAYOUT);
        final List<IntermediateV2> upgraded = new ArrayList<IntermediateV2>(original.size());
        for (Intermediate intermediate : original) {
            final Intermediate updatedIntermediate = intermediate.upgrade();
            Preconditions.check(updatedIntermediate instanceof IntermediateV2, "Incompatible data"
                    + " binding dependency. Please update your dependencies or recompile them with"
                    + " application module's data binding version.");
            //noinspection ConstantConditions
            upgraded.add((IntermediateV2) updatedIntermediate);
        }
        return upgraded;
    }

    private void saveIntermediate(ProcessingEnvironment processingEnvironment,
            BindingBuildInfo buildInfo, IntermediateV2 intermediate) {
        GenerationalClassUtil.writeIntermediateFile(processingEnvironment,
                buildInfo.modulePackage(), buildInfo.modulePackage() +
                        GenerationalClassUtil.ExtensionFilter.LAYOUT.getExtension(),
                intermediate);
    }

    @Override
    public void onProcessingOver(RoundEnvironment roundEnvironment,
            ProcessingEnvironment processingEnvironment, BindingBuildInfo buildInfo) {
    }

    private IntermediateV2 createIntermediateFromLayouts(String layoutInfoFolderPath,
            List<IntermediateV2> intermediateList) {
        final Set<String> excludeList = new HashSet<String>();
        for (IntermediateV2 lib : intermediateList) {
            excludeList.addAll(lib.mLayoutInfoMap.keySet());
        }
        final File layoutInfoFolder = new File(layoutInfoFolderPath);
        if (!layoutInfoFolder.isDirectory()) {
            L.d("layout info folder does not exist, skipping for %s", layoutInfoFolderPath);
            return null;
        }
        IntermediateV2 result = new IntermediateV2();
        for (File layoutFile : layoutInfoFolder.listFiles(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".xml") && !excludeList.contains(name);
            }
        })) {
            try {
                result.addEntry(layoutFile.getName(), FileUtils.readFileToString(layoutFile));
            } catch (IOException e) {
                L.e(e, "cannot load layout file information. Try a clean build");
            }
        }
        return result;
    }

    private void writeResourceBundle(ResourceBundle resourceBundle, boolean forLibraryModule,
            final int minSdk, String exportClassNamesTo)
            throws JAXBException {
        final CompilerChef compilerChef = CompilerChef.createChef(resourceBundle, getWriter());
        compilerChef.sealModels();
        compilerChef.writeComponent();
        if (compilerChef.hasAnythingToGenerate()) {
            compilerChef.writeViewBinderInterfaces(forLibraryModule);
            if (!forLibraryModule) {
                compilerChef.writeViewBinders(minSdk);
            }
        }
        if (forLibraryModule && exportClassNamesTo == null) {
            L.e("When compiling a library module, build info must include exportClassListTo path");
        }
        if (forLibraryModule) {
            Set<String> classNames = compilerChef.getWrittenClassNames();
            String out = StringUtils.join(classNames, SystemUtils.LINE_SEPARATOR);
            L.d("Writing list of classes to %s . \nList:%s", exportClassNamesTo, out);
            try {
                //noinspection ConstantConditions
                FileUtils.write(new File(exportClassNamesTo), out);
            } catch (IOException e) {
                L.e(e, "Cannot create list of written classes");
            }
        }
        mCallback.onChefReady(compilerChef, forLibraryModule, minSdk);
    }

    public interface Intermediate extends Serializable {

        Intermediate upgrade();

        void appendTo(ResourceBundle resourceBundle) throws Throwable;
    }

    public static class IntermediateV1 implements Intermediate {

        transient Unmarshaller mUnmarshaller;

        // name to xml content map
        Map<String, String> mLayoutInfoMap = new HashMap<String, String>();

        @Override
        public Intermediate upgrade() {
            final IntermediateV2 updated = new IntermediateV2();
            updated.mLayoutInfoMap = mLayoutInfoMap;
            updated.mUnmarshaller = mUnmarshaller;
            return updated;
        }

        @Override
        public void appendTo(ResourceBundle resourceBundle) throws JAXBException {
            if (mUnmarshaller == null) {
                JAXBContext context = JAXBContext
                        .newInstance(ResourceBundle.LayoutFileBundle.class);
                mUnmarshaller = context.createUnmarshaller();
            }
            for (String content : mLayoutInfoMap.values()) {
                final InputStream is = IOUtils.toInputStream(content);
                try {
                    final ResourceBundle.LayoutFileBundle bundle
                            = (ResourceBundle.LayoutFileBundle) mUnmarshaller.unmarshal(is);
                    resourceBundle.addLayoutBundle(bundle);
                    L.d("loaded layout info file %s", bundle);
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        }

        public void addEntry(String name, String contents) {
            mLayoutInfoMap.put(name, contents);
        }

        // keeping the method to match deserialized structure
        @SuppressWarnings("unused")
        public void removeOverridden(List<Intermediate> existing) {
        }
    }

    public static class IntermediateV2 extends IntermediateV1 {
        // specify so that we can define updates ourselves.
        private static final long serialVersionUID = 2L;
        @Override
        public void appendTo(ResourceBundle resourceBundle) throws JAXBException {
            for (Map.Entry<String, String> entry : mLayoutInfoMap.entrySet()) {
                final InputStream is = IOUtils.toInputStream(entry.getValue());
                try {
                    final ResourceBundle.LayoutFileBundle bundle = ResourceBundle.LayoutFileBundle
                            .fromXML(is);
                    resourceBundle.addLayoutBundle(bundle);
                    L.d("loaded layout info file %s", bundle);
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }
        }

        /**
         * if a layout is overridden from a module (which happens when layout is auto-generated),
         * we need to update its contents from the class that overrides it.
         * This must be done before this bundle is saved, otherwise, it will not be recognized
         * when it is used in another project.
         */
        public void updateOverridden(ResourceBundle bundle) throws JAXBException {
            // When a layout is copied from inherited module, it is eleminated while reading
            // info files. (createIntermediateFromLayouts).
            // Build process may also duplicate some files at compile time. This is where
            // we detect those copies and force inherit their module and classname information.
            final HashMap<String, List<ResourceBundle.LayoutFileBundle>> bundles = bundle
                    .getLayoutBundles();
            for (Map.Entry<String, String> info : mLayoutInfoMap.entrySet()) {
                String key = LayoutXmlProcessor.exportLayoutNameFromInfoFileName(info.getKey());
                final List<ResourceBundle.LayoutFileBundle> existingList = bundles.get(key);
                if (existingList != null && !existingList.isEmpty()) {
                    ResourceBundle.LayoutFileBundle myBundle = ResourceBundle.LayoutFileBundle
                            .fromXML(IOUtils.toInputStream(info.getValue()));
                    final ResourceBundle.LayoutFileBundle inheritFrom = existingList.get(0);
                    myBundle.inheritConfigurationFrom(inheritFrom);
                    L.d("inheriting data for %s (%s) from %s", info.getKey(), key, inheritFrom);
                    mLayoutInfoMap.put(info.getKey(), myBundle.toXML());
                }
            }
        }
    }
}