From fe4d62604b15af4cda24bcebad51f87474fed9e6 Mon Sep 17 00:00:00 2001 From: jsurfer Date: Thu, 23 Sep 2004 19:45:15 +0000 Subject: [PATCH] added first version of codetemplates (needs to fix some bugs) --- net.sourceforge.phpeclipse/plugin.xml | 18 +- .../phpdt/internal/core/builder/PHPBuilder.java | 11 +- .../codemanipulation/CodeGenerationSettings.java | 44 + .../corext/codemanipulation/StubUtility.java | 1408 ++++++++++++++------ .../corext/template/php/CodeTemplateContext.java | 2 +- .../phpdt/internal/ui/PHPUIMessages.properties | 14 + .../sourceforge/phpdt/internal/ui/PHPUIStatus.java | 10 +- .../internal/ui/preferences/CodeTemplateBlock.java | 514 +++++++ .../ui/preferences/CodeTemplatePreferencePage.java | 105 ++ .../ui/text/spelling/SpellReconcileStrategy.java | 2 +- .../net/sourceforge/phpdt/ui/CodeGeneration.java | 241 ++++ .../sourceforge/phpdt/ui/PreferenceConstants.java | 16 +- .../phpdt/ui/wizards/NewTypeWizardPage.java | 85 +- .../sourceforge/phpeclipse/PHPeclipsePlugin.java | 3 +- .../phpeclipse/wizards/PHPFileWizard.java | 51 +- .../templates/default-codetemplates.xml | 13 +- .../templates/default-templates.properties | 2 +- 17 files changed, 2086 insertions(+), 453 deletions(-) create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/codemanipulation/CodeGenerationSettings.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java create mode 100644 net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java diff --git a/net.sourceforge.phpeclipse/plugin.xml b/net.sourceforge.phpeclipse/plugin.xml index a767b83..b82edda 100644 --- a/net.sourceforge.phpeclipse/plugin.xml +++ b/net.sourceforge.phpeclipse/plugin.xml @@ -1396,6 +1396,18 @@ id="net.sourceforge.phpeclipse.preference.PHPEclipsePreferencePage"> + + + - + --> - --> + @@ -1801,7 +1813,7 @@ - + GenStubSettings) -// * @param imports Imports required by the stub are added to the imports structure. If imports structure is null -// * all type names are qualified. -// * @throws JavaModelException -// */ -// public static String genStub(String destTypeName, IMethod method, GenStubSettings settings, IImportsStructure imports) throws JavaModelException { -// IType declaringtype= method.getDeclaringType(); -// StringBuffer buf= new StringBuffer(); -// String methodName= method.getElementName(); -// String[] paramTypes= method.getParameterTypes(); -// String[] paramNames= method.getParameterNames(); -// String[] excTypes= method.getExceptionTypes(); -// String retTypeSig= method.getReturnType(); -// int flags= method.getFlags(); -// boolean isConstructor= method.isConstructor(); -// -// int lastParam= paramTypes.length -1; -// -// -// if (settings.createComments) { -// if (isConstructor) { -// String desc= "Constructor for " + destTypeName; //$NON-NLS-1$ -// genJavaDocStub(desc, paramNames, Signature.SIG_VOID, excTypes, buf); -// } else { -// // php doc -// if (settings.methodOverwrites) { -// boolean isDeprecated= Flags.isDeprecated(flags); -// genJavaDocSeeTag(declaringtype, methodName, paramTypes, settings.createNonJavadocComments, isDeprecated, buf); -// } else { -// // generate a default php doc comment -// String desc= "Method " + methodName; //$NON-NLS-1$ -// genJavaDocStub(desc, paramNames, retTypeSig, excTypes, buf); -// } + public static class GenStubSettings extends CodeGenerationSettings { + + public boolean callSuper; + public boolean methodOverwrites; + public boolean noBody; + public int methodModifiers; + + public GenStubSettings(CodeGenerationSettings settings) { + settings.setSettings(this); + methodModifiers= -1; + } + + } + + private static final String[] EMPTY= new String[0]; + + /** + * Generates a method stub including the method comment. Given a template + * method, a stub with the same signature will be constructed so it can be + * added to a type. The method body will be empty or contain a return or + * super call. + * @param destTypeName The name of the type to which the method will be + * added to + * @param method A method template (method belongs to different type than the parent) + * @param definingType The type that defines the method. + * @param settings Options as defined above (GenStubSettings) + * @param imports Imports required by the stub are added to the imports structure. If imports structure is null + * all type names are qualified. + * @throws JavaModelException + */ + public static String genStub(ICompilationUnit cu, String destTypeName, IMethod method, IType definingType, GenStubSettings settings) throws CoreException { + //IImportsStructure imports) throws CoreException { + String methName= method.getElementName(); + String[] paramNames= suggestArgumentNames(method.getJavaProject(), method.getParameterNames()); + String returnType= method.isConstructor() ? null : method.getReturnType(); + String lineDelimiter= String.valueOf('\n'); // reformatting required + + + StringBuffer buf= new StringBuffer(); + // add method comment + if (settings.createComments && cu != null) { + IMethod overridden= null; + if (settings.methodOverwrites && returnType != null) { + overridden= JavaModelUtil.findMethod(methName, method.getParameterTypes(), false, definingType.getMethods()); + } + String comment= getMethodComment(cu, destTypeName, methName, paramNames, method.getExceptionTypes(), returnType, overridden, lineDelimiter); + if (comment != null) { + buf.append(comment); + } else { + buf.append("/**").append(lineDelimiter); //$NON-NLS-1$ + buf.append(" *").append(lineDelimiter); //$NON-NLS-1$ + buf.append(" */").append(lineDelimiter); //$NON-NLS-1$ + } + buf.append(lineDelimiter); + } + // add method declaration + String bodyContent= null; + if (!settings.noBody) { + String bodyStatement= getDefaultMethodBodyStatement(methName, paramNames, returnType, settings.callSuper); + bodyContent= getMethodBodyContent(returnType == null, method.getJavaProject(), destTypeName, methName, bodyStatement, lineDelimiter); + if (bodyContent == null) { + bodyContent= ""; //$NON-NLS-1$ + } + } + int flags= settings.methodModifiers; + if (flags == -1) { + flags= method.getFlags(); + } + + genMethodDeclaration(destTypeName, method, flags, bodyContent, buf); // imports, buf); + return buf.toString(); + } + + /** + * Generates a method stub not including the method comment. Given a + * template method and the body content, a stub with the same signature will + * be constructed so it can be added to a type. + * @param destTypeName The name of the type to which the method will be + * added to + * @param method A method template (method belongs to different type than the parent) + * @param bodyContent Content of the body + * @param imports Imports required by the stub are added to the imports + * structure. If imports structure is null all type names are + * qualified. + * @param buf The buffer to append the gerenated code. + * @throws JavaModelException + */ + public static void genMethodDeclaration(String destTypeName, IMethod method, String bodyContent, StringBuffer buf) throws CoreException { // IImportsStructure imports, StringBuffer buf) throws CoreException { + genMethodDeclaration(destTypeName, method, method.getFlags(), bodyContent, buf); + } + + /** + * Generates a method stub not including the method comment. Given a + * template method and the body content, a stub with the same signature will + * be constructed so it can be added to a type. + * @param destTypeName The name of the type to which the method will be + * added to + * @param method A method template (method belongs to different type than the parent) + * @param bodyContent Content of the body + * @param imports Imports required by the stub are added to the imports + * structure. If imports structure is null all type names are + * qualified. + * @param buf The buffer to append the gerenated code. + * @throws JavaModelException + */ + public static void genMethodDeclaration(String destTypeName, IMethod method, int flags, String bodyContent, StringBuffer buf) throws CoreException { + //IImportsStructure imports, StringBuffer buf) throws CoreException { + IType parentType= method.getDeclaringType(); + String methodName= method.getElementName(); + String[] paramTypes= method.getParameterTypes(); + String[] paramNames= suggestArgumentNames(parentType.getJavaProject(), method.getParameterNames()); + + String[] excTypes= method.getExceptionTypes(); + + boolean isConstructor= method.isConstructor(); + String retTypeSig= isConstructor ? null : method.getReturnType(); + + int lastParam= paramTypes.length -1; + + if (Flags.isPublic(flags) || (parentType.isInterface() && bodyContent != null)) { + buf.append("public "); //$NON-NLS-1$ + } else if (Flags.isProtected(flags)) { + buf.append("protected "); //$NON-NLS-1$ + } else if (Flags.isPrivate(flags)) { + buf.append("private "); //$NON-NLS-1$ + } +// if (Flags.isSynchronized(flags)) { +// buf.append("synchronized "); //$NON-NLS-1$ +// } +// if (Flags.isVolatile(flags)) { +// buf.append("volatile "); //$NON-NLS-1$ // } -// buf.append('\n'); -// } -// -// if (Flags.isPublic(flags) || isConstructor || (declaringtype.isInterface() && !settings.noBody)) { -// buf.append("public "); //$NON-NLS-1$ -// } else if (Flags.isProtected(flags)) { -// buf.append("protected "); //$NON-NLS-1$ -// } else if (Flags.isPrivate(flags)) { -// buf.append("private "); //$NON-NLS-1$ -// } -// if (Flags.isSynchronized(flags)) { -// buf.append("synchronized "); //$NON-NLS-1$ -// } -// if (Flags.isVolatile(flags)) { -// buf.append("volatile "); //$NON-NLS-1$ -// } -// if (Flags.isStrictfp(flags)) { -// buf.append("strictfp "); //$NON-NLS-1$ +// if (Flags.isStrictfp(flags)) { +// buf.append("strictfp "); //$NON-NLS-1$ +// } + if (Flags.isStatic(flags)) { + buf.append("static "); //$NON-NLS-1$ + } + + if (isConstructor) { + buf.append(destTypeName); + } else { + String retTypeFrm; + if (!isPrimitiveType(retTypeSig)) { + retTypeFrm= resolveAndAdd(retTypeSig, parentType); + } else { + retTypeFrm= Signature.toString(retTypeSig); + } + buf.append(retTypeFrm); + buf.append(' '); + buf.append(methodName); + } + buf.append('('); + for (int i= 0; i <= lastParam; i++) { + String paramTypeSig= paramTypes[i]; + String paramTypeFrm; + + if (!isPrimitiveType(paramTypeSig)) { + paramTypeFrm= resolveAndAdd(paramTypeSig, parentType); + } else { + paramTypeFrm= Signature.toString(paramTypeSig); + } + buf.append(paramTypeFrm); + buf.append(' '); + buf.append(paramNames[i]); + if (i < lastParam) { + buf.append(", "); //$NON-NLS-1$ + } + } + buf.append(')'); + + int lastExc= excTypes.length - 1; + if (lastExc >= 0) { + buf.append(" throws "); //$NON-NLS-1$ + for (int i= 0; i <= lastExc; i++) { + String excTypeSig= excTypes[i]; + String excTypeFrm= resolveAndAdd(excTypeSig, parentType); + buf.append(excTypeFrm); + if (i < lastExc) { + buf.append(", "); //$NON-NLS-1$ + } + } + } + if (bodyContent == null) { + buf.append(";\n\n"); //$NON-NLS-1$ + } else { + buf.append(" {\n\t"); //$NON-NLS-1$ + if ((bodyContent != null) && (bodyContent.length() > 0)) { + buf.append(bodyContent); + buf.append('\n'); + } + buf.append("}\n"); //$NON-NLS-1$ + } + } + + public static String getDefaultMethodBodyStatement(String methodName, String[] paramNames, String retTypeSig, boolean callSuper) { + StringBuffer buf= new StringBuffer(); + if (callSuper) { + if (retTypeSig != null) { + if (!Signature.SIG_VOID.equals(retTypeSig)) { + buf.append("return "); //$NON-NLS-1$ + } + buf.append("super."); //$NON-NLS-1$ + buf.append(methodName); + } else { + buf.append("super"); //$NON-NLS-1$ + } + buf.append('('); + for (int i= 0; i < paramNames.length; i++) { + if (i > 0) { + buf.append(", "); //$NON-NLS-1$ + } + buf.append(paramNames[i]); + } + buf.append(");"); //$NON-NLS-1$ + } else { + if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { + if (!isPrimitiveType(retTypeSig) || Signature.getArrayCount(retTypeSig) > 0) { + buf.append("return null;"); //$NON-NLS-1$ + } else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) { + buf.append("return false;"); //$NON-NLS-1$ + } else { + buf.append("return 0;"); //$NON-NLS-1$ + } + } + } + return buf.toString(); + } + + public static String getMethodBodyContent(boolean isConstructor, IJavaProject project, String destTypeName, String methodName, String bodyStatement, String lineDelimiter) throws CoreException { + String templateName= isConstructor ? CodeTemplateContextType.CONSTRUCTORSTUB : CodeTemplateContextType.METHODSTUB; + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return bodyStatement; + } + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName); + context.setVariable(CodeTemplateContextType.BODY_STATEMENT, bodyStatement); + String str= evaluateTemplate(context, template); + if (str == null && !Strings.containsOnlyWhitespaces(bodyStatement)) { + return bodyStatement; + } + return str; + } + + public static String getGetterMethodBodyContent(IJavaProject project, String destTypeName, String methodName, String fieldName, String lineDelimiter) throws CoreException { + String templateName= CodeTemplateContextType.GETTERSTUB; + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + + return evaluateTemplate(context, template); + } + + public static String getSetterMethodBodyContent(IJavaProject project, String destTypeName, String methodName, String fieldName, String paramName, String lineDelimiter) throws CoreException { + String templateName= CodeTemplateContextType.SETTERSTUB; + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, destTypeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldName); + context.setVariable(CodeTemplateContextType.PARAM, paramName); + + return evaluateTemplate(context, template); + } + + public static String getCatchBodyContent(ICompilationUnit cu, String exceptionType, String variableName, String lineDelimiter) throws CoreException { + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.CATCHBLOCK); + if (template == null) { + return null; + } + + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setVariable(CodeTemplateContextType.EXCEPTION_TYPE, exceptionType); + context.setVariable(CodeTemplateContextType.EXCEPTION_VAR, variableName); //$NON-NLS-1$ + return evaluateTemplate(context, template); + } + + /** + * @see org.eclipse.jdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String) + */ + public static String getCompilationUnitContent(ICompilationUnit cu, String typeComment, String typeContent, String lineDelimiter) throws CoreException { + IPackageFragment pack= (IPackageFragment) cu.getParent(); + String packDecl= pack.isDefaultPackage() ? "" : "package " + pack.getElementName() + ';'; //$NON-NLS-1$ //$NON-NLS-2$ + + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.NEWTYPE); + if (template == null) { + return null; + } + + IJavaProject project= cu.getJavaProject(); + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), project, lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.PACKAGE_DECLARATION, packDecl); + context.setVariable(CodeTemplateContextType.TYPE_COMMENT, typeComment != null ? typeComment : ""); //$NON-NLS-1$ + context.setVariable(CodeTemplateContextType.TYPE_DECLARATION, typeContent); + context.setVariable(CodeTemplateContextType.TYPENAME, Signature.getQualifier(cu.getElementName())); + return evaluateTemplate(context, template); + } + + /* + * @see org.eclipse.jdt.ui.CodeGeneration#getTypeComment(ICompilationUnit, String, String) + */ + public static String getTypeComment(ICompilationUnit cu, String typeQualifiedName, String lineDelim) throws CoreException { + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.TYPECOMMENT); + if (template == null) { + return null; + } + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelim); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, Signature.getQualifier(typeQualifiedName)); + context.setVariable(CodeTemplateContextType.TYPENAME, Signature.getSimpleName(typeQualifiedName)); + return evaluateTemplate(context, template); + } + +// private static String[] getParameterTypesQualifiedNames(IMethodBinding binding) { +// ITypeBinding[] typeBindings= binding.getParameterTypes(); +// String[] result= new String[typeBindings.length]; +// for (int i= 0; i < result.length; i++) { +// result[i]= typeBindings[i].getQualifiedName(); +// } +// return result; // } -// if (Flags.isStatic(flags)) { -// buf.append("static "); //$NON-NLS-1$ -// } -// -// if (isConstructor) { -// buf.append(destTypeName); -// } else { -// String retTypeFrm; -// if (!isPrimitiveType(retTypeSig)) { -// retTypeFrm= resolveAndAdd(retTypeSig, declaringtype, imports); + + private static String getSeeTag(String declaringClassQualifiedName, String methodName, String[] parameterTypesQualifiedNames) { + StringBuffer buf= new StringBuffer(); + buf.append("@see "); //$NON-NLS-1$ + buf.append(declaringClassQualifiedName); + buf.append('#'); + buf.append(methodName); + buf.append('('); + for (int i= 0; i < parameterTypesQualifiedNames.length; i++) { + if (i > 0) { + buf.append(", "); //$NON-NLS-1$ + } + buf.append(parameterTypesQualifiedNames[i]); + } + buf.append(')'); + return buf.toString(); + } + + private static String getSeeTag(IMethod overridden) throws JavaModelException { + IType declaringType= overridden.getDeclaringType(); + StringBuffer buf= new StringBuffer(); + buf.append("@see "); //$NON-NLS-1$ + buf.append(declaringType.getFullyQualifiedName('.')); + buf.append('#'); + buf.append(overridden.getElementName()); + buf.append('('); + String[] paramTypes= overridden.getParameterTypes(); + for (int i= 0; i < paramTypes.length; i++) { + if (i > 0) { + buf.append(", "); //$NON-NLS-1$ + } + String curr= paramTypes[i]; + buf.append(JavaModelUtil.getResolvedTypeName(curr, declaringType)); + int arrayCount= Signature.getArrayCount(curr); + while (arrayCount > 0) { + buf.append("[]"); //$NON-NLS-1$ + arrayCount--; + } + } + buf.append(')'); + return buf.toString(); + } + + /** + * @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(IMethod,IMethod,String) + */ + public static String getMethodComment(IMethod method, IMethod overridden, String lineDelimiter) throws CoreException { + String retType= method.isConstructor() ? null : method.getReturnType(); + String[] paramNames= method.getParameterNames(); + + return getMethodComment(method.getCompilationUnit(), method.getDeclaringType().getElementName(), + method.getElementName(), paramNames, method.getExceptionTypes(), retType, overridden, lineDelimiter); + } + + /** + * @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, String, String[], String[], String, IMethod, String) + */ + public static String getMethodComment(ICompilationUnit cu, String typeName, String methodName, String[] paramNames, String[] excTypeSig, String retTypeSig, IMethod overridden, String lineDelimiter) throws CoreException { + String templateName= CodeTemplateContextType.METHODCOMMENT; + if (retTypeSig == null) { + templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT; + } else if (overridden != null) { + templateName= CodeTemplateContextType.OVERRIDECOMMENT; + } + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); + + if (retTypeSig != null) { + context.setVariable(CodeTemplateContextType.RETURN_TYPE, Signature.toString(retTypeSig)); + } + if (overridden != null) { + context.setVariable(CodeTemplateContextType.SEE_TAG, getSeeTag(overridden)); + } + TemplateBuffer buffer; + try { + buffer= context.evaluate(template); + } catch (BadLocationException e) { + throw new CoreException(Status.CANCEL_STATUS); + } catch (TemplateException e) { + throw new CoreException(Status.CANCEL_STATUS); + } + if (buffer == null) { + return null; + } + + String str= buffer.getString(); + if (Strings.containsOnlyWhitespaces(str)) { + return null; + } + TemplateVariable position= findTagVariable(buffer); // look if Javadoc tags have to be added + if (position == null) { + return str; + } + + IDocument textBuffer= new Document(str); + String[] exceptionNames= new String[excTypeSig.length]; + for (int i= 0; i < excTypeSig.length; i++) { + exceptionNames[i]= Signature.toString(excTypeSig[i]); + } + String returnType= retTypeSig != null ? Signature.toString(retTypeSig) : null; + int[] tagOffsets= position.getOffsets(); + for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first + try { + insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, false, lineDelimiter); + } catch (BadLocationException e) { + throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, e)); + } + } + return textBuffer.get(); + } + + public static String getFieldComment(ICompilationUnit cu, String typeName, String fieldName, String lineDelimiter) throws CoreException { + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.FIELDCOMMENT); + if (template == null) { + return null; + } + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, typeName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + + return evaluateTemplate(context, template); + } + + + /** + * @see org.eclipse.jdt.ui.CodeGeneration#getSetterComment(ICompilationUnit, String, String, String, String, String, String, String) + */ + public static String getSetterComment(ICompilationUnit cu, String typeName, String methodName, String fieldName, String fieldType, String paramName, String bareFieldName, String lineDelimiter) throws CoreException { + String templateName= CodeTemplateContextType.SETTERCOMMENT; + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); + context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName); + context.setVariable(CodeTemplateContextType.PARAM, paramName); + + return evaluateTemplate(context, template); + } + + /** + * @see org.eclipse.jdt.ui.CodeGeneration#getGetterComment(ICompilationUnit, String, String, String, String, String, String) + */ + public static String getGetterComment(ICompilationUnit cu, String typeName, String methodName, String fieldName, String fieldType, String bareFieldName, String lineDelimiter) throws CoreException { + String templateName= CodeTemplateContextType.GETTERCOMMENT; + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); + if (template == null) { + return null; + } + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); + context.setCompilationUnitVariables(cu); + context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); + context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, methodName); + context.setVariable(CodeTemplateContextType.FIELD, fieldName); + context.setVariable(CodeTemplateContextType.FIELD_TYPE, fieldType); + context.setVariable(CodeTemplateContextType.BARE_FIELD_NAME, bareFieldName); + + return evaluateTemplate(context, template); + } + + public static String evaluateTemplate(CodeTemplateContext context, Template template) throws CoreException { + TemplateBuffer buffer; + try { + buffer= context.evaluate(template); + } catch (BadLocationException e) { + throw new CoreException(Status.CANCEL_STATUS); + } catch (TemplateException e) { + throw new CoreException(Status.CANCEL_STATUS); + } + if (buffer == null) + return null; + String str= buffer.getString(); + if (Strings.containsOnlyWhitespaces(str)) { + return null; + } + return str; + } + + /** + * @see org.eclipse.jdt.ui.CodeGeneration#getMethodComment(ICompilationUnit, String, MethodDeclaration, IMethodBinding, String) + */ +// public static String getMethodComment(ICompilationUnit cu, String typeName, IMethodBinding overridden, String lineDelimiter) throws CoreException { +// if (overridden != null) { +// String declaringClassQualifiedName= overridden.getDeclaringClass().getQualifiedName(); +// String[] parameterTypesQualifiedNames= getParameterTypesQualifiedNames(overridden); +// return getMethodComment(cu, typeName, decl, true, overridden.isDeprecated(), declaringClassQualifiedName, parameterTypesQualifiedNames, lineDelimiter); // } else { -// retTypeFrm= Signature.toString(retTypeSig); +// return getMethodComment(cu, typeName, decl, false, false, null, null, lineDelimiter); // } -// buf.append(retTypeFrm); -// buf.append(' '); -// buf.append(methodName); // } -// buf.append('('); -// for (int i= 0; i <= lastParam; i++) { -// String paramTypeSig= paramTypes[i]; -// String paramTypeFrm; + + /** + * Returns the comment for a method using the comment code templates. + * null is returned if the template is empty. + * @param cu The compilation unit to which the method belongs + * @param typeName Name of the type to which the method belongs. + * @param decl The AST MethodDeclaration node that will be added as new + * method. + * @param isOverridden true iff decl overrides another method + * @param isDeprecated true iff the method that decl overrides is deprecated. + * Note: it must not be true if isOverridden is false. + * @param declaringClassQualifiedName Fully qualified name of the type in which the overriddden + * method (if any exists) in declared. If isOverridden is false, this is ignored. + * @param parameterTypesQualifiedNames Fully qualified names of parameter types of the type in which the overriddden + * method (if any exists) in declared. If isOverridden is false, this is ignored. + * @return String Returns the method comment or null if the + * configured template is empty. + * (formatting required) + * @throws CoreException + */ +// public static String getMethodComment(ICompilationUnit cu, String typeName, MethodDeclaration decl, boolean isOverridden, boolean isDeprecated, String declaringClassQualifiedName, String[] parameterTypesQualifiedNames, String lineDelimiter) throws CoreException { +// String templateName= CodeTemplateContextType.METHODCOMMENT; +// if (decl.isConstructor()) { +// templateName= CodeTemplateContextType.CONSTRUCTORCOMMENT; +// } else if (isOverridden) { +// templateName= CodeTemplateContextType.OVERRIDECOMMENT; +// } +// Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(templateName); +// if (template == null) { +// return null; +// } +// CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), cu.getJavaProject(), lineDelimiter); +// context.setCompilationUnitVariables(cu); +// context.setVariable(CodeTemplateContextType.ENCLOSING_TYPE, typeName); +// context.setVariable(CodeTemplateContextType.ENCLOSING_METHOD, decl.getName().getIdentifier()); +// if (!decl.isConstructor()) { +// context.setVariable(CodeTemplateContextType.RETURN_TYPE, ASTNodes.asString(decl.getReturnType())); +// } +// if (isOverridden) { +// String methodName= decl.getName().getIdentifier(); +// context.setVariable(CodeTemplateContextType.SEE_TAG, getSeeTag(declaringClassQualifiedName, methodName, parameterTypesQualifiedNames)); +// } // -// if (!isPrimitiveType(paramTypeSig)) { -// paramTypeFrm= resolveAndAdd(paramTypeSig, declaringtype, imports); -// } else { -// paramTypeFrm= Signature.toString(paramTypeSig); +// TemplateBuffer buffer; +// try { +// buffer= context.evaluate(template); +// } catch (BadLocationException e) { +// throw new CoreException(Status.CANCEL_STATUS); +// } catch (TemplateException e) { +// throw new CoreException(Status.CANCEL_STATUS); // } -// buf.append(paramTypeFrm); -// buf.append(' '); -// buf.append(paramNames[i]); -// if (i < lastParam) { -// buf.append(", "); //$NON-NLS-1$ +// if (buffer == null) +// return null; +// String str= buffer.getString(); +// if (Strings.containsOnlyWhitespaces(str)) { +// return null; // } -// } -// buf.append(')'); -// -// int lastExc= excTypes.length - 1; -// if (lastExc >= 0) { -// buf.append(" throws "); //$NON-NLS-1$ -// for (int i= 0; i <= lastExc; i++) { -// String excTypeSig= excTypes[i]; -// String excTypeFrm= resolveAndAdd(excTypeSig, declaringtype, imports); -// buf.append(excTypeFrm); -// if (i < lastExc) { -// buf.append(", "); //$NON-NLS-1$ +// TemplateVariable position= findTagVariable(buffer); // look if Javadoc tags have to be added +// if (position == null) { +// return str; +// } +// +// IDocument textBuffer= new Document(str); +// List params= decl.parameters(); +// String[] paramNames= new String[params.size()]; +// for (int i= 0; i < params.size(); i++) { +// SingleVariableDeclaration elem= (SingleVariableDeclaration) params.get(i); +// paramNames[i]= elem.getName().getIdentifier(); +// } +// List exceptions= decl.thrownExceptions(); +// String[] exceptionNames= new String[exceptions.size()]; +// for (int i= 0; i < exceptions.size(); i++) { +// exceptionNames[i]= ASTNodes.getSimpleNameIdentifier((Name) exceptions.get(i)); +// } +// String returnType= !decl.isConstructor() ? ASTNodes.asString(decl.getReturnType()) : null; +// int[] tagOffsets= position.getOffsets(); +// for (int i= tagOffsets.length - 1; i >= 0; i--) { // from last to first +// try { +// insertTag(textBuffer, tagOffsets[i], position.getLength(), paramNames, exceptionNames, returnType, isDeprecated, lineDelimiter); +// } catch (BadLocationException e) { +// throw new CoreException(PHPUIStatus.createError(IStatus.ERROR, e)); // } // } +// return textBuffer.get(); // } -// if (settings.noBody) { -// buf.append(";\n\n"); //$NON-NLS-1$ -// } else { -// buf.append(" {\n\t"); //$NON-NLS-1$ -// if (!settings.callSuper) { -// if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { -// buf.append('\t'); -// if (!isPrimitiveType(retTypeSig) || Signature.getArrayCount(retTypeSig) > 0) { -// buf.append("return null;\n\t"); //$NON-NLS-1$ -// } else if (retTypeSig.equals(Signature.SIG_BOOLEAN)) { -// buf.append("return false;\n\t"); //$NON-NLS-1$ -// } else { -// buf.append("return 0;\n\t"); //$NON-NLS-1$ -// } -// } -// } else { -// buf.append('\t'); -// if (!isConstructor) { -// if (!Signature.SIG_VOID.equals(retTypeSig)) { -// buf.append("return "); //$NON-NLS-1$ -// } -// buf.append("super."); //$NON-NLS-1$ -// buf.append(methodName); + + private static TemplateVariable findTagVariable(TemplateBuffer buffer) { + TemplateVariable[] positions= buffer.getVariables(); + for (int i= 0; i < positions.length; i++) { + TemplateVariable curr= positions[i]; + if (CodeTemplateContextType.TAGS.equals(curr.getType())) { + return curr; + } + } + return null; + } + + private static void insertTag(IDocument textBuffer, int offset, int length, String[] paramNames, String[] exceptionNames, String returnType, boolean isDeprecated, String lineDelimiter) throws BadLocationException { + IRegion region= textBuffer.getLineInformationOfOffset(offset); + if (region == null) { + return; + } + String lineStart= textBuffer.get(region.getOffset(), offset - region.getOffset()); + + StringBuffer buf= new StringBuffer(); + for (int i= 0; i < paramNames.length; i++) { + if (buf.length() > 0) { + buf.append(lineDelimiter); buf.append(lineStart); + } + buf.append("@param "); buf.append(paramNames[i]); //$NON-NLS-1$ + } + if (returnType != null && !returnType.equals("void")) { //$NON-NLS-1$ + if (buf.length() > 0) { + buf.append(lineDelimiter); buf.append(lineStart); + } + buf.append("@return"); //$NON-NLS-1$ + } + if (exceptionNames != null) { + for (int i= 0; i < exceptionNames.length; i++) { + if (buf.length() > 0) { + buf.append(lineDelimiter); buf.append(lineStart); + } + buf.append("@throws "); buf.append(exceptionNames[i]); //$NON-NLS-1$ + } + } + if (isDeprecated) { + if (buf.length() > 0) { + buf.append(lineDelimiter); buf.append(lineStart); + } + buf.append("@deprecated"); //$NON-NLS-1$ + } + textBuffer.replace(offset, length, buf.toString()); + } + + private static boolean isPrimitiveType(String typeName) { + char first= Signature.getElementType(typeName).charAt(0); + return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); + } + + private static String resolveAndAdd(String refTypeSig, IType declaringType) throws JavaModelException {//, IImportsStructure imports) throws JavaModelException { + String resolvedTypeName= JavaModelUtil.getResolvedTypeName(refTypeSig, declaringType); + if (resolvedTypeName != null) { + StringBuffer buf= new StringBuffer(); +// if (imports != null) { +// buf.append(imports.addImport(resolvedTypeName)); // } else { -// buf.append("super"); //$NON-NLS-1$ + buf.append(resolvedTypeName); // } -// buf.append('('); -// for (int i= 0; i <= lastParam; i++) { -// buf.append(paramNames[i]); -// if (i < lastParam) { -// buf.append(", "); //$NON-NLS-1$ + int arrayCount= Signature.getArrayCount(refTypeSig); + for (int i= 0; i < arrayCount; i++) { + buf.append("[]"); //$NON-NLS-1$ + } + return buf.toString(); + } + return Signature.toString(refTypeSig); + } + + /** + * Finds a method in a list of methods. + * @return The found method or null, if nothing found + */ + private static IMethod findMethod(IMethod method, List allMethods) throws JavaModelException { + String name= method.getElementName(); + String[] paramTypes= method.getParameterTypes(); + boolean isConstructor= method.isConstructor(); + + for (int i= allMethods.size() - 1; i >= 0; i--) { + IMethod curr= (IMethod) allMethods.get(i); + if (JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, curr)) { + return curr; + } + } + return null; + } + + /** + * Creates needed constructors for a type. + * @param type The type to create constructors for + * @param supertype The type's super type + * @param settings Options for comment generation + * @param imports Required imports are added to the import structure. Structure can be null, types are qualified then. + * @return Returns the generated stubs or null if the creation has been canceled + */ +// public static String[] evalConstructors(IType type, IType supertype, IImportsStructure imports) throws CoreException { +// IMethod[] superMethods= supertype.getMethods(); +// String typeName= type.getElementName(); +// ICompilationUnit cu= type.getCompilationUnit(); +// IMethod[] methods= type.getMethods(); +// GenStubSettings genStubSettings= new GenStubSettings(settings); +// genStubSettings.callSuper= true; +// +// ArrayList newMethods= new ArrayList(superMethods.length); +// for (int i= 0; i < superMethods.length; i++) { +// IMethod curr= superMethods[i]; +// if (curr.isConstructor() && (JavaModelUtil.isVisibleInHierarchy(curr, type.getPackageFragment()))) { +// if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, methods) == null) { +// genStubSettings.methodModifiers= Flags.AccPublic | JdtFlags.clearAccessModifiers(curr.getFlags()); +// String newStub= genStub(cu, typeName, curr, curr.getDeclaringType(), genStubSettings, imports); +// newMethods.add(newStub); // } // } -// buf.append(");\n\t"); //$NON-NLS-1$ // } -// buf.append("}\n"); //$NON-NLS-1$ +// return (String[]) newMethods.toArray(new String[newMethods.size()]); // } -// return buf.toString(); -// } -// -// private static boolean isSet(int options, int flag) { -// return (options & flag) != 0; -// } -// -// private static boolean isPrimitiveType(String typeName) { -// char first= Signature.getElementType(typeName).charAt(0); -// return (first != Signature.C_RESOLVED && first != Signature.C_UNRESOLVED); -// } + + /** + * Returns all unimplemented constructors of a type including root type default + * constructors if there are no other superclass constructors unimplemented. + * @param type The type to create constructors for + * @return Returns the generated stubs or null if the creation has been canceled + */ +// public static IMethod[] getOverridableConstructors(IType type) throws CoreException { +// List constructorMethods= new ArrayList(); +// ITypeHierarchy hierarchy= type.newSupertypeHierarchy(null); +// IType supertype= hierarchy.getSuperclass(type); +// if (supertype == null) +// return (new IMethod[0]); // -// private static String resolveAndAdd(String refTypeSig, IType declaringType, IImportsStructure imports) throws JavaModelException { -// String resolvedTypeName= JavaModelUtil.getResolvedTypeName(refTypeSig, declaringType); -// if (resolvedTypeName != null) { -// StringBuffer buf= new StringBuffer(); -// if (imports != null) { -// buf.append(imports.addImport(resolvedTypeName)); -// } else { -// buf.append(resolvedTypeName); -// } -// int arrayCount= Signature.getArrayCount(refTypeSig); -// for (int i= 0; i < arrayCount; i++) { -// buf.append("[]"); //$NON-NLS-1$ -// } -// return buf.toString(); -// } -// return Signature.toString(refTypeSig); -// } -// -// /** -// * Generates a default JavaDoc comment stub for a method. -// */ -// public static void genJavaDocStub(String descr, String[] paramNames, String retTypeSig, String[] excTypeSigs, StringBuffer buf) { -// buf.append("/**\n"); //$NON-NLS-1$ -// buf.append(" * "); buf.append(descr); buf.append(".\n"); //$NON-NLS-2$ //$NON-NLS-1$ -// for (int i= 0; i < paramNames.length; i++) { -// buf.append(" * @param "); buf.append(paramNames[i]); buf.append('\n'); //$NON-NLS-1$ -// } -// if (retTypeSig != null && !retTypeSig.equals(Signature.SIG_VOID)) { -// String simpleName= Signature.getSimpleName(Signature.toString(retTypeSig)); -// buf.append(" * @return "); buf.append(simpleName); buf.append('\n'); //$NON-NLS-1$ -// } -// if (excTypeSigs != null) { -// for (int i= 0; i < excTypeSigs.length; i++) { -// String simpleName= Signature.getSimpleName(Signature.toString(excTypeSigs[i])); -// buf.append(" * @throws "); buf.append(simpleName); buf.append('\n'); //$NON-NLS-1$ -// } -// } -// buf.append(" */"); //$NON-NLS-1$ -// } -// -// /** -// * Generates a '@see' tag to the defined method. -// */ -// public static void genJavaDocSeeTag(IType declaringType, String methodName, String[] paramTypes, boolean nonJavaDocComment, boolean isDeprecated, StringBuffer buf) throws JavaModelException { -// String[] fullParamNames= new String[paramTypes.length]; -// for (int i= 0; i < paramTypes.length; i++) { -// fullParamNames[i]= JavaModelUtil.getResolvedTypeName(paramTypes[i], declaringType); -// } -// String fullTypeName= JavaModelUtil.getFullyQualifiedName(declaringType); -// -// genJavaDocSeeTag(fullTypeName, methodName, fullParamNames, nonJavaDocComment, isDeprecated, buf); -// } -// -// /** -// * Generates a '@see' tag to the defined method. -// */ -// public static void genJavaDocSeeTag(String fullyQualifiedTypeName, String methodName, String[] fullParamTypeNames, boolean nonJavaDocComment, boolean isDeprecated, StringBuffer buf) throws JavaModelException { -// // create a @see link -// buf.append("/*"); //$NON-NLS-1$ -// if (!nonJavaDocComment) { -// buf.append('*'); -// } else { -// buf.append(" (non-Javadoc)"); //$NON-NLS-1$ -// } -// buf.append("\n * @see "); //$NON-NLS-1$ -// buf.append(fullyQualifiedTypeName); -// buf.append('#'); -// buf.append(methodName); -// buf.append('('); -// for (int i= 0; i < fullParamTypeNames.length; i++) { -// if (i > 0) { -// buf.append(", "); //$NON-NLS-1$ +// IMethod[] superMethods= supertype.getMethods(); +// boolean constuctorFound= false; +// String typeName= type.getElementName(); +// IMethod[] methods= type.getMethods(); +// for (int i= 0; i < superMethods.length; i++) { +// IMethod curr= superMethods[i]; +// if (curr.isConstructor()) { +// constuctorFound= true; +// if (JavaModelUtil.isVisibleInHierarchy(curr, type.getPackageFragment())) +// if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, methods) == null) +// constructorMethods.add(curr); +// +// } // } -// buf.append(fullParamTypeNames[i]); -// } -// buf.append(")\n"); //$NON-NLS-1$ -// if (isDeprecated) { -// buf.append(" * @deprecated\n"); //$NON-NLS-1$ -// } -// buf.append(" */"); //$NON-NLS-1$ -// } -// -// -// -// /** -// * Finds a method in a list of methods. -// * @return The found method or null, if nothing found -// */ -// private static IMethod findMethod(IMethod method, List allMethods) throws JavaModelException { -// String name= method.getElementName(); -// String[] paramTypes= method.getParameterTypes(); -// boolean isConstructor= method.isConstructor(); -// -// for (int i= allMethods.size() - 1; i >= 0; i--) { -// IMethod curr= (IMethod) allMethods.get(i); -// if (JavaModelUtil.isSameMethodSignature(name, paramTypes, isConstructor, curr)) { -// return curr; -// } -// } -// return null; -// } - - - /** - * Creates needed constructors for a type. - * @param type The type to create constructors for - * @param supertype The type's super type - * @param settings Options for comment generation - * @param imports Required imports are added to the import structure. Structure can be null, types are qualified then. - * @return Returns the generated stubs or null if the creation has been canceled - */ -// public static String[] evalConstructors(IType type, IType supertype, CodeGenerationSettings settings, IImportsStructure imports) throws JavaModelException { -// IMethod[] superMethods= supertype.getMethods(); -// String typeName= type.getElementName(); -// IMethod[] methods= type.getMethods(); -// GenStubSettings genStubSettings= new GenStubSettings(settings); -// genStubSettings.callSuper= true; -// ArrayList newMethods= new ArrayList(superMethods.length); -// for (int i= 0; i < superMethods.length; i++) { -// IMethod curr= superMethods[i]; -// if (curr.isConstructor() && (JavaModelUtil.isVisible(curr, type.getPackageFragment()) || Flags.isProtected(curr.getFlags()))) { +// +// // http://bugs.eclipse.org/bugs/show_bug.cgi?id=38487 +// if (!constuctorFound) { +// IType objectType= type.getJavaProject().findType("java.lang.Object"); //$NON-NLS-1$ +// IMethod curr= objectType.getMethod("Object", EMPTY); //$NON-NLS-1$ // if (JavaModelUtil.findMethod(typeName, curr.getParameterTypes(), true, methods) == null) { -// String newStub= genStub(typeName, superMethods[i], genStubSettings, imports); -// newMethods.add(newStub); +// constructorMethods.add(curr); // } // } +// return (IMethod[]) constructorMethods.toArray(new IMethod[constructorMethods.size()]); // } -// return (String[]) newMethods.toArray(new String[newMethods.size()]); -// } -// -// /** -// * Searches for unimplemented methods of a type. -// * @param isSubType If set, the evaluation is for a subtype of the given type. If not set, the -// * evaluation is for the type itself. -// * @param settings Options for comment generation -// * @param selectionQuery If not null will select the methods to implement. -// * @param imports Required imports are added to the import structure. Structure can be null, types are qualified then. -// * @return Returns the generated stubs or null if the creation has been canceled -// */ -// public static String[] evalUnimplementedMethods(IType type, ITypeHierarchy hierarchy, boolean isSubType, CodeGenerationSettings settings, -// IOverrideMethodQuery selectionQuery, IImportsStructure imports) throws JavaModelException { -// List allMethods= new ArrayList(); -// List toImplement= new ArrayList(); + + /** + * Returns all overridable methods of a type + * @param type The type to search the overridable methods for + * @param hierarchy The type hierarchy of the type + * @param isSubType If set, the result can include methods of the passed type, if not only methods from super + * types are considered + * @return Returns the all methods that can be overridden + */ +// public static IMethod[] getOverridableMethods(IType type, ITypeHierarchy hierarchy, boolean isSubType) throws JavaModelException { +// List allMethods= new ArrayList(); // -// IMethod[] typeMethods= type.getMethods(); -// for (int i= 0; i < typeMethods.length; i++) { -// IMethod curr= typeMethods[i]; -// if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && !Flags.isPrivate(curr.getFlags())) { -// allMethods.add(curr); +// IMethod[] typeMethods= type.getMethods(); +// for (int i= 0; i < typeMethods.length; i++) { +// IMethod curr= typeMethods[i]; +// if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && !Flags.isPrivate(curr.getFlags())) { +// allMethods.add(curr); +// } // } -// } // -// IType[] superTypes= hierarchy.getAllSuperclasses(type); -// for (int i= 0; i < superTypes.length; i++) { -// IMethod[] methods= superTypes[i].getMethods(); -// for (int k= 0; k < methods.length; k++) { -// IMethod curr= methods[k]; -// if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && !Flags.isPrivate(curr.getFlags())) { -// if (findMethod(curr, allMethods) == null) { -// allMethods.add(curr); +// IType[] superTypes= hierarchy.getAllSuperclasses(type); +// for (int i= 0; i < superTypes.length; i++) { +// IMethod[] methods= superTypes[i].getMethods(); +// for (int k= 0; k < methods.length; k++) { +// IMethod curr= methods[k]; +// if (!curr.isConstructor() && !Flags.isStatic(curr.getFlags()) && !Flags.isPrivate(curr.getFlags())) { +// if (findMethod(curr, allMethods) == null) { +// allMethods.add(curr); +// } // } // } // } -// } // -// // do not call super -// for (int i= 0; i < allMethods.size(); i++) { -// IMethod curr= (IMethod) allMethods.get(i); -// if ((Flags.isAbstract(curr.getFlags()) || curr.getDeclaringType().isInterface()) && (isSubType || !type.equals(curr.getDeclaringType()))) { -// // implement all abstract methods -// toImplement.add(curr); -// } -// } +// IType[] superInterfaces= hierarchy.getAllSuperInterfaces(type); +// for (int i= 0; i < superInterfaces.length; i++) { +// IMethod[] methods= superInterfaces[i].getMethods(); +// for (int k= 0; k < methods.length; k++) { +// IMethod curr= methods[k]; // -// IType[] superInterfaces= hierarchy.getAllSuperInterfaces(type); -// for (int i= 0; i < superInterfaces.length; i++) { -// IMethod[] methods= superInterfaces[i].getMethods(); -// for (int k= 0; k < methods.length; k++) { -// IMethod curr= methods[k]; -// -// // binary interfaces can contain static initializers (variable intializations) -// // 1G4CKUS -// if (!Flags.isStatic(curr.getFlags())) { -// IMethod impl= findMethod(curr, allMethods); -// if (impl == null || ((curr.getExceptionTypes().length < impl.getExceptionTypes().length) && !Flags.isFinal(impl.getFlags()))) { -// if (impl != null) { -// allMethods.remove(impl); +// // binary interfaces can contain static initializers (variable intializations) +// // 1G4CKUS +// if (!Flags.isStatic(curr.getFlags())) { +// IMethod impl= findMethod(curr, allMethods); +// if (impl == null || !JavaModelUtil.isVisibleInHierarchy(impl, type.getPackageFragment()) || prefereInterfaceMethod(hierarchy, curr, impl)) { +// if (impl != null) { +// allMethods.remove(impl); +// } +// // implement an interface method when it does not exist in the hierarchy +// // or when it throws less exceptions that the implemented +// allMethods.add(curr); // } -// // implement an interface method when it does not exist in the hierarchy -// // or when it throws less exceptions that the implemented -// toImplement.add(curr); -// allMethods.add(curr); // } // } // } -// } -// IMethod[] toImplementArray= (IMethod[]) toImplement.toArray(new IMethod[toImplement.size()]); -// if (selectionQuery != null) { // if (!isSubType) { // allMethods.removeAll(Arrays.asList(typeMethods)); // } @@ -394,54 +890,102 @@ public class StubUtility { // allMethods.remove(i); // } // } -// IMethod[] choice= (IMethod[]) allMethods.toArray(new IMethod[allMethods.size()]); -// toImplementArray= selectionQuery.select(choice, toImplementArray, hierarchy); -// if (toImplementArray == null) { -// //cancel pressed -// return null; +// return (IMethod[]) allMethods.toArray(new IMethod[allMethods.size()]); +// } + +// private static boolean prefereInterfaceMethod(ITypeHierarchy hierarchy, IMethod interfaceMethod, IMethod curr) throws JavaModelException { +// if (Flags.isFinal(curr.getFlags())) { +// return false; +// } +// IType interfaceType= interfaceMethod.getDeclaringType(); +// IType[] interfaces= hierarchy.getAllSuperInterfaces(curr.getDeclaringType()); +// for (int i= 0; i < interfaces.length; i++) { +// if (interfaces[i] == interfaceType) { +// return false; +// } // } +// return curr.getExceptionTypes().length > interfaceMethod.getExceptionTypes().length; // } -// GenStubSettings genStubSettings= new GenStubSettings(settings); -// genStubSettings.methodOverwrites= true; -// String[] result= new String[toImplementArray.length]; -// for (int i= 0; i < toImplementArray.length; i++) { -// IMethod curr= toImplementArray[i]; -// IMethod overrides= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); -// genStubSettings.callSuper= (overrides != null); -// -// IMethod desc= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, type, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); -// if (desc != null) { -// curr= desc; + + /** + * Generate method stubs for methods to overrride + * @param type The type to search the overridable methods for + * @param hierarchy The type hierarchy of the type + * @param methodsToImplement Methods to override or implement + * @param settings Options for comment generation + * @param imports Required imports are added to the import structure. Structure can be null, types are qualified then. + * @return Returns the generated stubs + */ +// public static String[] genOverrideStubs(IMethod[] methodsToImplement, IType type, ITypeHierarchy hierarchy, CodeGenerationSettings settings, IImportsStructure imports) throws CoreException { +// GenStubSettings genStubSettings= new GenStubSettings(settings); +// genStubSettings.methodOverwrites= true; +// ICompilationUnit cu= type.getCompilationUnit(); +// String[] result= new String[methodsToImplement.length]; +// for (int i= 0; i < methodsToImplement.length; i++) { +// IMethod curr= methodsToImplement[i]; +// IMethod overrides= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); +// if (overrides != null) { +// genStubSettings.callSuper= true; +// curr= overrides; +// } +// genStubSettings.methodModifiers= curr.getFlags(); +// IMethod desc= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, type, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor()); +// if (desc == null) { +// desc= curr; +// } +// result[i]= genStub(cu, type.getElementName(), curr, desc.getDeclaringType(), genStubSettings, imports); // } -// result[i]= genStub(type.getElementName(), curr, genStubSettings, imports); +// return result; // } -// return result; -// } - - /** - * Examines a string and returns the first line delimiter found. - */ -// public static String getLineDelimiterUsed(IJavaElement elem) throws JavaModelException { -// ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); -// if (cu != null && cu.exists()) { -// IBuffer buf= cu.getBuffer(); -// int length= buf.getLength(); -// for (int i= 0; i < length; i++) { -// char ch= buf.getChar(i); -// if (ch == SWT.CR) { -// if (i + 1 < length) { -// if (buf.getChar(i + 1) == SWT.LF) { -// return "\r\n"; //$NON-NLS-1$ -// } -// } -// return "\r"; //$NON-NLS-1$ -// } else if (ch == SWT.LF) { -// return "\n"; //$NON-NLS-1$ + /** + * Searches for unimplemented methods of a type. + * @param isSubType If set, the evaluation is for a subtype of the given type. If not set, the + * evaluation is for the type itself. + * @param settings Options for comment generation + * @param imports Required imports are added to the import structure. Structure can be null, types are qualified then. + * @return Returns the generated stubs or null if the creation has been canceled + */ +// public static String[] evalUnimplementedMethods(IType type, ITypeHierarchy hierarchy, boolean isSubType, CodeGenerationSettings settings, +// IImportsStructure imports) throws CoreException { +// +// IMethod[] inheritedMethods= getOverridableMethods(type, hierarchy, isSubType); +// +// List toImplement= new ArrayList(); +// for (int i= 0; i < inheritedMethods.length; i++) { +// IMethod curr= inheritedMethods[i]; +// if (JdtFlags.isAbstract(curr)) { +// toImplement.add(curr); // } // } +// IMethod[] toImplementArray= (IMethod[]) toImplement.toArray(new IMethod[toImplement.size()]); +// return genOverrideStubs(toImplementArray, type, hierarchy, settings, imports); // } -// return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ -// } + + /** + * Examines a string and returns the first line delimiter found. + */ + public static String getLineDelimiterUsed(IJavaElement elem) throws JavaModelException { + ICompilationUnit cu= (ICompilationUnit) elem.getAncestor(IJavaElement.COMPILATION_UNIT); + if (cu != null && cu.exists()) { + IBuffer buf= cu.getBuffer(); + int length= buf.getLength(); + for (int i= 0; i < length; i++) { + char ch= buf.getChar(i); + if (ch == SWT.CR) { + if (i + 1 < length) { + if (buf.getChar(i + 1) == SWT.LF) { + return "\r\n"; //$NON-NLS-1$ + } + } + return "\r"; //$NON-NLS-1$ + } else if (ch == SWT.LF) { + return "\n"; //$NON-NLS-1$ + } + } + } + return System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + } + /** * Embodies the policy which line delimiter to use when inserting into @@ -530,5 +1074,119 @@ public class StubUtility { } return null; } + /* + * Workarounds for bug 38111 + */ +// public static String[] getArgumentNameSuggestions(IJavaProject project, String baseName, int dimensions, String[] excluded) { +// String name= workaround38111(baseName); +// String[] res= NamingConventions.suggestArgumentNames(project, "", name, dimensions, excluded); //$NON-NLS-1$ +// return sortByLength(res); // longest first +// } +// +// public static String[] getFieldNameSuggestions(IJavaProject project, String baseName, int dimensions, int modifiers, String[] excluded) { +// String name= workaround38111(baseName); +// String[] res= NamingConventions.suggestFieldNames(project, "", name, dimensions, modifiers, excluded); //$NON-NLS-1$ +// return sortByLength(res); // longest first +// } +// +// public static String[] getLocalNameSuggestions(IJavaProject project, String baseName, int dimensions, String[] excluded) { +// String name= workaround38111(baseName); +// String[] res= NamingConventions.suggestLocalVariableNames(project, "", name, dimensions, excluded); //$NON-NLS-1$ +// return sortByLength(res); // longest first +// } + + private static String[] sortByLength(String[] proposals) { + Arrays.sort(proposals, new Comparator() { + public int compare(Object o1, Object o2) { + return ((String) o2).length() - ((String) o1).length(); + } + }); + return proposals; + } + + private static String workaround38111(String baseName) { + if (BASE_TYPES.contains(baseName)) + return baseName; + return Character.toUpperCase(baseName.charAt(0)) + baseName.substring(1); + } + + private static final List BASE_TYPES= Arrays.asList( + new String[] {"boolean", "byte", "char", "double", "float", "int", "long", "short"}); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ //$NON-NLS-5$ //$NON-NLS-6$ //$NON-NLS-7$ //$NON-NLS-8$ + + public static String suggestArgumentName(IJavaProject project, String baseName, String[] excluded) { +// String[] argnames= getArgumentNameSuggestions(project, baseName, 0, excluded); +// if (argnames.length > 0) { +// return argnames[0]; +// } + return baseName; + } + + public static String[] suggestArgumentNames(IJavaProject project, String[] paramNames) { + String prefixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); + String suffixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); + if (prefixes.length() + suffixes.length() == 0) { + return paramNames; + } + + String[] newNames= new String[paramNames.length]; + // Ensure that the codegeneration preferences are respected + for (int i= 0; i < paramNames.length; i++) { + String curr= paramNames[i]; + if (!hasPrefixOrSuffix(prefixes, suffixes, curr)) { + newNames[i]= suggestArgumentName(project, paramNames[i], null); + } else { + newNames[i]= curr; + } + } + return newNames; + } + + public static boolean hasFieldName(IJavaProject project, String name) { + String prefixes= project.getOption(JavaCore.CODEASSIST_FIELD_PREFIXES, true); + String suffixes= project.getOption(JavaCore.CODEASSIST_FIELD_SUFFIXES, true); + String staticPrefixes= project.getOption(JavaCore.CODEASSIST_STATIC_FIELD_PREFIXES, true); + String staticSuffixes= project.getOption(JavaCore.CODEASSIST_STATIC_FIELD_SUFFIXES, true); + + + return hasPrefixOrSuffix(prefixes, suffixes, name) + || hasPrefixOrSuffix(staticPrefixes, staticSuffixes, name); + } + + public static boolean hasParameterName(IJavaProject project, String name) { + String prefixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_PREFIXES, true); + String suffixes= project.getOption(JavaCore.CODEASSIST_ARGUMENT_SUFFIXES, true); + return hasPrefixOrSuffix(prefixes, suffixes, name); + } + + public static boolean hasLocalVariableName(IJavaProject project, String name) { + String prefixes= project.getOption(JavaCore.CODEASSIST_LOCAL_PREFIXES, true); + String suffixes= project.getOption(JavaCore.CODEASSIST_LOCAL_SUFFIXES, true); + return hasPrefixOrSuffix(prefixes, suffixes, name); + } + + public static boolean hasConstantName(String name) { + return Character.isUpperCase(name.charAt(0)); + } + + + private static boolean hasPrefixOrSuffix(String prefixes, String suffixes, String name) { + final String listSeparartor= ","; //$NON-NLS-1$ + + StringTokenizer tok= new StringTokenizer(prefixes, listSeparartor); + while (tok.hasMoreTokens()) { + String curr= tok.nextToken(); + if (name.startsWith(curr)) { + return true; + } + } + tok= new StringTokenizer(suffixes, listSeparartor); + while (tok.hasMoreTokens()) { + String curr= tok.nextToken(); + if (name.endsWith(curr)) { + return true; + } + } + return false; + } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java index 9aef349..01908fe 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/corext/template/php/CodeTemplateContext.java @@ -52,7 +52,7 @@ public class CodeTemplateContext extends TemplateContext { while (iterator.hasNext()) { TemplateVariableResolver var= (TemplateVariableResolver) iterator.next(); if (var instanceof CodeTemplateContextType.CodeTemplateVariableResolver) { - Assert.isNotNull(getVariable(var.getType()), "Variable " + var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$ + // Assert.isNotNull(getVariable(var.getType()), "Variable " + var.getType() + "not defined"); //$NON-NLS-1$ //$NON-NLS-2$ } } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.properties b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.properties index fb30956..b5a8f8f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.properties +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIMessages.properties @@ -540,6 +540,20 @@ ResourceTransferDragAdapter.moving_resource=Moving Resources via DND ResourceTransferDragAdapter.cannot_delete_files=Cannot delete the following file(s) ######### +# Spelling +######### + +Spelling.dictionary.file.extension=dictionary +Spelling.error.label=The word ''{0}'' is not correctly spelled +Spelling.correct.label=Change to ''{0}'' +Spelling.add.info=Adds the word ''{0}'' to the dictionary +Spelling.add.label=Add ''{0}'' to dictionary +Spelling.ignore.info=Always ignores ''{0}'' during the current session +Spelling.ignore.label=Always ignore ''{0}'' +Spelling.case.label=Change to upper case +Spelling.error.case.label= The word ''{0}'' should have an initial upper case letter + +######### # misc ######### diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIStatus.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIStatus.java index 91e1537..4fcf12a 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIStatus.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/PHPUIStatus.java @@ -29,7 +29,15 @@ public class PHPUIStatus extends Status { public PHPUIStatus(int code, String message, Throwable throwable) { super(IStatus.ERROR, PHPeclipsePlugin.getPluginId(), code, message, throwable); } - + + public static IStatus createError(int code, Throwable throwable) { + String message= throwable.getMessage(); + if (message == null) { + message= throwable.getClass().getName(); + } + return new PHPUIStatus(IStatus.ERROR, code, message, throwable); + } + public static IStatus createError(int code, String message, Throwable throwable) { return new PHPUIStatus(IStatus.ERROR, code, message, throwable); } diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java new file mode 100644 index 0000000..a1e4f67 --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplateBlock.java @@ -0,0 +1,514 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import java.io.BufferedInputStream; +import java.io.BufferedOutputStream; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.FileOutputStream; +import java.io.IOException; +import java.io.InputStream; +import java.io.OutputStream; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; +import net.sourceforge.phpdt.internal.ui.text.IPHPPartitions; +import net.sourceforge.phpdt.internal.ui.text.template.preferences.TemplateVariableProcessor; +import net.sourceforge.phpdt.internal.ui.util.PixelConverter; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.DialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.IDialogFieldListener; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.ITreeListAdapter; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.LayoutUtil; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.SelectionButtonDialogField; +import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.TreeListDialogField; +import net.sourceforge.phpdt.ui.PreferenceConstants; +import net.sourceforge.phpdt.ui.text.JavaTextTools; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; +import net.sourceforge.phpeclipse.phpeditor.JavaSourceViewer; + +import org.eclipse.jface.dialogs.MessageDialog; +import org.eclipse.jface.preference.IPreferenceStore; +import org.eclipse.jface.resource.JFaceResources; +import org.eclipse.jface.text.Document; +import org.eclipse.jface.text.IDocument; +import org.eclipse.jface.text.source.SourceViewer; +import org.eclipse.jface.text.templates.Template; +import org.eclipse.jface.text.templates.TemplateContextType; +import org.eclipse.jface.text.templates.persistence.TemplatePersistenceData; +import org.eclipse.jface.text.templates.persistence.TemplateReaderWriter; +import org.eclipse.jface.text.templates.persistence.TemplateStore; +import org.eclipse.jface.viewers.LabelProvider; +import org.eclipse.jface.viewers.StructuredSelection; +import org.eclipse.jface.window.Window; +import org.eclipse.swt.SWT; +import org.eclipse.swt.events.KeyEvent; +import org.eclipse.swt.graphics.Font; +import org.eclipse.swt.graphics.Image; +import org.eclipse.swt.layout.GridData; +import org.eclipse.swt.layout.GridLayout; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.swt.widgets.FileDialog; +import org.eclipse.swt.widgets.Label; +import org.eclipse.swt.widgets.Shell; + +/** + */ +public class CodeTemplateBlock { + + private class CodeTemplateAdapter implements ITreeListAdapter, IDialogFieldListener { + + private final Object[] NO_CHILDREN = new Object[0]; + + public void customButtonPressed(TreeListDialogField field, int index) { + doButtonPressed(index, field.getSelectedElements()); + } + + public void selectionChanged(TreeListDialogField field) { + List selected = field.getSelectedElements(); + field.enableButton(IDX_EDIT, canEdit(selected)); + field.enableButton(IDX_EXPORT, !selected.isEmpty()); + + updateSourceViewerInput(selected); + } + + public void doubleClicked(TreeListDialogField field) { + List selected = field.getSelectedElements(); + if (canEdit(selected)) { + doButtonPressed(IDX_EDIT, selected); + } + } + + public Object[] getChildren(TreeListDialogField field, Object element) { + if (element == COMMENT_NODE || element == CODE_NODE) { + return getTemplateOfCategory(element == COMMENT_NODE); + } + return NO_CHILDREN; + } + + public Object getParent(TreeListDialogField field, Object element) { + if (element instanceof TemplatePersistenceData) { + TemplatePersistenceData data = (TemplatePersistenceData) element; + if (data.getTemplate().getName().endsWith(CodeTemplateContextType.COMMENT_SUFFIX)) { + return COMMENT_NODE; + } + return CODE_NODE; + } + return null; + } + + public boolean hasChildren(TreeListDialogField field, Object element) { + return (element == COMMENT_NODE || element == CODE_NODE); + } + + public void dialogFieldChanged(DialogField field) { + } + + public void keyPressed(TreeListDialogField field, KeyEvent event) { + } + + } + + private static class CodeTemplateLabelProvider extends LabelProvider { + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILabelProvider#getImage(java.lang.Object) + */ + public Image getImage(Object element) { + return null; + + } + + /* + * (non-Javadoc) + * + * @see org.eclipse.jface.viewers.ILabelProvider#getText(java.lang.Object) + */ + public String getText(Object element) { + if (element == COMMENT_NODE || element == CODE_NODE) { + return (String) element; + } + TemplatePersistenceData data = (TemplatePersistenceData) element; + Template template = data.getTemplate(); + String name = template.getName(); + if (CodeTemplateContextType.CATCHBLOCK.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.catchblock.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.METHODSTUB.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.methodstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.CONSTRUCTORSTUB.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.constructorstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.GETTERSTUB.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.getterstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.SETTERSTUB.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.setterstub.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.NEWTYPE.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.newtype.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.TYPECOMMENT.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.typecomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.FIELDCOMMENT.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.fieldcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.METHODCOMMENT.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.methodcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.OVERRIDECOMMENT.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.overridecomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.CONSTRUCTORCOMMENT.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.constructorcomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.GETTERCOMMENT.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.gettercomment.label"); //$NON-NLS-1$ + } else if (CodeTemplateContextType.SETTERCOMMENT.equals(name)) { + return PreferencesMessages.getString("CodeTemplateBlock.settercomment.label"); //$NON-NLS-1$ + } + return template.getDescription(); + } + + } + + private final static int IDX_EDIT = 0; + + private final static int IDX_IMPORT = 2; + + private final static int IDX_EXPORT = 3; + + private final static int IDX_EXPORTALL = 4; + + protected final static Object COMMENT_NODE = PreferencesMessages.getString("CodeTemplateBlock.templates.comment.node"); //$NON-NLS-1$ + + protected final static Object CODE_NODE = PreferencesMessages.getString("CodeTemplateBlock.templates.code.node"); //$NON-NLS-1$ + + private static final String PREF_JAVADOC_STUBS = PreferenceConstants.CODEGEN_ADD_COMMENTS; + + private TreeListDialogField fCodeTemplateTree; + + private SelectionButtonDialogField fCreateJavaDocComments; + + protected TemplateStore fTemplates; + + private PixelConverter fPixelConverter; + + private SourceViewer fPatternViewer; + + private Control fSWTWidget; + + private TemplateVariableProcessor fTemplateProcessor; + + public CodeTemplateBlock() { + + fTemplates = PHPeclipsePlugin.getDefault().getCodeTemplateStore(); + fTemplateProcessor = new TemplateVariableProcessor(); + + CodeTemplateAdapter adapter = new CodeTemplateAdapter(); + + String[] buttonLabels = new String[] { + /* IDX_EDIT */PreferencesMessages.getString("CodeTemplateBlock.templates.edit.button"), //$NON-NLS-1$ + /* */null, + /* IDX_IMPORT */PreferencesMessages.getString("CodeTemplateBlock.templates.import.button"), //$NON-NLS-1$ + /* IDX_EXPORT */PreferencesMessages.getString("CodeTemplateBlock.templates.export.button"), //$NON-NLS-1$ + /* IDX_EXPORTALL */PreferencesMessages.getString("CodeTemplateBlock.templates.exportall.button") //$NON-NLS-1$ + + }; + fCodeTemplateTree = new TreeListDialogField(adapter, buttonLabels, new CodeTemplateLabelProvider()); + fCodeTemplateTree.setDialogFieldListener(adapter); + fCodeTemplateTree.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.templates.label")); //$NON-NLS-1$ + + fCodeTemplateTree.enableButton(IDX_EXPORT, false); + fCodeTemplateTree.enableButton(IDX_EDIT, false); + + fCodeTemplateTree.addElement(COMMENT_NODE); + fCodeTemplateTree.addElement(CODE_NODE); + + fCreateJavaDocComments = new SelectionButtonDialogField(SWT.CHECK | SWT.WRAP); + fCreateJavaDocComments.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.label")); //$NON-NLS-1$ + fCreateJavaDocComments.setSelection(PreferenceConstants.getPreferenceStore().getBoolean(PREF_JAVADOC_STUBS)); + + fCodeTemplateTree.selectFirstElement(); + } + + protected Control createContents(Composite parent) { + fPixelConverter = new PixelConverter(parent); + fSWTWidget = parent; + + Composite composite = new Composite(parent, SWT.NONE); + GridLayout layout = new GridLayout(); + layout.marginHeight = 0; + layout.marginWidth = 0; + layout.numColumns = 2; + composite.setLayout(layout); + + fCodeTemplateTree.doFillIntoGrid(composite, 3); + LayoutUtil.setHorizontalSpan(fCodeTemplateTree.getLabelControl(null), 2); + LayoutUtil.setHorizontalGrabbing(fCodeTemplateTree.getTreeControl(null)); + + fPatternViewer = createViewer(composite, 2); + + fCreateJavaDocComments.doFillIntoGrid(composite, 2); + + DialogField label = new DialogField(); + label.setLabelText(PreferencesMessages.getString("CodeTemplateBlock.createcomment.description")); //$NON-NLS-1$ + label.doFillIntoGrid(composite, 2); + + return composite; + + } + + private Shell getShell() { + if (fSWTWidget != null) { + return fSWTWidget.getShell(); + } + return PHPeclipsePlugin.getActiveWorkbenchShell(); + } + + private SourceViewer createViewer(Composite parent, int nColumns) { + Label label = new Label(parent, SWT.NONE); + label.setText(PreferencesMessages.getString("CodeTemplateBlock.preview")); //$NON-NLS-1$ + GridData data = new GridData(); + data.horizontalSpan = nColumns; + label.setLayoutData(data); + + IDocument document = new Document(); + JavaTextTools tools = PHPeclipsePlugin.getDefault().getJavaTextTools(); + tools.setupJavaDocumentPartitioner(document, IPHPPartitions.PHP_PARTITIONING); + IPreferenceStore store = PHPeclipsePlugin.getDefault().getCombinedPreferenceStore(); + SourceViewer viewer = new JavaSourceViewer(parent, null, null, false, SWT.BORDER | SWT.V_SCROLL | SWT.H_SCROLL, store); + TemplateEditorSourceViewerConfiguration configuration = new TemplateEditorSourceViewerConfiguration(tools.getColorManager(), + store, null, fTemplateProcessor); + viewer.configure(configuration); + viewer.setEditable(false); + viewer.setDocument(document); + + Font font = JFaceResources.getFont(PreferenceConstants.EDITOR_TEXT_FONT); + viewer.getTextWidget().setFont(font); + new JavaSourcePreviewerUpdater(viewer, configuration, store); + + Control control = viewer.getControl(); + data = new GridData(GridData.HORIZONTAL_ALIGN_FILL | GridData.FILL_VERTICAL); + data.horizontalSpan = nColumns; + data.heightHint = fPixelConverter.convertHeightInCharsToPixels(5); + control.setLayoutData(data); + + return viewer; + } + + protected TemplatePersistenceData[] getTemplateOfCategory(boolean isComment) { + ArrayList res = new ArrayList(); + TemplatePersistenceData[] templates = fTemplates.getTemplateData(false); + for (int i = 0; i < templates.length; i++) { + TemplatePersistenceData curr = templates[i]; + if (isComment == curr.getTemplate().getName().endsWith(CodeTemplateContextType.COMMENT_SUFFIX)) { + res.add(curr); + } + } + return (TemplatePersistenceData[]) res.toArray(new TemplatePersistenceData[res.size()]); + } + + protected static boolean canEdit(List selected) { + return selected.size() == 1 && (selected.get(0) instanceof TemplatePersistenceData); + } + + protected void updateSourceViewerInput(List selection) { + if (fPatternViewer == null || fPatternViewer.getTextWidget().isDisposed()) { + return; + } + if (selection.size() == 1 && selection.get(0) instanceof TemplatePersistenceData) { + TemplatePersistenceData data = (TemplatePersistenceData) selection.get(0); + Template template = data.getTemplate(); + TemplateContextType type = PHPeclipsePlugin.getDefault().getCodeTemplateContextRegistry().getContextType( + template.getContextTypeId()); + fTemplateProcessor.setContextType(type); + fPatternViewer.getDocument().set(template.getPattern()); + } else { + fPatternViewer.getDocument().set(""); //$NON-NLS-1$ + } + } + + protected void doButtonPressed(int buttonIndex, List selected) { + if (buttonIndex == IDX_EDIT) { + edit((TemplatePersistenceData) selected.get(0)); + } else if (buttonIndex == IDX_EXPORT) { + export(selected); + } else if (buttonIndex == IDX_EXPORTALL) { + exportAll(); + } else if (buttonIndex == IDX_IMPORT) { + import_(); + } + } + + private void edit(TemplatePersistenceData data) { + Template newTemplate = new Template(data.getTemplate()); + EditTemplateDialog dialog = new EditTemplateDialog(getShell(), newTemplate, true, false, PHPeclipsePlugin.getDefault() + .getCodeTemplateContextRegistry()); + if (dialog.open() == Window.OK) { + // changed + data.setTemplate(newTemplate); + fCodeTemplateTree.refresh(data); + fCodeTemplateTree.selectElements(new StructuredSelection(data)); + } + } + + private void import_() { + FileDialog dialog = new FileDialog(getShell()); + dialog.setText(PreferencesMessages.getString("CodeTemplateBlock.import.title")); //$NON-NLS-1$ + dialog.setFilterExtensions(new String[] { PreferencesMessages.getString("CodeTemplateBlock.import.extension") }); //$NON-NLS-1$ + String path = dialog.open(); + + if (path == null) + return; + + try { + TemplateReaderWriter reader = new TemplateReaderWriter(); + File file = new File(path); + if (file.exists()) { + InputStream input = new BufferedInputStream(new FileInputStream(file)); + TemplatePersistenceData[] datas = reader.read(input, null); + for (int i = 0; i < datas.length; i++) { + updateTemplate(datas[i]); + } + } + + fCodeTemplateTree.refresh(); + updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); + + } catch (FileNotFoundException e) { + openReadErrorDialog(e); + } catch (IOException e) { + openReadErrorDialog(e); + } + + } + + private void updateTemplate(TemplatePersistenceData data) { + TemplatePersistenceData[] datas = fTemplates.getTemplateData(true); + for (int i = 0; i < datas.length; i++) { + String id = datas[i].getId(); + if (id != null && id.equals(data.getId())) { + datas[i].setTemplate(data.getTemplate()); + break; + } + } + } + + private void exportAll() { + export(fTemplates.getTemplateData(false)); + } + + private void export(List selected) { + List datas = new ArrayList(); + for (int i = 0; i < selected.size(); i++) { + Object curr = selected.get(i); + if (curr instanceof TemplatePersistenceData) { + datas.add(curr); + } else { + TemplatePersistenceData[] cat = getTemplateOfCategory(curr == COMMENT_NODE); + datas.addAll(Arrays.asList(cat)); + } + } + export((TemplatePersistenceData[]) datas.toArray(new TemplatePersistenceData[datas.size()])); + } + + private void export(TemplatePersistenceData[] templates) { + FileDialog dialog = new FileDialog(getShell(), SWT.SAVE); + dialog.setText(PreferencesMessages.getFormattedString("CodeTemplateBlock.export.title", String.valueOf(templates.length))); //$NON-NLS-1$ + dialog.setFilterExtensions(new String[] { PreferencesMessages.getString("CodeTemplateBlock.export.extension") }); //$NON-NLS-1$ + dialog.setFileName(PreferencesMessages.getString("CodeTemplateBlock.export.filename")); //$NON-NLS-1$ + String path = dialog.open(); + + if (path == null) + return; + + File file = new File(path); + + if (file.isHidden()) { + String title = PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ + String message = PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.hidden", file.getAbsolutePath()); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + return; + } + + if (file.exists() && !file.canWrite()) { + String title = PreferencesMessages.getString("CodeTemplateBlock.export.error.title"); //$NON-NLS-1$ + String message = PreferencesMessages.getFormattedString("CodeTemplateBlock.export.error.canNotWrite", file.getAbsolutePath()); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + return; + } + + if (!file.exists() || confirmOverwrite(file)) { + try { + OutputStream output = new BufferedOutputStream(new FileOutputStream(file)); + TemplateReaderWriter writer = new TemplateReaderWriter(); + writer.save(templates, output); + } catch (IOException e) { + openWriteErrorDialog(e); + } + } + + } + + private boolean confirmOverwrite(File file) { + return MessageDialog.openQuestion(getShell(), PreferencesMessages.getString("CodeTemplateBlock.export.exists.title"), //$NON-NLS-1$ + PreferencesMessages.getFormattedString("CodeTemplateBlock.export.exists.message", file.getAbsolutePath())); //$NON-NLS-1$ + } + + public void performDefaults() { + IPreferenceStore prefs = PHPeclipsePlugin.getDefault().getPreferenceStore(); + fCreateJavaDocComments.setSelection(prefs.getDefaultBoolean(PREF_JAVADOC_STUBS)); + + fTemplates.restoreDefaults(); + + // refresh + fCodeTemplateTree.refresh(); + updateSourceViewerInput(fCodeTemplateTree.getSelectedElements()); + } + + public boolean performOk(boolean enabled) { + IPreferenceStore prefs = PreferenceConstants.getPreferenceStore(); + prefs.setValue(PREF_JAVADOC_STUBS, fCreateJavaDocComments.isSelected()); + PHPeclipsePlugin.getDefault().savePluginPreferences(); + + try { + fTemplates.save(); + } catch (IOException e) { + PHPeclipsePlugin.log(e); + openWriteErrorDialog(e); + } + return true; + } + + public void performCancel() { + try { + fTemplates.load(); + } catch (IOException e) { + openReadErrorDialog(e); + } + } + + private void openReadErrorDialog(Exception e) { + String title = PreferencesMessages.getString("CodeTemplateBlock.error.read.title"); //$NON-NLS-1$ + + String message = e.getLocalizedMessage(); + if (message != null) + message = PreferencesMessages.getFormattedString("CodeTemplateBlock.error.parse.message", message); //$NON-NLS-1$ + else + message = PreferencesMessages.getString("CodeTemplateBlock.error.read.message"); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + } + + private void openWriteErrorDialog(Exception e) { + String title = PreferencesMessages.getString("CodeTemplateBlock.error.write.title"); //$NON-NLS-1$ + String message = PreferencesMessages.getString("CodeTemplateBlock.error.write.message"); //$NON-NLS-1$ + MessageDialog.openError(getShell(), title, message); + } + +} \ No newline at end of file diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java new file mode 100644 index 0000000..292083a --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/preferences/CodeTemplatePreferencePage.java @@ -0,0 +1,105 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.internal.ui.preferences; + +import net.sourceforge.phpdt.internal.ui.IJavaHelpContextIds; +import net.sourceforge.phpdt.internal.ui.dialogs.StatusUtil; +import net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + +import org.eclipse.core.runtime.IStatus; +import org.eclipse.jface.dialogs.Dialog; +import org.eclipse.jface.preference.PreferencePage; +import org.eclipse.swt.widgets.Composite; +import org.eclipse.swt.widgets.Control; +import org.eclipse.ui.IWorkbench; +import org.eclipse.ui.IWorkbenchPreferencePage; +import org.eclipse.ui.help.WorkbenchHelp; + +/* + * The page to configure the code formatter options. + */ +public class CodeTemplatePreferencePage extends PreferencePage implements IWorkbenchPreferencePage, IStatusChangeListener { + + private CodeTemplateBlock fCodeTemplateConfigurationBlock; + + public CodeTemplatePreferencePage() { + setPreferenceStore(PHPeclipsePlugin.getDefault().getPreferenceStore()); + //setDescription(PreferencesMessages.getString("CodeTemplatesPreferencePage.description")); //$NON-NLS-1$ + + // only used when page is shown programatically + setTitle(PreferencesMessages.getString("CodeTemplatesPreferencePage.title")); //$NON-NLS-1$ + + fCodeTemplateConfigurationBlock= new CodeTemplateBlock(); + } + + /* + * @see IWorkbenchPreferencePage#init(org.eclipse.ui.IWorkbench) + */ + public void init(IWorkbench workbench) { + } + + /* + * @see PreferencePage#createControl(Composite) + */ + public void createControl(Composite parent) { + super.createControl(parent); + WorkbenchHelp.setHelp(getControl(), IJavaHelpContextIds.CODE_MANIPULATION_PREFERENCE_PAGE); + } + + /* + * @see PreferencePage#createContents(Composite) + */ + protected Control createContents(Composite parent) { + Control composite= fCodeTemplateConfigurationBlock.createContents(parent); + Dialog.applyDialogFont(composite); + return composite; + } + + /* + * @see IPreferencePage#performOk() + */ + public boolean performOk() { + if (!fCodeTemplateConfigurationBlock.performOk(true)) { + return false; + } + return super.performOk(); + } + + /* + * @see PreferencePage#performDefaults() + */ + protected void performDefaults() { + fCodeTemplateConfigurationBlock.performDefaults(); + super.performDefaults(); + } + + /* (non-Javadoc) + * @see net.sourceforge.phpdt.internal.ui.wizards.IStatusChangeListener#statusChanged(org.eclipse.core.runtime.IStatus) + */ + public void statusChanged(IStatus status) { + setValid(!status.matches(IStatus.ERROR)); + StatusUtil.applyToStatusLine(this, status); + } + + /* (non-Javadoc) + * @see org.eclipse.jface.preference.IPreferencePage#performCancel() + */ + public boolean performCancel() { + fCodeTemplateConfigurationBlock.performCancel(); + + return super.performCancel(); + } + +} + + + diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java index a977166..84d5f35 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/internal/ui/text/spelling/SpellReconcileStrategy.java @@ -226,7 +226,7 @@ public class SpellReconcileStrategy implements IReconcilingStrategy, IReconcilin } } - /** The document to operate on */ + /** The document to operate on */ private IDocument fDocument= null; /** The text editor to operate on */ diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java new file mode 100644 index 0000000..a6d10fc --- /dev/null +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/CodeGeneration.java @@ -0,0 +1,241 @@ +/******************************************************************************* + * Copyright (c) 2000, 2004 IBM Corporation and others. + * All rights reserved. This program and the accompanying materials + * are made available under the terms of the Common Public License v1.0 + * which accompanies this distribution, and is available at + * http://www.eclipse.org/legal/cpl-v10.html + * + * Contributors: + * IBM Corporation - initial API and implementation + *******************************************************************************/ +package net.sourceforge.phpdt.ui; + +import org.eclipse.core.runtime.CoreException; + +import net.sourceforge.phpdt.core.ICompilationUnit; +import net.sourceforge.phpdt.core.IMethod; +//import net.sourceforge.phpdt.core.dom.IMethodBinding; +//import net.sourceforge.phpdt.core.dom.MethodDeclaration; + +import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; + +/** + * Class that offers access to the templates contained in the 'code templates' preference page. + * + * @since 2.1 + */ +public class CodeGeneration { + + private CodeGeneration() { + } + + /** + * Returns the content for a new compilation unit using the 'new Java file' code template. + * @param cu The compilation to create the source for. The compilation unit does not need to exist. + * @param typeComment The comment for the type to be created. Used when the code template contains a ${typecomment} variable. Can be null if + * no comment should be added. + * @param typeContent The code of the type, including type declaration and body. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the new content or null if the template is undefined or empty. + * @throws CoreException Thrown when the evaluation of the code template fails. + */ + public static String getCompilationUnitContent(ICompilationUnit cu, String typeComment, String typeContent, String lineDelimiter) throws CoreException { + return StubUtility.getCompilationUnitContent(cu, typeComment, typeContent, lineDelimiter); + } + + /** + * Returns the content for a new type comment using the 'type comment' code template. The returned content is unformatted and is not indented. + * @param cu The compilation where the type is contained. The compilation unit does not need to exist. + * @param typeQualifiedName The name of the type to which the comment is added. For inner types the name must be qualified and include the outer + * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the new content or null if the code template is undefined or empty. The returned content is unformatted and is not indented. + * @throws CoreException Thrown when the evaluation of the code template fails. + */ + public static String getTypeComment(ICompilationUnit cu, String typeQualifiedName, String lineDelimiter) throws CoreException { + return StubUtility.getTypeComment(cu, typeQualifiedName, lineDelimiter); + } + + /** + * Returns the content for a new field comment using the 'field comment' code template. The returned content is unformatted and is not indented. + * @param cu The compilation where the field is contained. The compilation unit does not need to exist. + * @param typeName The name of the field declared type. + * @param fieldName The name of the field to which the comment is added. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the new content or null if the code template is undefined or empty. The returned content is unformatted and is not indented. + * @throws CoreException Thrown when the evaluation of the code template fails. + * @since 3.0 + */ + public static String getFieldComment(ICompilationUnit cu, String typeName, String fieldName, String lineDelimiter) throws CoreException { + return StubUtility.getFieldComment(cu, typeName, fieldName, lineDelimiter); + } + + /** + * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). + * null is returned if the template is empty. + * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. + * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer + * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param decl The MethodDeclaration AST node that will be added as new + * method. The node does not need to exist in an AST (no parent needed) and does not need to resolve. + * See {@link net.sourceforge.phpdt.core.dom.AST#newMethodDeclaration()} for how to create such a node. + * @param overridden The binding of the method that will be overridden by the created + * method or null if no method is overridden. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the generated method comment or null if the + * code template is empty. The returned content is unformatted and not indented (formatting required). + * @throws CoreException Thrown when the evaluation of the code template fails. + */ +// public static String getMethodComment(ICompilationUnit cu, String declaringTypeName, MethodDeclaration decl, IMethodBinding overridden, String lineDelimiter) throws CoreException { +// return StubUtility.getMethodComment(cu, declaringTypeName, decl, overridden, lineDelimiter); +// } + + /** + * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). + * null is returned if the template is empty. + *

