1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Eclipse Public License, Version 1.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.eclipse.org/org/documents/epl-v10.php
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 package com.android.ide.eclipse.adt.internal.wizards.templates;
17 
18 import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectPage.ACTIVITY_NAME_SUFFIX;
19 import static com.android.ide.eclipse.adt.internal.wizards.templates.NewProjectPage.LAYOUT_NAME_PREFIX;
20 
21 import com.android.ide.eclipse.adt.AdtUtils;
22 
23 import freemarker.template.SimpleScalar;
24 import freemarker.template.TemplateMethodModel;
25 import freemarker.template.TemplateModel;
26 import freemarker.template.TemplateModelException;
27 
28 import java.util.List;
29 
30 /**
31  * Method invoked by FreeMarker to convert an Activity class name into
32  * a suitable layout name.
33  */
34 public class FmActivityToLayoutMethod implements TemplateMethodModel {
35     @Override
exec(List args)36     public TemplateModel exec(List args) throws TemplateModelException {
37         if (args.size() != 1) {
38             throw new TemplateModelException("Wrong arguments");
39         }
40 
41         String activityName = args.get(0).toString();
42 
43         if (activityName.isEmpty()) {
44             return new SimpleScalar("");
45         }
46 
47         // Strip off the end portion of the activity name. The user might be typing
48         // the activity name such that only a portion has been entered so far (e.g.
49         // "MainActivi") and we want to chop off that portion too such that we don't
50         // offer a layout name partially containing the activity suffix (e.g. "main_activi").
51         int suffixStart = activityName.lastIndexOf(ACTIVITY_NAME_SUFFIX.charAt(0));
52         if (suffixStart != -1 && activityName.regionMatches(suffixStart, ACTIVITY_NAME_SUFFIX, 0,
53                 activityName.length() - suffixStart)) {
54             activityName = activityName.substring(0, suffixStart);
55         }
56         assert !activityName.endsWith(ACTIVITY_NAME_SUFFIX) : activityName;
57 
58         // Convert CamelCase convention used in activity class names to underlined convention
59         // used in layout name:
60         String name = LAYOUT_NAME_PREFIX + AdtUtils.camelCaseToUnderlines(activityName);
61 
62         return new SimpleScalar(name);
63     }
64 }