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 20 import com.android.ide.eclipse.adt.AdtUtils; 21 22 import freemarker.template.SimpleScalar; 23 import freemarker.template.TemplateMethodModel; 24 import freemarker.template.TemplateModel; 25 import freemarker.template.TemplateModelException; 26 27 import java.util.List; 28 29 /** 30 * Similar to {@link FmCamelCaseToUnderscoreMethod}, but strips off common class 31 * suffixes such as "Activity", "Fragment", etc. 32 */ 33 public class FmClassNameToResourceMethod implements TemplateMethodModel { 34 @Override exec(List args)35 public TemplateModel exec(List args) throws TemplateModelException { 36 if (args.size() != 1) { 37 throw new TemplateModelException("Wrong arguments"); 38 } 39 40 String name = args.get(0).toString(); 41 42 if (name.isEmpty()) { 43 return new SimpleScalar(""); 44 } 45 46 name = stripSuffix(name, ACTIVITY_NAME_SUFFIX); 47 name = stripSuffix(name, "Fragment"); //$NON-NLS-1$ 48 name = stripSuffix(name, "Service"); //$NON-NLS-1$ 49 name = stripSuffix(name, "Provider"); //$NON-NLS-1$ 50 51 return new SimpleScalar(AdtUtils.camelCaseToUnderlines(name)); 52 } 53 54 // Strip off the end portion of the activity name. The user might be typing 55 // the activity name such that only a portion has been entered so far (e.g. 56 // "MainActivi") and we want to chop off that portion too such that we don't stripSuffix(String name, String suffix)57 private static String stripSuffix(String name, String suffix) { 58 int suffixStart = name.lastIndexOf(suffix.charAt(0)); 59 if (suffixStart != -1 && name.regionMatches(suffixStart, suffix, 0, 60 name.length() - suffixStart)) { 61 name = name.substring(0, suffixStart); 62 } 63 assert !name.endsWith(suffix) : name; 64 65 return name; 66 } 67 }