aboutsummaryrefslogtreecommitdiffstats
path: root/eclipse/plugins/com.android.ide.eclipse.adt/src/com/android/ide/eclipse/adt/internal/wizards/templates/TemplateHandler.java
blob: 4f107fb9803e565e0d01bce1ad9a6ea314be0274 (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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
/*
 * Copyright (C) 2012 The Android Open Source Project
 *
 * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php
 *
 * 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.android.ide.eclipse.adt.internal.wizards.templates;

import static com.android.ide.eclipse.adt.AdtConstants.DOT_FTL;
import static com.android.ide.eclipse.adt.AdtConstants.DOT_JAR;
import static com.android.ide.eclipse.adt.AdtConstants.DOT_XML;

import com.android.annotations.NonNull;
import com.android.annotations.Nullable;
import com.android.ide.eclipse.adt.AdtPlugin;
import com.android.ide.eclipse.adt.AdtUtils;
import com.android.ide.eclipse.adt.internal.editors.formatting.XmlFormatPreferences;
import com.android.ide.eclipse.adt.internal.editors.formatting.XmlFormatStyle;
import com.android.ide.eclipse.adt.internal.editors.formatting.XmlPrettyPrinter;
import com.android.ide.eclipse.adt.internal.editors.layout.gle2.DomUtilities;
import com.android.manifmerger.ManifestMerger;
import com.android.resources.ResourceFolderType;
import com.android.sdklib.SdkConstants;
import com.google.common.base.Charsets;
import com.google.common.io.ByteStreams;
import com.google.common.io.Files;

import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import org.eclipse.core.runtime.Path;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.StringWriter;
import java.io.Writer;
import java.net.URI;
import java.net.URL;
import java.security.CodeSource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import lombok.ast.libs.org.parboiled.google.collect.Lists;

/**
 * Handler which manages instantiating FreeMarker templates, copying resources
 * and merging into existing files
 */
class TemplateHandler {
    /**
     * Special marker indicating that this path refers to the special shared
     * resource directory rather than being somewhere inside the root/ directory
     * where all template specific resources are found
     */
    private static final String VALUE_TEMPLATE_DIR = "$TEMPLATEDIR"; //$NON-NLS-1$

    /**
     * Directory within the template which contains the resources referenced
     * from the template.xml file
     */
    private static final String DATA_ROOT = "root";      //$NON-NLS-1$

    /**
     * Shared resource directory containing common resources shared among
     * multiple templates
     */
    private static final String RESOURCE_ROOT = "res";   //$NON-NLS-1$

    /** Relative path within the ADT plugin where the templates are found */
    static final String TEMPLATE_PREFIX = "/templates/"; //$NON-NLS-1$

    /** Reserved filename which describes each template */
    static final String TEMPLATE_XML = "template.xml";   //$NON-NLS-1$

    // Various tags and attributes used in the template metadata files - template.xml,
    // globals.xml.ftl, recipe.xml.ftl, etc.

    static final String TAG_MERGE = "merge";             //$NON-NLS-1$
    static final String TAG_EXECUTE = "execute";         //$NON-NLS-1$
    static final String TAG_GLOBALS = "globals";         //$NON-NLS-1$
    static final String TAG_GLOBAL = "global";           //$NON-NLS-1$
    static final String TAG_PARAMETER = "parameter";     //$NON-NLS-1$
    static final String TAG_COPY = "copy";               //$NON-NLS-1$
    static final String TAG_INSTANTIATE = "instantiate"; //$NON-NLS-1$
    static final String TAG_OPEN = "open";               //$NON-NLS-1$
    static final String TAG_THUMB = "thumb";             //$NON-NLS-1$
    static final String TAG_THUMBS = "thumbs";           //$NON-NLS-1$
    static final String ATTR_VALUE = "value";            //$NON-NLS-1$
    static final String ATTR_DEFAULT = "default";        //$NON-NLS-1$
    static final String ATTR_SUGGEST = "suggest";        //$NON-NLS-1$
    static final String ATTR_ID = "id";                  //$NON-NLS-1$
    static final String ATTR_NAME = "name";              //$NON-NLS-1$
    static final String ATTR_DESCRIPTION = "description";//$NON-NLS-1$
    static final String ATTR_TYPE = "type";              //$NON-NLS-1$
    static final String ATTR_HELP = "help";              //$NON-NLS-1$
    static final String ATTR_FILE = "file";              //$NON-NLS-1$
    static final String ATTR_TO = "to";                  //$NON-NLS-1$
    static final String ATTR_FROM = "from";              //$NON-NLS-1$
    static final String ATTR_CONSTRAINTS = "constraints";//$NON-NLS-1$

    /** Default padding to apply in wizards around the thumbnail preview images */
    static final int PREVIEW_PADDING = 10;

    /** Default width to scale thumbnail preview images in wizards to */
    static final int PREVIEW_WIDTH = 200;

    /**
     * List of files to open after the wizard has been created (these are
     * identified by {@link #TAG_OPEN} elements in the recipe file
     */
    private final List<String> mOpen = Lists.newArrayList();

    /** Path to the directory containing the templates */
    private final File mRootPath;

    /** The template loader which is responsible for finding (and sharing) template files */
    private final MyTemplateLoader mLoader;

    /** Agree to all file-overwrites from now on? */
    private boolean mYesToAll = false;

    /** Is writing the template cancelled? */
    private boolean mNoToAll = false;

    /**
     * Should files that we merge contents into be backed up? If yes, will
     * create emacs-style tilde-file backups (filename.xml~)
     */
    private boolean mBackupMergedFiles = true;

    /**
     * Template metadata
     */
    private TemplateMetadata mTemplate;

    /** Creates a new {@link TemplateHandler} for the given root path */
    static TemplateHandler createFromPath(File rootPath) {
        return new TemplateHandler(rootPath);
    }

    private TemplateHandler(File rootPath) {
        mRootPath = rootPath;
        mLoader = new MyTemplateLoader();
        mLoader.setPrefix(mRootPath.getPath());
    }

    public void setBackupMergedFiles(boolean backupMergedFiles) {
        mBackupMergedFiles = backupMergedFiles;
    }

    public void render(final File outputPath, Map<String, Object> args) {
        if (!outputPath.exists()) {
            outputPath.mkdirs();
        }

        // Render the instruction list template.
        Map<String, Object> paramMap = createParameterMap(args);
        Configuration freemarker = new Configuration();
        freemarker.setObjectWrapper(new DefaultObjectWrapper());
        freemarker.setTemplateLoader(mLoader);

        processVariables(freemarker, TEMPLATE_XML, paramMap, outputPath);
    }

    Map<String, Object> createParameterMap(Map<String, Object> args) {
        final Map<String, Object> paramMap = createBuiltinMap();

        // Wizard parameters supplied by user, specific to this template
        paramMap.putAll(args);

        return paramMap;
    }

    /** Data model for the templates */
    static Map<String, Object> createBuiltinMap() {
        // Create the data model.
        final Map<String, Object> paramMap = new HashMap<String, Object>();

        // Builtin conversion methods
        paramMap.put("slashedPackageName", new FmSlashedPackageNameMethod());       //$NON-NLS-1$
        paramMap.put("camelCaseToUnderscore", new FmCamelCaseToUnderscoreMethod()); //$NON-NLS-1$
        paramMap.put("underscoreToCamelCase", new FmUnderscoreToCamelCaseMethod()); //$NON-NLS-1$
        paramMap.put("activityToLayout", new FmActivityToLayoutMethod());           //$NON-NLS-1$
        paramMap.put("layoutToActivity", new FmLayoutToActivityMethod());           //$NON-NLS-1$

        // This should be handled better: perhaps declared "required packages" as part of the
        // inputs? (It would be better if we could conditionally disable template based
        // on availability)
        Map<String, String> builtin = new HashMap<String, String>();
        builtin.put("templatesRes", VALUE_TEMPLATE_DIR); //$NON-NLS-1$
        paramMap.put("android", builtin);                //$NON-NLS-1$

        return paramMap;
    }

    @Nullable
    public TemplateMetadata getTemplate() {
        if (mTemplate == null) {
            String xml = readTemplateTextResource(TEMPLATE_XML);
            if (xml != null) {
                Document doc = DomUtilities.parseDocument(xml, true);
                if (doc != null && doc.getDocumentElement() != null) {
                    mTemplate = new TemplateMetadata(doc);
                }
            }
        }

        return mTemplate;
    }

    @Nullable
    public static TemplateMetadata getTemplate(String templateName) {
        String relative = getTemplatePath(templateName) + '/' +TEMPLATE_XML;
        String xml = AdtPlugin.readEmbeddedTextFile(relative);
        Document doc = DomUtilities.parseDocument(xml, true);
        if (doc != null && doc.getDocumentElement() != null) {
            return new TemplateMetadata(doc);
        }

        return null;
    }

    @NonNull
    public static String getTemplatePath(String templateName) {
        return TEMPLATE_PREFIX + templateName;
    }

    @NonNull
    public String getResourcePath(String templateName) {
        return new File(mRootPath.getPath(), templateName).getPath();
    }

    /**
     * Load a text resource for the given relative path within the template
     *
     * @param relativePath relative path within the template
     * @return the string contents of the template text file
     */
    @Nullable
    public String readTemplateTextResource(@NonNull String relativePath) {
        if (mRootPath.getPath().startsWith(TEMPLATE_PREFIX)) {
            return AdtPlugin.readEmbeddedTextFile(getResourcePath(relativePath));
        } else {
            try {
                return Files.toString(new File(mRootPath, relativePath), Charsets.UTF_8);
            } catch (IOException e) {
                AdtPlugin.log(e, null);
                return null;
            }
        }
    }

    @Nullable
    public String readTemplateTextResource(@NonNull File file) {
        if (mRootPath.getPath().startsWith(TEMPLATE_PREFIX)) {
            return AdtPlugin.readEmbeddedTextFile(file.getPath());
        } else {
            try {
                return Files.toString(file, Charsets.UTF_8);
            } catch (IOException e) {
                AdtPlugin.log(e, null);
                return null;
            }
        }
    }

    /**
     * Reads the contents of a resource
     *
     * @param relativePath the path relative to the template directory
     * @return the binary data read from the file
     */
    @Nullable
    public byte[] readTemplateResource(@NonNull String relativePath) {
        if (mRootPath.getPath().startsWith(TEMPLATE_PREFIX)) {
            return AdtPlugin.readEmbeddedFile(getResourcePath(relativePath));
        } else {
            try {
                return Files.toByteArray(new File(mRootPath, relativePath));
            } catch (IOException e) {
                AdtPlugin.log(e, null);
                return null;
            }
        }
    }

    /** Read the given FreeMarker file and process the variable definitions */
    private void processVariables(final Configuration freemarker,
            String file, final Map<String, Object> paramMap, final File outputPath) {
        try {
            String xml;
            if (file.endsWith(DOT_XML)) {
                // Just read the file
                xml = readTemplateTextResource(file);
            } else {
                mLoader.setTemplateFile(new File(mRootPath, file));
                Template inputsTemplate = freemarker.getTemplate(file);
                StringWriter out = new StringWriter();
                inputsTemplate.process(paramMap, out);
                out.flush();
                xml = out.toString();
            }

            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();
            saxParser.parse(new ByteArrayInputStream(xml.getBytes()), new DefaultHandler() {
                @Override
                public void startElement(String uri, String localName, String name,
                        Attributes attributes)
                        throws SAXException {
                    if (TAG_PARAMETER.equals(name)) {
                        String id = attributes.getValue(ATTR_ID);
                        if (!paramMap.containsKey(id)) {
                            String value = attributes.getValue(ATTR_DEFAULT);
                            paramMap.put(id, value);
                        }
                    } else if (TAG_GLOBAL.equals(name)) {
                        String id = attributes.getValue(ATTR_ID);
                        if (!paramMap.containsKey(id)) {
                            String value = attributes.getValue(ATTR_VALUE);
                            paramMap.put(id, value);
                        }
                    } else if (TAG_GLOBALS.equals(name)) {
                        // Handle evaluation of variables
                        String path = attributes.getValue(ATTR_FILE);
                        if (path != null) {
                            processVariables(freemarker, path, paramMap, outputPath);
                        } // else: <globals> root element
                    } else if (TAG_EXECUTE.equals(name)) {
                        String path = attributes.getValue(ATTR_FILE);
                        if (path != null) {
                            execute(freemarker, path, paramMap, outputPath);
                        }
                    } else if (!name.equals("template") && !name.equals("category")
                            && !name.equals("option")) {
                        System.err.println("WARNING: Unknown template directive " + name);
                    }
                }
            });
        } catch (Exception e) {
            AdtPlugin.log(e, null);
        }
    }

    private boolean canOverwrite(File file) {
        if (file.exists() && !file.isDirectory()) {
            // Warn that the file already exists and ask the user what to do
            if (!mYesToAll) {
                MessageDialog dialog = new MessageDialog(null, "File Already Exists", null,
                        String.format(
                                "%1$s already exists.\nWould you like to replace it?",
                                file.getPath()),
                        MessageDialog.QUESTION, new String[] {
                                // Yes will be moved to the end because it's the default
                                "Yes", "No", "Cancel", "Yes to All"
                        }, 0);
                int result = dialog.open();
                switch (result) {
                    case 0:
                        // Yes
                        break;
                    case 3:
                        // Yes to all
                        mYesToAll = true;
                        break;
                    case 1:
                        // No
                        return false;
                    case SWT.DEFAULT:
                    case 2:
                        // Cancel
                        mNoToAll = true;
                        return false;
                }
            }

            if (mBackupMergedFiles) {
                return makeBackup(file);
            } else {
                return file.delete();
            }
        }

        return true;
    }

    /** Executes the given recipe file: copying, merging, instantiating, opening files etc */
    private void execute(
            final Configuration freemarker,
            String file,
            final Map<String, Object> paramMap,
            final File outputPath) {
        try {
            mLoader.setTemplateFile(new File(mRootPath, file));
            Template freemarkerTemplate = freemarker.getTemplate(file);

            StringWriter out = new StringWriter();
            freemarkerTemplate.process(paramMap, out);
            out.flush();
            String xml = out.toString();

            // Parse and execute the resulting instruction list.
            SAXParserFactory factory = SAXParserFactory.newInstance();
            SAXParser saxParser = factory.newSAXParser();

            saxParser.parse(new ByteArrayInputStream(xml.getBytes()),
                    new DefaultHandler() {
                @Override
                public void startElement(String uri, String localName, String name,
                        Attributes attributes)
                        throws SAXException {
                    if (mNoToAll) {
                        return;
                    }

                    try {
                        boolean instantiate = TAG_INSTANTIATE.equals(name);
                        if (TAG_COPY.equals(name) || instantiate) {
                            String fromPath = attributes.getValue(ATTR_FROM);
                            String toPath = attributes.getValue(ATTR_TO);
                            if (toPath == null || toPath.isEmpty()) {
                                toPath = attributes.getValue(ATTR_FROM);
                                toPath = AdtUtils.stripSuffix(toPath, DOT_FTL);
                            }
                            File to = new File(outputPath, toPath);
                            if (instantiate) {
                                instantiate(freemarker, paramMap, fromPath, to);
                            } else {
                                copyBundledResource(fromPath, to);
                            }
                        } else if (TAG_MERGE.equals(name)) {
                            String fromPath = attributes.getValue(ATTR_FROM);
                            String toPath = attributes.getValue(ATTR_TO);
                            if (toPath == null || toPath.isEmpty()) {
                                toPath = attributes.getValue(ATTR_FROM);
                                toPath = AdtUtils.stripSuffix(toPath, DOT_FTL);
                            }
                            // Resources in template.xml are located within root/
                            File to = new File(outputPath, toPath);
                            merge(freemarker, paramMap, fromPath, to);
                        } else if (name.equals(TAG_OPEN)) {
                            // The relative path here is within the output directory:
                            String relativePath = attributes.getValue(ATTR_FILE);
                            if (relativePath != null && !relativePath.isEmpty()) {
                                mOpen.add(relativePath);
                            }
                        } else if (!name.equals("recipe")) { //$NON-NLS-1$
                            System.err.println("WARNING: Unknown template directive " + name);
                        }
                    } catch (Exception e) {
                        AdtPlugin.log(e, null);
                    }
                }
            });

        } catch (Exception e) {
            AdtPlugin.log(e, null);
        }
    }

    private File getFullPath(String fromPath) {
        if (fromPath.startsWith(VALUE_TEMPLATE_DIR)) {
            return new File(mRootPath.getParentFile(), RESOURCE_ROOT
                    + fromPath.substring(VALUE_TEMPLATE_DIR.length()));
        }
        return new File(mRootPath, DATA_ROOT + File.separator + fromPath);
    }

    private void merge(
            @NonNull final Configuration freemarker,
            @NonNull final Map<String, Object> paramMap,
            @NonNull String relativeFrom,
            @NonNull File to) throws IOException, TemplateException {
        if (!to.exists()) {
            // The target file doesn't exist: don't merge, just copy
            boolean instantiate = relativeFrom.endsWith(DOT_FTL);
            if (instantiate) {
                instantiate(freemarker, paramMap, relativeFrom, to);
            } else {
                copyBundledResource(relativeFrom, to);
            }
            return;
        }

        if (!to.getPath().endsWith(DOT_XML)) {
            throw new RuntimeException("Only XML files can be merged at this point: " + to);
        }

        String xml = null;
        File from = getFullPath(relativeFrom);
        if (relativeFrom.endsWith(DOT_FTL)) {
            // Perform template substitution of the template prior to merging
            mLoader.setTemplateFile(from);
            Template template = freemarker.getTemplate(from.getName());
            Writer out = new StringWriter();
            template.process(paramMap, out);
            out.flush();
            xml = out.toString();
        } else {
            xml = readTemplateTextResource(from);
            if (xml == null) {
                return;
            }
        }

        String currentXml = Files.toString(to, Charsets.UTF_8);
        Document currentManifest = DomUtilities.parseStructuredDocument(currentXml);
        Document fragment = DomUtilities.parseStructuredDocument(xml);

        XmlFormatStyle formatStyle = XmlFormatStyle.MANIFEST;
        boolean modified;
        boolean ok;
        if (to.getName().equals(SdkConstants.FN_ANDROID_MANIFEST_XML)) {
            modified = ok = mergeManifest(currentManifest, fragment);
        } else {
            // Merge plain XML files
            ResourceFolderType folderType =
                    ResourceFolderType.getFolderType(to.getParentFile().getName());
            if (folderType != null) {
                formatStyle = XmlFormatStyle.getForFolderType(folderType);
            } else {
                formatStyle = XmlFormatStyle.FILE;
            }

            modified = mergeResourceFile(currentManifest, fragment, folderType, paramMap);
            ok = true;
        }

        // Finally write out the merged file (formatting etc)
        if (ok) {
            if (modified) {
                XmlPrettyPrinter printer = new XmlPrettyPrinter(
                        XmlFormatPreferences.create(), formatStyle, null);
                StringBuilder sb = new StringBuilder(2 );
                printer.prettyPrint(-1, currentManifest, null, null, sb, false /*openTagOnly*/);
                String contents = sb.toString();
                writeString(to, contents, false);
            }
        } else {
            // Just insert into file along with comment, using the "standard" conflict
            // syntax that many tools and editors recognize.
            String sep = AdtUtils.getLineSeparator();
            String contents =
                    "<<<<<<< Original" + sep
                    + currentXml + sep
                    + "=======" + sep
                    + xml
                    + ">>>>>>> Added" + sep;
            writeString(to, contents, false);
        }
    }

    /**
     * Writes the given contents into the given file (unless that file already
     * contains the given contents), and if the file exists ask user whether
     * the file should be overwritten (unless the user has already answered "Yes to All"
     * or "Cancel" (no to all).
     */
    private void writeString(File destination, String contents, boolean confirmOverwrite)
            throws IOException {
        // First make sure that the files aren't identical, in which case we can do
        // nothing (and not involve user)
        if (!(destination.exists()
                && isIdentical(contents.getBytes(Charsets.UTF_8), destination))) {
            // And if the file does exist (and is now known to be different),
            // ask user whether it should be replaced (canOverwrite will also
            // return true if the file doesn't exist)
            if (confirmOverwrite) {
                if (!canOverwrite(destination)) {
                    return;
                }
            } else {
                if (destination.exists()) {
                    if (mBackupMergedFiles) {
                        makeBackup(destination);
                    } else {
                        destination.delete();
                    }
                }
            }
            Files.write(contents, destination, Charsets.UTF_8);
        }
    }

    /**
     * Writes the given contents into the given file (unless that file already
     * contains the given contents), and if the file exists ask user whether
     * the file should be overwritten (unless the user has already answered "Yes to All"
     * or "Cancel" (no to all).
     */
    private void writeBytes(File destination, byte[] contents, boolean confirmOverwrite)
            throws IOException {
        // First make sure that the files aren't identical, in which case we can do
        // nothing (and not involve user)
        if (!(destination.exists() && isIdentical(contents, destination))) {
            // And if the file does exist (and is now known to be different),
            // ask user whether it should be replaced (canOverwrite will also
            // return true if the file doesn't exist)
            if (confirmOverwrite) {
                if (!canOverwrite(destination)) {
                    return;
                }
            } else {
                if (destination.exists()) {
                    if (mBackupMergedFiles) {
                        makeBackup(destination);
                    } else {
                        destination.delete();
                    }
                }
            }
            Files.write(contents, destination);
        }
    }

    /** Merges the given resource file contents into the given resource file
     * @param paramMap */
    private boolean mergeResourceFile(Document currentManifest, Document fragment,
            ResourceFolderType folderType, Map<String, Object> paramMap) {
        boolean modified = false;

        // For layouts for example, I want to *append* inside the root all the
        // contents of the new file.
        // But for resources for example, I want to combine elements which specify
        // the same name or id attribute.
        // For elements like manifest files we need to insert stuff at the right
        // location in a nested way (activities in the application element etc)
        // but that doesn't happen for the other file types.
        Element root = fragment.getDocumentElement();
        NodeList children = root.getChildNodes();
        List<Node> nodes = new ArrayList<Node>(children.getLength());
        for (int i = children.getLength() - 1; i >= 0; i--) {
            Node child = children.item(i);
            nodes.add(child);
            root.removeChild(child);
        }

        root = currentManifest.getDocumentElement();

        if (folderType == ResourceFolderType.VALUES) {
            // Try to merge items of the same name
            Map<String, Node> old = new HashMap<String, Node>();
            NodeList newSiblings = root.getChildNodes();
            for (int i = newSiblings.getLength() - 1; i >= 0; i--) {
                Node child = newSiblings.item(i);
                if (child.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) child;
                    String name = getResourceId(element);
                    if (name != null) {
                        old.put(name, element);
                    }
                }
            }

            for (Node node : nodes) {
                if (node.getNodeType() == Node.ELEMENT_NODE) {
                    Element element = (Element) node;
                    String name = getResourceId(element);
                    Node replace = name != null ? old.get(name) : null;
                    if (replace != null) {
                        // There is an existing item with the same id: just replace it
                        // ACTUALLY -- let's NOT change it.
                        // Let's say you've used the activity wizard once, and it
                        // emits some configuration parameter as a resource that
                        // it depends on, say "padding". Then the user goes and
                        // tweaks the padding to some other number.
                        // Now running the wizard a *second* time for some new activity,
                        // we should NOT go and set the value back to the template's
                        // default!
                        //root.replaceChild(node, replace);

                        // ... ON THE OTHER HAND... What if it's a parameter class
                        // (where the template rewrites a common attribute). Here it's
                        // really confusing if the new parameter is not set. This is
                        // really an error in the template, since we shouldn't have conflicts
                        // like that, but we need to do something to help track this down.
                        AdtPlugin.log(null,
                                "Warning: Ignoring name conflict in resource file for name %1$s",
                                name);
                    } else {
                        root.appendChild(node);
                        modified = true;
                    }
                }
            }
        } else {
            // In other file types, such as layouts, just append all the new content
            // at the end.
            for (Node node : nodes) {
                root.appendChild(node);
                modified = true;
            }
        }
        return modified;
    }

    /** Merges the given manifest fragment into the given manifest file */
    private boolean mergeManifest(Document currentManifest, Document fragment) {
        ManifestMerger merger = new ManifestMerger(AdtPlugin.getDefault());
        return currentManifest != null && fragment != null
                && merger.process(currentManifest, fragment);
    }

    /**
     * Makes a backup of the given file, if it exists, by renaming it to name~
     * (and removing an old name~ file if it exists)
     */
    private static boolean makeBackup(File file) {
        if (!file.exists()) {
            return true;
        }
        if (file.isDirectory()) {
            return false;
        }

        File backupFile = new File(file.getParentFile(), file.getName() + '~');
        if (backupFile.exists()) {
            backupFile.delete();
        }
        return file.renameTo(backupFile);
    }

    private static String getResourceId(Element element) {
        String name = element.getAttribute(ATTR_NAME);
        if (name == null) {
            name = element.getAttribute(ATTR_ID);
        }

        return name;
    }

    /** Instantiates the given template file into the given output file */
    private void instantiate(
            @NonNull final Configuration freemarker,
            @NonNull final Map<String, Object> paramMap,
            @NonNull String relativeFrom,
            @NonNull File to) throws IOException, TemplateException {
        File parentFile = to.getParentFile();
        if (!parentFile.exists()) {
            parentFile.mkdirs();
        }

        // For now, treat extension-less files as directories... this isn't quite right
        // so I should refine this! Maybe with a unique attribute in the template file?
        boolean isDirectory = relativeFrom.indexOf('.') == -1;
        if (isDirectory) {
            // It's a directory
            copyBundledResource(relativeFrom, to);
        } else {
            File from = getFullPath(relativeFrom);
            mLoader.setTemplateFile(from);
            Template template = freemarker.getTemplate(from.getName());
            Writer out = new StringWriter(1024);
            template.process(paramMap, out);
            out.flush();
            String contents = out.toString();

            if (relativeFrom.endsWith(DOT_XML)) {
                XmlFormatStyle formatStyle = XmlFormatStyle.getForFile(new Path(to.getPath()));
                XmlFormatPreferences prefs = XmlFormatPreferences.create();
                contents = XmlPrettyPrinter.prettyPrint(contents, prefs, formatStyle, null);
            }

            writeString(to, contents, true);
        }
    }

    /**
     * Returns the list of files to open when the template has been created
     *
     * @return the list of files to open
     */
    @NonNull
    public List<String> getFilesToOpen() {
        return mOpen;
    }

    /** Copy a bundled resource (part of the plugin .jar file) into the given file system path */
    private final void copyBundledResource(String relativeFrom, File output) throws IOException {
        File from = getFullPath(relativeFrom);

        // Local file copy? (Only used for the template-development wizard)
        if (!mRootPath.getPath().startsWith(TEMPLATE_PREFIX)) {
            copy(from, output);
            return;
        }

        String resourcePath = from.getPath();
        CodeSource source = TemplateHandler.class.getProtectionDomain().getCodeSource();
        if (source != null) {
            URL location = source.getLocation();
            try {
                URI locationUri = location.toURI();
                File locationFile = new File(locationUri);
                if (!locationUri.getPath().endsWith(DOT_JAR)) {
                    // Plain file; e.g. when running out of Eclipse plugin in
                    // Eclipse; it uses the bin/ folder instead of running out of a jar
                    File sourceFile = new File(locationFile, resourcePath);
                    copy(sourceFile, output);
                    return;
                }

                // Copy out of jar file
                JarFile jarFile = new JarFile(locationFile);
                int chopIndex = resourcePath.length() + 1;
                for (final Enumeration<JarEntry> e = jarFile.entries(); e.hasMoreElements();) {
                    final JarEntry entry = e.nextElement();
                    if (entry.getName().startsWith(resourcePath)) {
                        final String filename = entry.getName().substring(chopIndex);
                        assert entry.getName().charAt(resourcePath.length()) == '/';
                        final File file = new File(output, filename);
                        if (!entry.isDirectory()) {
                            // Copy stream
                            InputStream in = jarFile.getInputStream(entry);
                            try {
                                byte[] data = ByteStreams.toByteArray(in);
                                writeBytes(output, data, true);
                            } finally {
                                in.close();
                            }
                        } else {
                            // Create directory
                            if (!file.exists() && !file.mkdirs()) {
                                throw new IOException("Could not create directory " + file);
                            }
                        }
                    }
                }
            } catch (Exception e) {
                 AdtPlugin.log(e, null);
            }
        }
    }

    /** Returns true if the given file contains the given bytes */
    private static boolean isIdentical(@Nullable byte[] data, @NonNull File dest)
            throws IOException {
        assert dest.isFile();
        byte[] existing = Files.toByteArray(dest);
        return Arrays.equals(existing, data);
    }

    /**
     * Copies the given source file into the given destination file (where the
     * source is allowed to be a directory, in which case the whole directory is
     * copied recursively)
     */
    private void copy(File src, File dest) throws IOException {
        if (src.isDirectory()){
            if (!dest.exists() && !dest.mkdirs()) {
                throw new IOException("Could not create directory " + dest);
            }
            File[] children = src.listFiles();
            if (children != null) {
                for (File child : children) {
                    copy(child, new File(dest, child.getName()));
                }
            }
        } else {
            if (dest.exists() && isIdentical(Files.toByteArray(src), dest)) {
                return;
            }
            if (!canOverwrite(dest)) {
                return;
            }

            File parent = dest.getParentFile();
            if (parent != null && !parent.exists()) {
                parent.mkdirs();
            }
            Files.copy(src, dest);
        }
    }

    /**
     * A custom {@link TemplateLoader} which locates and provides templates
     * within the plugin .jar file
     */
    private static final class MyTemplateLoader implements TemplateLoader {
        private String mPrefix;

        public void setPrefix(String prefix) {
            mPrefix = prefix;
        }

        public void setTemplateFile(File file) {
            setTemplateParent(file.getParentFile());
        }

        public void setTemplateParent(File parent) {
            mPrefix = parent.getPath();
        }

        @Override
        public Reader getReader(Object templateSource, String encoding) throws IOException {
            URL url = (URL) templateSource;
            return new InputStreamReader(url.openStream(), encoding);
        }

        @Override
        public long getLastModified(Object templateSource) {
            return 0;
        }

        @Override
        public Object findTemplateSource(String name) throws IOException {
            String path = mPrefix != null ? mPrefix + '/' + name : name;
            URL resource = TemplateHandler.class.getResource(path);

            // Support for local files during template development
            if (resource == null && mPrefix != null && !mPrefix.startsWith(TEMPLATE_PREFIX)) {
                File file = new File(path);
                if (file.exists()) {
                    return file.toURI().toURL();
                }
            }

            return resource;
        }

        @Override
        public void closeTemplateSource(Object templateSource) throws IOException {
        }
    }
}