The returned string is unformatted and not indented. + *

Exception types and return type are in signature notation. e.g. a source method declared as public void foo(String text, int length) + * would return the array {"QString;","I"} as parameter types. See {@link net.sourceforge.phpdt.core.Signature}. + * + * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. + * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer + * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName Name of the method. + * @param paramNames Names of the parameters for the method. + * @param excTypeSig Thrown exceptions (Signature notation). + * @param retTypeSig Return type (Signature notation) or null + * for constructors. + * @param overridden The method that will be overridden by the created method or + * null for non-overriding methods. If not null, the method must exist. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the constructed comment or null if + * the comment code template is empty. The returned content is unformatted and not indented (formatting required). + * @throws CoreException Thrown when the evaluation of the code template fails. + */ + public static String getMethodComment(ICompilationUnit cu, String declaringTypeName, String methodName, String[] paramNames, String[] excTypeSig, String retTypeSig, IMethod overridden, String lineDelimiter) throws CoreException { + return StubUtility.getMethodComment(cu, declaringTypeName, methodName, paramNames, excTypeSig, retTypeSig, overridden, lineDelimiter); + } + + /** + * Returns the comment for a method or constructor using the comment code templates (constructor / method / overriding method). + * null is returned if the template is empty. + *

The returned string is unformatted and not indented. + * + * @param method The method to be documented. The method must exist. + * @param overridden The method that will be overridden by the created method or + * null for non-overriding methods. If not null, the method must exist. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the constructed comment or null if + * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). + * @throws CoreException Thrown when the evaluation of the code template fails. + */ + public static String getMethodComment(IMethod method, IMethod overridden, String lineDelimiter) throws CoreException { + return StubUtility.getMethodComment(method, overridden, lineDelimiter); + } + + /** + * Returns the content of the body for a method or constructor using the method body templates. + * null is returned if the template is empty. + *

The returned string is unformatted and not indented. + * + * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. + * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer + * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName Name of the method. + * @param isConstructor Defines if the created body is for a constructor. + * @param bodyStatement The code to be entered at the place of the variable ${body_statement}. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the constructed body content or null if + * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). + * @throws CoreException Thrown when the evaluation of the code template fails. + */ + public static String getMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, boolean isConstructor, String bodyStatement, String lineDelimiter) throws CoreException { + return StubUtility.getMethodBodyContent(isConstructor, cu.getJavaProject(), declaringTypeName, methodName, bodyStatement, lineDelimiter); + } + + /** + * Returns the content of body for a getter method using the getter method body template. + * null is returned if the template is empty. + *

The returned string is unformatted and not indented. + * + * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. + * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer + * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName The name of the getter method. + * @param fieldName The name of the field to get in the getter method, corresponding to the template variable for ${field}. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the constructed body content or null if + * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). + * @throws CoreException Thrown when the evaluation of the code template fails. + * @since 3.0 + */ + public static String getGetterMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String lineDelimiter) throws CoreException { + return StubUtility.getGetterMethodBodyContent(cu.getJavaProject(), declaringTypeName, methodName, fieldName, lineDelimiter); + } + + /** + * Returns the content of body for a setter method using the setter method body template. + * null is returned if the template is empty. + *

The returned string is unformatted and not indented. + * + * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. + * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer + * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName The name of the setter method. + * @param fieldName The name of the field to be set in the setter method, corresponding to the template variable for ${field}. + * @param paramName The name of the parameter passed to the setter method, corresponding to the template variable for $(param). + * @param lineDelimiter The line delimiter to be used. + * @return Returns the constructed body content or null if + * the comment code template is empty. The returned string is unformatted and and has no indent (formatting required). + * @throws CoreException Thrown when the evaluation of the code template fails. + * @since 3.0 + */ + public static String getSetterMethodBodyContent(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String paramName, String lineDelimiter) throws CoreException { + return StubUtility.getSetterMethodBodyContent(cu.getJavaProject(), declaringTypeName, methodName, fieldName, paramName, lineDelimiter); + } + + /** + * Returns the comment for a getter method using the getter comment template. + * null is returned if the template is empty. + *

The returned string is unformatted and not indented. + * + * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. + * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer + * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName Name of the method. + * @param fieldName Name of the field to get. + * @param fieldType The type of the field to get. + * @param bareFieldName The field name without prefix or suffix. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the generated getter comment or null if the + * code template is empty. The returned content is not indented. + * @throws CoreException Thrown when the evaluation of the code template fails. + * @since 3.0 + */ + public static String getGetterComment(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String fieldType, String bareFieldName, String lineDelimiter) throws CoreException { + return StubUtility.getGetterComment(cu, declaringTypeName, methodName, fieldName, fieldType, bareFieldName, lineDelimiter); + } + + /** + * Returns the comment for a setter method using the setter method body template. + * null is returned if the template is empty. + *

The returned string is unformatted and not indented. + * + * @param cu The compilation unit to which the method belongs. The compilation unit does not need to exist. + * @param declaringTypeName Name of the type to which the method belongs. For inner types the name must be qualified and include the outer + * types names (dot separated). See {@link net.sourceforge.phpdt.core.IType#getTypeQualifiedName(char)}. + * @param methodName Name of the method. + * @param fieldName Name of the field that is set. + * @param fieldType The type of the field that is to set. + * @param paramName The name of the parameter that used to set. + * @param bareFieldName The field name without prefix or suffix. + * @param lineDelimiter The line delimiter to be used. + * @return Returns the generated setter comment or null if the + * code template is empty. The returned comment is not indented. + * @throws CoreException Thrown when the evaluation of the code template fails. + * @since 3.0 + */ + public static String getSetterComment(ICompilationUnit cu, String declaringTypeName, String methodName, String fieldName, String fieldType, String paramName, String bareFieldName, String lineDelimiter) throws CoreException { + return StubUtility.getSetterComment(cu, declaringTypeName, methodName, fieldName, fieldType, paramName, bareFieldName, lineDelimiter); + } +} diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java index 52017fc..f751f9f 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/PreferenceConstants.java @@ -147,14 +147,24 @@ public class PreferenceConstants { * @see #CODEGEN_USE_GETTERSETTER_SUFFIX */ public static final String CODEGEN_GETTERSETTER_SUFFIX = "net.sourceforge.phpdt.ui.gettersetter.suffix.list"; //$NON-NLS-1$ + /** + * A named preference that controls if comment stubs will be added + * automatically to newly created types and methods. + *

+ * Value is of type Boolean. + *

+ * @since 2.1 + */ + public static final String CODEGEN_ADD_COMMENTS= "net.sourceforge.phpdt.ui.phpdoc"; //$NON-NLS-1$ /** * A name preference that controls if a JavaDoc stub gets added to newly created types and methods. *

* Value is of type Boolean. *

+ * @deprecated Use CODEGEN_ADD_COMMENTS instead (Name is more precise). */ - public static final String CODEGEN__JAVADOC_STUBS = "net.sourceforge.phpdt.ui.phpdoc"; //$NON-NLS-1$ +// public static final String CODEGEN__JAVADOC_STUBS = CODEGEN_ADD_COMMENTS; //$NON-NLS-1$ /** * A named preference that controls if a non-phpdoc comment gets added to methods generated via the @@ -2256,14 +2266,14 @@ public final static String EDITOR_TEXT_FONT= "net.sourceforge.phpdt.ui.editors.t store.setDefault(PreferenceConstants.CODEGEN_USE_GETTERSETTER_SUFFIX, false); store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_PREFIX, "fg, f, _$, _, m_"); //$NON-NLS-1$ store.setDefault(PreferenceConstants.CODEGEN_GETTERSETTER_SUFFIX, "_"); //$NON-NLS-1$ - store.setDefault(PreferenceConstants.CODEGEN__JAVADOC_STUBS, true); + store.setDefault(PreferenceConstants.CODEGEN_ADD_COMMENTS, true); store.setDefault(PreferenceConstants.CODEGEN__NON_JAVADOC_COMMENTS, false); store.setDefault(PreferenceConstants.CODEGEN__FILE_COMMENTS, false); // MembersOrderPreferencePage store.setDefault(PreferenceConstants.APPEARANCE_MEMBER_SORT_ORDER, "T,SI,SF,SM,I,F,C,M"); //$NON-NLS-1$ // must add here to guarantee that it is the first in the listener list - // store.addPropertyChangeListener(PHPeclipsePlugin.getDefault().getMemberOrderPreferenceCache()); + store.addPropertyChangeListener(PHPeclipsePlugin.getDefault().getMemberOrderPreferenceCache()); // PHPEditorPreferencePage /* diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java index 582eda6..0d8a251 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpdt/ui/wizards/NewTypeWizardPage.java @@ -18,6 +18,7 @@ import net.sourceforge.phpdt.core.IBuffer; import net.sourceforge.phpdt.core.ICompilationUnit; import net.sourceforge.phpdt.core.IJavaElement; import net.sourceforge.phpdt.core.IPackageFragment; +import net.sourceforge.phpdt.core.IPackageFragmentRoot; import net.sourceforge.phpdt.core.ISourceRange; import net.sourceforge.phpdt.core.IType; import net.sourceforge.phpdt.core.ToolFactory; @@ -28,6 +29,7 @@ import net.sourceforge.phpdt.externaltools.internal.ui.StatusInfo; import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; import net.sourceforge.phpdt.internal.corext.template.php.JavaContext; import net.sourceforge.phpdt.internal.corext.template.php.Templates; +import net.sourceforge.phpdt.internal.corext.util.JavaModelUtil; import net.sourceforge.phpdt.internal.ui.PHPUiImages; import net.sourceforge.phpdt.internal.ui.util.SWTUtil; import net.sourceforge.phpdt.internal.ui.wizards.NewWizardMessages; @@ -43,6 +45,7 @@ import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.Separator; import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonDialogField; import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringButtonStatusDialogField; import net.sourceforge.phpdt.internal.ui.wizards.dialogfields.StringDialogField; +import net.sourceforge.phpdt.ui.CodeGeneration; import net.sourceforge.phpdt.ui.PreferenceConstants; import net.sourceforge.phpeclipse.PHPeclipsePlugin; @@ -1321,17 +1324,17 @@ public abstract class NewTypeWizardPage extends NewContainerWizardPage { // if (!isInnerClass) { lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ // -// ICompilationUnit parentCU = pack.createCompilationUnit(clName + ".php", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$ +// ICompilationUnit parentCU = pack.createCompilationUnit(clName + ".php", "", false, new SubProgressMonitor(monitor, 2)); //$NON-NLS-1$ //$NON-NLS-2$ // createdWorkingCopy = (ICompilationUnit) parentCU.getSharedWorkingCopy(null, JavaUI.getBufferFactory(), null); // // imports = new ImportsStructure(createdWorkingCopy, prefOrder, threshold, false); // // add an import that will be removed again. Having this import solves 14661 // imports.addImport(pack.getElementName(), getTypeName()); // -// String typeContent = constructTypeStub(new ImportsManager(imports), lineDelimiter); -// + String typeContent = constructTypeStub(lineDelimiter);//new ImportsManager(imports), lineDelimiter); + // String cuContent = constructCUContent(parentCU, typeContent, lineDelimiter); -// + // createdWorkingCopy.getBuffer().setContents(cuContent); // createdType = createdWorkingCopy.getType(clName); @@ -1493,25 +1496,25 @@ public abstract class NewTypeWizardPage extends NewContainerWizardPage { /* * Called from createType to construct the source for this type */ - // private String constructTypeStub(ImportsManager imports, String lineDelimiter) { - // StringBuffer buf= new StringBuffer(); - // - // int modifiers= getModifiers(); - // buf.append(Flags.toString(modifiers)); - // if (modifiers != 0) { - // buf.append(' '); - // } - // buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ - // buf.append(getTypeName()); - // writeSuperClass(buf, imports); - // writeSuperInterfaces(buf, imports); - // buf.append('{'); - // buf.append(lineDelimiter); - // buf.append(lineDelimiter); - // buf.append('}'); - // buf.append(lineDelimiter); - // return buf.toString(); - // } + private String constructTypeStub(String lineDelimiter) { // ImportsManager imports, String lineDelimiter) { + StringBuffer buf= new StringBuffer(); + + int modifiers= getModifiers(); + buf.append(Flags.toString(modifiers)); + if (modifiers != 0) { + buf.append(' '); + } + buf.append(fIsClass ? "class " : "interface "); //$NON-NLS-2$ //$NON-NLS-1$ + buf.append(getTypeName()); +// writeSuperClass(buf, imports); +// writeSuperInterfaces(buf, imports); + buf.append('{'); + buf.append(lineDelimiter); + buf.append(lineDelimiter); + buf.append('}'); + buf.append(lineDelimiter); + return buf.toString(); + } /** * @deprecated Overwrite createTypeMembers(IType, IImportsManager, IProgressMonitor) instead @@ -1582,24 +1585,24 @@ public abstract class NewTypeWizardPage extends NewContainerWizardPage { * @return the type comment or null if a type comment * is not desired */ - // protected String getTypeComment(ICompilationUnit parentCU) { - // if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) { - // try { - // StringBuffer typeName= new StringBuffer(); - // if (isEnclosingTypeSelected()) { - // typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.'); - // } - // typeName.append(getTypeName()); - // String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), String.valueOf('\n')); - // if (comment != null && isValidComment(comment)) { - // return comment; - // } - // } catch (CoreException e) { - // PHPeclipsePlugin.log(e); - // } - // } - // return null; - // } + protected String getTypeComment(ICompilationUnit parentCU) { + if (PreferenceConstants.getPreferenceStore().getBoolean(PreferenceConstants.CODEGEN_ADD_COMMENTS)) { + try { + StringBuffer typeName= new StringBuffer(); + if (isEnclosingTypeSelected()) { + typeName.append(JavaModelUtil.getTypeQualifiedName(getEnclosingType())).append('.'); + } + typeName.append(getTypeName()); + String comment= CodeGeneration.getTypeComment(parentCU, typeName.toString(), String.valueOf('\n')); + if (comment != null && isValidComment(comment)) { + return comment; + } + } catch (CoreException e) { + PHPeclipsePlugin.log(e); + } + } + return null; + } /** * @deprecated Use getTemplate(String,ICompilationUnit,int) diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java index 341a36a..b0b2811 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/PHPeclipsePlugin.java @@ -31,6 +31,7 @@ import net.sourceforge.phpdt.externaltools.internal.model.ColorManager; import net.sourceforge.phpdt.externaltools.internal.model.ExternalToolsPlugin; import net.sourceforge.phpdt.internal.core.BatchOperation; import net.sourceforge.phpdt.internal.core.JavaModelManager; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; import net.sourceforge.phpdt.internal.corext.template.php.HTMLContextType; import net.sourceforge.phpdt.internal.corext.template.php.JavaContextType; import net.sourceforge.phpdt.internal.corext.template.php.JavaDocContextType; @@ -1530,7 +1531,7 @@ public class PHPeclipsePlugin extends AbstractUIPlugin implements if (fCodeTemplateContextTypeRegistry == null) { fCodeTemplateContextTypeRegistry= new ContributionContextTypeRegistry(); -// CodeTemplateContextType.registerContextTypes(fCodeTemplateContextTypeRegistry); + CodeTemplateContextType.registerContextTypes(fCodeTemplateContextTypeRegistry); } return fCodeTemplateContextTypeRegistry; diff --git a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java index d172145..ea1a3fb 100644 --- a/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java +++ b/net.sourceforge.phpeclipse/src/net/sourceforge/phpeclipse/wizards/PHPFileWizard.java @@ -17,6 +17,11 @@ import java.io.IOException; import java.io.InputStream; import java.lang.reflect.InvocationTargetException; +import net.sourceforge.phpdt.internal.corext.codemanipulation.StubUtility; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContext; +import net.sourceforge.phpdt.internal.corext.template.php.CodeTemplateContextType; +import net.sourceforge.phpeclipse.PHPeclipsePlugin; + import org.eclipse.core.resources.IContainer; import org.eclipse.core.resources.IFile; import org.eclipse.core.resources.IResource; @@ -29,12 +34,14 @@ import org.eclipse.core.runtime.Path; import org.eclipse.core.runtime.Status; import org.eclipse.jface.dialogs.MessageDialog; import org.eclipse.jface.operation.IRunnableWithProgress; +import org.eclipse.jface.text.templates.Template; import org.eclipse.jface.viewers.ISelection; import org.eclipse.jface.viewers.IStructuredSelection; import org.eclipse.jface.wizard.Wizard; import org.eclipse.ui.INewWizard; import org.eclipse.ui.IWorkbench; import org.eclipse.ui.IWorkbenchPage; +import org.eclipse.ui.IWorkbenchWizard; import org.eclipse.ui.PartInitException; import org.eclipse.ui.PlatformUI; import org.eclipse.ui.ide.IDE; @@ -177,20 +184,36 @@ public class PHPFileWizard extends Wizard implements INewWizard { * We will initialize file contents with a sample text. */ private InputStream openContentStream() { - StringBuffer contents = new StringBuffer(""); - return new ByteArrayInputStream(contents.toString().getBytes()); + try { + Template template= PHPeclipsePlugin.getDefault().getCodeTemplateStore().findTemplate(CodeTemplateContextType.NEWTYPE); + if (template == null) { + return null; + } + String lineDelimiter = System.getProperty("line.separator", "\n"); //$NON-NLS-1$ //$NON-NLS-2$ + CodeTemplateContext context= new CodeTemplateContext(template.getContextTypeId(), null, lineDelimiter); +// context.setCompilationUnitVariables(cu); + + + return new ByteArrayInputStream(StubUtility.evaluateTemplate(context, template).getBytes()); + } catch (CoreException e) { + e.printStackTrace(); + return null; + } + +// StringBuffer contents = new StringBuffer(""); +// return new ByteArrayInputStream(contents.toString().getBytes()); } private void throwCoreException(String message) throws CoreException { diff --git a/net.sourceforge.phpeclipse/templates/default-codetemplates.xml b/net.sourceforge.phpeclipse/templates/default-codetemplates.xml index 645b950..45d2b09 100644 --- a/net.sourceforge.phpeclipse/templates/default-codetemplates.xml +++ b/net.sourceforge.phpeclipse/templates/default-codetemplates.xml @@ -45,16 +45,15 @@ * ${see_to_overridden} */ - @@ -64,7 +63,7 @@ ${body_statement} - + diff --git a/net.sourceforge.phpeclipse/templates/default-templates.properties b/net.sourceforge.phpeclipse/templates/default-templates.properties index ca68397..a0c3f56 100644 --- a/net.sourceforge.phpeclipse/templates/default-templates.properties +++ b/net.sourceforge.phpeclipse/templates/default-templates.properties @@ -134,7 +134,7 @@ CodeTemplates.overridecomment.nonjd=(non-Javadoc) # ! Do not translate ${date} ! CodeTemplates.newfile.content1=Created on ${date} CodeTemplates.newfile.content2=To change the template for this generated file go to -CodeTemplates.newfile.content3=Window - Preferences - Java - Code Style - Code Templates +CodeTemplates.newfile.content3=Window - Preferences - PHPeclipse - PHP - Code Templates CodeTemplates.catchblock.tododesc=Auto-generated catch block CodeTemplates.methodstub.tododesc=Auto-generated method stub -- 1.7.1