Some Eclipse Foundation services are deprecated, or will be soon. Please ensure you've read this important communication.
View | Details | Raw Unified | Return to bug 39188 | Differences between
and this patch

Collapse All | Expand All

(-)core extension/org/eclipse/jdt/internal/corext/codemanipulation/CodeGenerationMessages.properties (+2 lines)
Lines 17-22 Link Here
17
17
18
AddUnimplementedMethodsOperation.description=Evaluating and adding unimplemented methods...
18
AddUnimplementedMethodsOperation.description=Evaluating and adding unimplemented methods...
19
19
20
AddCustomConstructorOperation.description=Evaluating and adding new constructor...
21
20
OrganizeImportsOperation.description=Organizing imports of {0}...
22
OrganizeImportsOperation.description=Organizing imports of {0}...
21
23
22
AddJavaDocStubOperation.description=Create Javadoc stub...
24
AddJavaDocStubOperation.description=Create Javadoc stub...
(-)ui/org/eclipse/jdt/internal/ui/IJavaHelpContextIds.java (+1 lines)
Lines 30-35 Link Here
30
	public static final String ADD_METHODSTUB_ACTION= 										PREFIX + "add_methodstub_action_context"; //$NON-NLS-1$
30
	public static final String ADD_METHODSTUB_ACTION= 										PREFIX + "add_methodstub_action_context"; //$NON-NLS-1$
31
	public static final String ADD_UNIMPLEMENTED_METHODS_ACTION= 					PREFIX + "add_unimplemented_methods_action_context"; //$NON-NLS-1$
31
	public static final String ADD_UNIMPLEMENTED_METHODS_ACTION= 					PREFIX + "add_unimplemented_methods_action_context"; //$NON-NLS-1$
32
	public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION= 			PREFIX + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$	
32
	public static final String ADD_UNIMPLEMENTED_CONSTRUCTORS_ACTION= 			PREFIX + "add_unimplemented_constructors_action_context"; //$NON-NLS-1$	
33
	public static final String CREATE_NEW_CONSTRUCTOR_ACTION= 					PREFIX + "create_new_constructor_action_context"; //$NON-NLS-1$	
33
	public static final String SHOW_IN_PACKAGEVIEW_ACTION= 								PREFIX + "show_in_packageview_action_context"; //$NON-NLS-1$
34
	public static final String SHOW_IN_PACKAGEVIEW_ACTION= 								PREFIX + "show_in_packageview_action_context"; //$NON-NLS-1$
34
	public static final String SHOW_IN_HIERARCHYVIEW_ACTION= 							PREFIX + "show_in_hierarchyview_action_context"; //$NON-NLS-1$
35
	public static final String SHOW_IN_HIERARCHYVIEW_ACTION= 							PREFIX + "show_in_hierarchyview_action_context"; //$NON-NLS-1$
35
	public static final String FOCUS_ON_SELECTION_ACTION= 								PREFIX + "focus_on_selection_action"; //$NON-NLS-1$
36
	public static final String FOCUS_ON_SELECTION_ACTION= 								PREFIX + "focus_on_selection_action"; //$NON-NLS-1$
(-)ui/org/eclipse/jdt/internal/ui/actions/ActionMessages.properties (-1 / +16 lines)
Lines 82-88 Link Here
82
AddGetterSetterAction.error.actionfailed=Generating Getters and Setters Failed.
82
AddGetterSetterAction.error.actionfailed=Generating Getters and Setters Failed.
83
AddGetterSetterAction.error.fieldNotExisting=The field ''{0}'' has been removed in the editor.
83
AddGetterSetterAction.error.fieldNotExisting=The field ''{0}'' has been removed in the editor.
84
AddGetterSetterAction.not_applicable=Operation not applicable to current text selection. A field has to be selected or a type that declares fields.
84
AddGetterSetterAction.not_applicable=Operation not applicable to current text selection. A field has to be selected or a type that declares fields.
85
AddGetterSetterAction.interface_not_applicable=The Generate Getters and Setters operation is not applicable on interfaces.
85
AddGetterSetterAction.interface_not_applicable=The Generate Getters and Setters operation is not applicable to interfaces.
86
AddGetterSetterAction.read_only=The compilation unit in which the field ''{0}'' is declared is read only.
86
AddGetterSetterAction.read_only=The compilation unit in which the field ''{0}'' is declared is read only.
87
87
88
AddGetterSetterAction.QueryDialog.title=Generate Getters and Setters
88
AddGetterSetterAction.QueryDialog.title=Generate Getters and Setters
Lines 119-124 Link Here
119
AddUnimplementedConstructorsAction.error.nothing_found=There are no constructors from the superclass which may be added.
119
AddUnimplementedConstructorsAction.error.nothing_found=There are no constructors from the superclass which may be added.
120
AddUnimplementedConstructorsAction.dialog.title=Add Constructors from Superclass
120
AddUnimplementedConstructorsAction.dialog.title=Add Constructors from Superclass
121
AddUnimplementedConstructorsAction.dialog.label=&Select constructors to implement:
121
AddUnimplementedConstructorsAction.dialog.label=&Select constructors to implement:
122
123
CreateNewConstructorAction.label=Create New &Constructor using Fields...
124
CreateNewConstructorAction.description=Create New Constructor using fields
125
CreateNewConstructorAction.tooltip=Create New Constructor using Fields
126
CreateNewConstructorAction.error.title=Create New Constructor using Fields
127
CreateNewConstructorAction.error.type_removed_in_editor=Input type has been removed in editor.
128
CreateNewConstructorAction.not_applicable=The operation is not applicable to the current selection.
129
CreateNewConstructorAction.fields_selected={0} of {1} selected.
130
CreateNewConstructorAction.dialog.title=Create New Constructor using Fields
131
CreateNewConstructorAction.dialog.label=&Select fields to initialize:
132
CreateNewConstructorAction.interface_not_applicable=The Create New Constructor operation is not applicable to interfaces.
133
CreateNewConstructorAction.typeContainsNoFields.message=The type contains no fields.
134
135
CreateNewConstructorSelectionDialog.up_button=&Up
136
CreateNewConstructorSelectionDialog.down_button=&Down
122
137
123
AddJavaDocStubAction.label=Add &Javadoc Comment
138
AddJavaDocStubAction.label=Add &Javadoc Comment
124
AddJavaDocStubAction.description=Add a Javadoc comment stub to the member element
139
AddJavaDocStubAction.description=Add a Javadoc comment stub to the member element
(-)ui/org/eclipse/jdt/ui/actions/GenerateActionGroup.java (-4 / +15 lines)
Lines 35-47 Link Here
35
import org.eclipse.ui.texteditor.ConvertLineDelimitersAction;
35
import org.eclipse.ui.texteditor.ConvertLineDelimitersAction;
36
import org.eclipse.ui.texteditor.IUpdate;
36
import org.eclipse.ui.texteditor.IUpdate;
37
37
38
import org.eclipse.jdt.ui.IContextMenuConstants;
39
38
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
40
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
39
import org.eclipse.jdt.internal.ui.actions.AddTaskAction;
41
import org.eclipse.jdt.internal.ui.actions.AddTaskAction;
40
import org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction;
42
import org.eclipse.jdt.internal.ui.javaeditor.AddImportOnSelectionAction;
41
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
43
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
42
44
43
import org.eclipse.jdt.ui.IContextMenuConstants;
44
45
/**
45
/**
46
 * Action group that adds the source and generate actions to a part's context
46
 * Action group that adds the source and generate actions to a part's context
47
 * menu and installs handlers for the corresponding global menu actions.
47
 * menu and installs handlers for the corresponding global menu actions.
Lines 64-69 Link Here
64
	private AddGetterSetterAction fAddGetterSetter;
64
	private AddGetterSetterAction fAddGetterSetter;
65
	private AddDelegateMethodsAction fAddDelegateMethods;
65
	private AddDelegateMethodsAction fAddDelegateMethods;
66
	private AddUnimplementedConstructorsAction fAddUnimplementedConstructors;
66
	private AddUnimplementedConstructorsAction fAddUnimplementedConstructors;
67
	private CreateNewConstructorAction fCreateNewConstructor;
67
	private AddJavaDocStubAction fAddJavaDocStub;
68
	private AddJavaDocStubAction fAddJavaDocStub;
68
	private AddBookmarkAction fAddBookmark;
69
	private AddBookmarkAction fAddBookmark;
69
	private AddTaskAction fAddTaskAction;
70
	private AddTaskAction fAddTaskAction;
Lines 116-126 Link Here
116
		fAddDelegateMethods= new AddDelegateMethodsAction(editor);
117
		fAddDelegateMethods= new AddDelegateMethodsAction(editor);
117
		fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS);
118
		fAddDelegateMethods.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_DELEGATE_METHODS);
118
		editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$
119
		editor.setAction("AddDelegateMethods", fAddDelegateMethods); //$NON-NLS-1$
119
		
120
			
120
		fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor);
121
		fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(editor);
121
		fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS);
122
		fAddUnimplementedConstructors.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_UNIMPLEMENTED_CONTRUCTORS);
122
		editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$		
123
		editor.setAction("AddUnimplementedConstructors", fAddUnimplementedConstructors); //$NON-NLS-1$		
123
		
124
125
		fCreateNewConstructor= new CreateNewConstructorAction(editor);
126
		fCreateNewConstructor.setActionDefinitionId(IJavaEditorActionDefinitionIds.CREATE_NEW_CONSTRUCTOR);
127
		editor.setAction("CreateNewConstructor", fCreateNewConstructor); //$NON-NLS-1$		
128
124
		fAddJavaDocStub= new AddJavaDocStubAction(editor);
129
		fAddJavaDocStub= new AddJavaDocStubAction(editor);
125
		fAddJavaDocStub.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_JAVADOC_COMMENT);
130
		fAddJavaDocStub.setActionDefinitionId(IJavaEditorActionDefinitionIds.ADD_JAVADOC_COMMENT);
126
		editor.setAction("AddJavadocComment", fAddJavaDocStub); //$NON-NLS-1$		
131
		editor.setAction("AddJavadocComment", fAddJavaDocStub); //$NON-NLS-1$		
Lines 183-188 Link Here
183
		fAddGetterSetter= new AddGetterSetterAction(site);
188
		fAddGetterSetter= new AddGetterSetterAction(site);
184
		fAddDelegateMethods= new AddDelegateMethodsAction(site);
189
		fAddDelegateMethods= new AddDelegateMethodsAction(site);
185
		fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site);
190
		fAddUnimplementedConstructors= new AddUnimplementedConstructorsAction(site);
191
		fCreateNewConstructor= new CreateNewConstructorAction(site);
186
		fAddJavaDocStub= new AddJavaDocStubAction(site);
192
		fAddJavaDocStub= new AddJavaDocStubAction(site);
187
		fAddBookmark= new AddBookmarkAction(site.getShell());
193
		fAddBookmark= new AddBookmarkAction(site.getShell());
188
		fAddToClasspathAction= new AddToClasspathAction(site);
194
		fAddToClasspathAction= new AddToClasspathAction(site);
Lines 197-202 Link Here
197
		fAddGetterSetter.update(selection);
203
		fAddGetterSetter.update(selection);
198
		fAddDelegateMethods.update(selection);
204
		fAddDelegateMethods.update(selection);
199
		fAddUnimplementedConstructors.update(selection);	
205
		fAddUnimplementedConstructors.update(selection);	
206
		fCreateNewConstructor.update(selection);
200
		fAddJavaDocStub.update(selection);
207
		fAddJavaDocStub.update(selection);
201
		fAddToClasspathAction.update(selection);
208
		fAddToClasspathAction.update(selection);
202
		fRemoveFromClasspathAction.update(selection);
209
		fRemoveFromClasspathAction.update(selection);
Lines 216-221 Link Here
216
		registerSelectionListener(provider, fAddGetterSetter);
223
		registerSelectionListener(provider, fAddGetterSetter);
217
		registerSelectionListener(provider, fAddDelegateMethods);
224
		registerSelectionListener(provider, fAddDelegateMethods);
218
		registerSelectionListener(provider, fAddUnimplementedConstructors);
225
		registerSelectionListener(provider, fAddUnimplementedConstructors);
226
		registerSelectionListener(provider, fCreateNewConstructor);
219
		registerSelectionListener(provider, fAddJavaDocStub);
227
		registerSelectionListener(provider, fAddJavaDocStub);
220
		registerSelectionListener(provider, fAddBookmark);
228
		registerSelectionListener(provider, fAddBookmark);
221
		registerSelectionListener(provider, fAddToClasspathAction);
229
		registerSelectionListener(provider, fAddToClasspathAction);
Lines 288-293 Link Here
288
		added+= addAction(result, fAddGetterSetter);
296
		added+= addAction(result, fAddGetterSetter);
289
		added+= addAction(result, fAddDelegateMethods);
297
		added+= addAction(result, fAddDelegateMethods);
290
		added+= addAction(result, fAddUnimplementedConstructors);
298
		added+= addAction(result, fAddUnimplementedConstructors);
299
		added+= addAction(result, fCreateNewConstructor);
291
		added+= addAction(result, fAddJavaDocStub);
300
		added+= addAction(result, fAddJavaDocStub);
292
		result.add(new Separator());		
301
		result.add(new Separator());		
293
		added+= addAction(result, fSurroundWithTryCatch);
302
		added+= addAction(result, fSurroundWithTryCatch);
Lines 308-313 Link Here
308
		added+= addAction(result, fAddGetterSetter);
317
		added+= addAction(result, fAddGetterSetter);
309
		added+= addAction(result, fAddDelegateMethods);
318
		added+= addAction(result, fAddDelegateMethods);
310
		added+= addAction(result, fAddUnimplementedConstructors);
319
		added+= addAction(result, fAddUnimplementedConstructors);
320
		added+= addAction(result, fCreateNewConstructor);
311
		added+= addAction(result, fAddJavaDocStub);
321
		added+= addAction(result, fAddJavaDocStub);
312
		added+= addAction(result, fAddToClasspathAction);
322
		added+= addAction(result, fAddToClasspathAction);
313
		added+= addAction(result, fRemoveFromClasspathAction);
323
		added+= addAction(result, fRemoveFromClasspathAction);
Lines 342-347 Link Here
342
		actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter);
352
		actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_GETTER_SETTER, fAddGetterSetter);
343
		actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_DELEGATE_METHODS, fAddDelegateMethods);
353
		actionBar.setGlobalActionHandler(JdtActionConstants.GENERATE_DELEGATE_METHODS, fAddDelegateMethods);
344
		actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors);
354
		actionBar.setGlobalActionHandler(JdtActionConstants.ADD_CONSTRUCTOR_FROM_SUPERCLASS, fAddUnimplementedConstructors);
355
		actionBar.setGlobalActionHandler(JdtActionConstants.CREATE_NEW_CONSTRUCTOR, fCreateNewConstructor);
345
		actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub);
356
		actionBar.setGlobalActionHandler(JdtActionConstants.ADD_JAVA_DOC_COMMENT, fAddJavaDocStub);
346
		actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings);
357
		actionBar.setGlobalActionHandler(JdtActionConstants.EXTERNALIZE_STRINGS, fExternalizeStrings);
347
		actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize);
358
		actionBar.setGlobalActionHandler(JdtActionConstants.FIND_STRINGS_TO_EXTERNALIZE, fFindStringsToExternalize);
(-)ui/org/eclipse/jdt/ui/actions/IJavaEditorActionDefinitionIds.java (+6 lines)
Lines 183-188 Link Here
183
	public static final String ADD_UNIMPLEMENTED_CONTRUCTORS= "org.eclipse.jdt.ui.edit.text.java.add.unimplemented.constructors"; //$NON-NLS-1$
183
	public static final String ADD_UNIMPLEMENTED_CONTRUCTORS= "org.eclipse.jdt.ui.edit.text.java.add.unimplemented.constructors"; //$NON-NLS-1$
184
	
184
	
185
	/**
185
	/**
186
	 * Action definition ID of the source ->create new constructor action
187
	 * (value <code>"org.eclipse.jdt.ui.edit.text.java.create.new.constructor"</code>).
188
	 */
189
	public static final String CREATE_NEW_CONSTRUCTOR= "org.eclipse.jdt.ui.edit.text.java.create.new.constructor"; //$NON-NLS-1$
190
191
	/**
186
	 * Action definition ID of the source -> generate setter/getter action
192
	 * Action definition ID of the source -> generate setter/getter action
187
	 * (value <code>"org.eclipse.jdt.ui.edit.text.java.create.getter.setter"</code>).
193
	 * (value <code>"org.eclipse.jdt.ui.edit.text.java.create.getter.setter"</code>).
188
	 */
194
	 */
(-)ui/org/eclipse/jdt/ui/actions/JdtActionConstants.java (+6 lines)
Lines 176-181 Link Here
176
	public static final String ADD_CONSTRUCTOR_FROM_SUPERCLASS= "org.eclipse.jdt.ui.actions.AddConstructorFromSuperclass"; //$NON-NLS-1$
176
	public static final String ADD_CONSTRUCTOR_FROM_SUPERCLASS= "org.eclipse.jdt.ui.actions.AddConstructorFromSuperclass"; //$NON-NLS-1$
177
	
177
	
178
	/**
178
	/**
179
	 * Source menu: name of standard create New Constructor global action
180
	 * (value <code>"org.eclipse.jdt.ui.actions.CreateNewConstructor"</code>).
181
	 */
182
	public static final String CREATE_NEW_CONSTRUCTOR= "org.eclipse.jdt.ui.actions.CreateNewConstructor"; //$NON-NLS-1$
183
184
	/**
179
	 * Source menu: name of standard Add Javadoc Comment global action
185
	 * Source menu: name of standard Add Javadoc Comment global action
180
	 * (value <code>"org.eclipse.jdt.ui.actions.AddJavaDocComment"</code>).
186
	 * (value <code>"org.eclipse.jdt.ui.actions.AddJavaDocComment"</code>).
181
	 */
187
	 */
(-)core (+151 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2003 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials 
4
 * are made available under the terms of the Common Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/cpl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.internal.corext.codemanipulation;
12
13
import org.eclipse.core.resources.IWorkspaceRunnable;
14
import org.eclipse.core.runtime.CoreException;
15
import org.eclipse.core.runtime.IProgressMonitor;
16
import org.eclipse.core.runtime.NullProgressMonitor;
17
import org.eclipse.core.runtime.OperationCanceledException;
18
import org.eclipse.core.runtime.SubProgressMonitor;
19
20
import org.eclipse.jdt.core.Flags;
21
import org.eclipse.jdt.core.ICompilationUnit;
22
import org.eclipse.jdt.core.IField;
23
import org.eclipse.jdt.core.IJavaElement;
24
import org.eclipse.jdt.core.IJavaProject;
25
import org.eclipse.jdt.core.IMethod;
26
import org.eclipse.jdt.core.IType;
27
import org.eclipse.jdt.core.ITypeHierarchy;
28
import org.eclipse.jdt.core.JavaModelException;
29
import org.eclipse.jdt.core.NamingConventions;
30
import org.eclipse.jdt.core.Signature;
31
32
import org.eclipse.jdt.internal.corext.codemanipulation.StubUtility.GenStubSettings;
33
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
34
35
/**
36
 * Creates a custom constructor with fields initialized.
37
 * If the type is open in an editor, be sure to pass over the types working working copy.
38
 */
39
public class AddCustomConstructorOperation implements IWorkspaceRunnable {
40
	private IJavaElement fInsertPosition;
41
	private IField[] fSelected;
42
	private IType fType;
43
	private IMethod fConstructorCreated;
44
	private boolean fDoSave;
45
	private CodeGenerationSettings fSettings;
46
	
47
	public AddCustomConstructorOperation(IType type, CodeGenerationSettings settings, IField[] selected, boolean save, IJavaElement insertPosition) {
48
		super();
49
		fType= type;
50
		fDoSave= save;
51
		fConstructorCreated= null;
52
		fSettings= settings;
53
		fSelected= selected;
54
		fInsertPosition= insertPosition;
55
	}
56
57
	/**
58
	 * Runs the operation.
59
	 * @throws OperationCanceledException Runtime error thrown when operation is cancelled.
60
	 */
61
	public void run(IProgressMonitor monitor) throws CoreException, OperationCanceledException {
62
		try {
63
			if (monitor == null) {
64
				monitor= new NullProgressMonitor();
65
			}			
66
			monitor.setTaskName(CodeGenerationMessages.getString("AddCustomConstructorOperation.description")); //$NON-NLS-1$
67
			monitor.beginTask("", 3); //$NON-NLS-1$
68
			
69
			ITypeHierarchy hierarchy= fType.newSupertypeHierarchy(new SubProgressMonitor(monitor, 1));
70
			monitor.worked(1);
71
			
72
			ImportsStructure imports= new ImportsStructure(fType.getCompilationUnit(), fSettings.importOrder, fSettings.importThreshold, true);
73
			String defaultConstructor= getDefaultConstructor(fType, hierarchy, imports);
74
			int firstParenIndex= defaultConstructor.indexOf("(") + 1; //$NON-NLS-1$
75
			int closingBraceIndex= defaultConstructor.indexOf("}"); //$NON-NLS-1$
76
			StringBuffer buf= new StringBuffer(defaultConstructor.substring(0, firstParenIndex));
77
			String[] params= new String[fSelected.length];
78
			for (int i= 0; i < fSelected.length; i++) {
79
				buf.append(Signature.toString(fSelected[i].getTypeSignature()));				
80
				buf.append(" "); //$NON-NLS-1$
81
				IJavaProject project= fSelected[i].getJavaProject();
82
				String accessName= NamingConventions.removePrefixAndSuffixForFieldName(project, fSelected[i].getElementName(), fSelected[i].getFlags());
83
				if (accessName.length() > 0) {
84
					char first= accessName.charAt(0);
85
					if (Character.isLowerCase(first)) {
86
						accessName= Character.toUpperCase(first) + accessName.substring(1);
87
					}
88
				}
89
90
				String paramName= StubUtility.guessArgumentName(project, accessName, new String[0]);
91
				
92
				buf.append(params[i]= paramName);
93
				if (i != fSelected.length - 1)
94
					buf.append(","); //$NON-NLS-1$					
95
			}
96
			buf.append(defaultConstructor.substring(firstParenIndex, closingBraceIndex));
97
			for (int i= 0; i < fSelected.length; i++) {
98
				String fieldName= fSelected[i].getElementName();
99
				boolean isStatic= Flags.isStatic(fSelected[i].getFlags());
100
				if (isStatic) {
101
					buf.append(fSelected[i].getParent().getElementName());
102
					buf.append("."); //$NON-NLS-1$
103
				}	
104
				else if ((fSettings.useKeywordThis) || params[i].equals(fieldName))
105
					buf.append("this."); //$NON-NLS-1$				
106
				buf.append(fieldName);
107
				buf.append(" = "); //$NON-NLS-1$
108
				buf.append(params[i]);
109
				buf.append(";\n"); //$NON-NLS-1$
110
			}
111
			buf.append("}"); //$NON-NLS-1$
112
			
113
			String lineDelim= StubUtility.getLineDelimiterUsed(fType);
114
			int indent= StubUtility.getIndentUsed(fType) + 1;
115
				
116
			String formattedContent= StubUtility.codeFormat(buf.toString(), indent, lineDelim) + lineDelim;
117
			fConstructorCreated= fType.createMethod(formattedContent, fInsertPosition, true, null);
118
119
			monitor.worked(1);		
120
			imports.create(fDoSave, null);
121
			monitor.worked(1);
122
		} finally {
123
			monitor.done();
124
		}
125
	}
126
		
127
	private String getDefaultConstructor(IType type, ITypeHierarchy hierarchy, ImportsStructure imports)  {
128
		try {
129
			ICompilationUnit cu= type.getCompilationUnit();
130
			GenStubSettings genStubSettings= new GenStubSettings(fSettings);	
131
				
132
			IType objectType= type.getJavaProject().findType("java.lang.Object"); //$NON-NLS-1$
133
			IMethod curr= objectType.getMethod("Object", new String[0]);  //$NON-NLS-1$
134
			IMethod defaultConstructor= JavaModelUtil.findMethodImplementationInHierarchy(hierarchy, type, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor());
135
			IMethod desc= JavaModelUtil.findMethodDeclarationInHierarchy(hierarchy, type, curr.getElementName(), curr.getParameterTypes(), curr.isConstructor());
136
			String str= StubUtility.genStub(cu, type.getElementName(), defaultConstructor, desc.getDeclaringType(), genStubSettings, imports);				
137
			return str;	
138
139
		} catch (JavaModelException e) {
140
		} catch (CoreException e) {
141
		}
142
		return null;
143
	}	
144
	
145
	/**
146
	 * Returns the created constructor. To be called after a sucessful run.
147
	 */	
148
	public IMethod getCreatedConstructor() {
149
		return fConstructorCreated;
150
	}	
151
}
(-)ui/org/eclipse/jdt/ui/actions/CreateNewConstructorAction.java (+545 lines)
Added Link Here
1
/*******************************************************************************
2
 * Copyright (c) 2000, 2003 IBM Corporation and others.
3
 * All rights reserved. This program and the accompanying materials 
4
 * are made available under the terms of the Common Public License v1.0
5
 * which accompanies this distribution, and is available at
6
 * http://www.eclipse.org/legal/cpl-v10.html
7
 * 
8
 * Contributors:
9
 *     IBM Corporation - initial API and implementation
10
 *******************************************************************************/
11
package org.eclipse.jdt.ui.actions;
12
13
import java.lang.reflect.InvocationTargetException;
14
import java.util.ArrayList;
15
import java.util.List;
16
17
import org.eclipse.core.runtime.CoreException;
18
import org.eclipse.core.runtime.IStatus;
19
20
import org.eclipse.swt.layout.GridLayout;
21
import org.eclipse.swt.widgets.Composite;
22
import org.eclipse.swt.widgets.Shell;
23
24
import org.eclipse.jface.dialogs.IDialogConstants;
25
import org.eclipse.jface.dialogs.MessageDialog;
26
import org.eclipse.jface.operation.IRunnableContext;
27
import org.eclipse.jface.text.IRewriteTarget;
28
import org.eclipse.jface.text.ITextSelection;
29
import org.eclipse.jface.viewers.CheckboxTreeViewer;
30
import org.eclipse.jface.viewers.ILabelProvider;
31
import org.eclipse.jface.viewers.IStructuredSelection;
32
import org.eclipse.jface.viewers.ITreeContentProvider;
33
import org.eclipse.jface.viewers.Viewer;
34
import org.eclipse.jface.window.Window;
35
36
import org.eclipse.ui.IEditorPart;
37
import org.eclipse.ui.IWorkbenchSite;
38
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
39
import org.eclipse.ui.help.WorkbenchHelp;
40
41
import org.eclipse.jdt.core.ICompilationUnit;
42
import org.eclipse.jdt.core.IField;
43
import org.eclipse.jdt.core.IJavaElement;
44
import org.eclipse.jdt.core.IMethod;
45
import org.eclipse.jdt.core.IType;
46
import org.eclipse.jdt.core.JavaModelException;
47
48
import org.eclipse.jdt.ui.JavaElementLabelProvider;
49
50
import org.eclipse.jdt.internal.corext.codemanipulation.AddCustomConstructorOperation;
51
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
52
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
53
import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
54
import org.eclipse.jdt.internal.ui.JavaPlugin;
55
import org.eclipse.jdt.internal.ui.actions.ActionMessages;
56
import org.eclipse.jdt.internal.ui.actions.ActionUtil;
57
import org.eclipse.jdt.internal.ui.actions.SelectionConverter;
58
import org.eclipse.jdt.internal.ui.actions.WorkbenchRunnableAdapter;
59
import org.eclipse.jdt.internal.ui.dialogs.SourceActionDialog;
60
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
61
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
62
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
63
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
64
import org.eclipse.jdt.internal.ui.util.BusyIndicatorRunnableContext;
65
import org.eclipse.jdt.internal.ui.util.ElementValidator;
66
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
67
68
69
public class CreateNewConstructorAction extends SelectionDispatchAction {
70
	
71
	private CompilationUnitEditor fEditor;
72
	private static final String fDialogTitle= ActionMessages.getString("CreateNewConstructorAction.error.title"); //$NON-NLS-1$
73
	
74
	/**
75
	 * Creates a new <code>CreateNewConstructorAction</code>. The action requires
76
	 * that the selection provided by the site's selection provider is of type <code>
77
	 * org.eclipse.jface.viewers.IStructuredSelection</code>.
78
	 * 
79
	 * @param site the site providing context information for this action
80
	 */
81
	public CreateNewConstructorAction(IWorkbenchSite site) {
82
		super(site);
83
		setText(ActionMessages.getString("CreateNewConstructorAction.label")); //$NON-NLS-1$
84
		setDescription(ActionMessages.getString("CreateNewConstructorAction.description")); //$NON-NLS-1$
85
		setToolTipText(ActionMessages.getString("CreateNewConstructorAction.tooltip")); //$NON-NLS-1$
86
		
87
		WorkbenchHelp.setHelp(this, IJavaHelpContextIds.CREATE_NEW_CONSTRUCTOR_ACTION);
88
	}
89
90
	/**
91
	 * Note: This constructor is for internal use only. Clients should not call this constructor.
92
	 */
93
	public CreateNewConstructorAction(CompilationUnitEditor editor) {
94
		this(editor.getEditorSite());
95
		fEditor= editor;
96
		setEnabled(checkEnabledEditor());
97
	}
98
	
99
	//---- Structured Viewer -----------------------------------------------------------
100
	
101
	/* (non-Javadoc)
102
	 * Method declared on SelectionDispatchAction
103
	 */
104
	public void selectionChanged(IStructuredSelection selection) {
105
		try {
106
			setEnabled(canEnable(selection));
107
		} catch (JavaModelException e) {
108
			// http://bugs.eclipse.org/bugs/show_bug.cgi?id=19253
109
			if (JavaModelUtil.filterNotPresentException(e))
110
				JavaPlugin.log(e);
111
			setEnabled(false);
112
		}
113
	}
114
	
115
	private boolean canEnable(IStructuredSelection selection) throws JavaModelException {
116
		if (getSelectedFields(selection) != null)
117
			return true;
118
119
		if ((selection.size() == 1) && (selection.getFirstElement() instanceof IType)) {
120
			IType type= (IType) selection.getFirstElement();
121
			return type.getCompilationUnit() != null && type.isClass(); // look if class: not cheap but done by all source generation actions
122
		}
123
124
		if ((selection.size() == 1) && (selection.getFirstElement() instanceof ICompilationUnit))
125
			return true;
126
127
		return false;
128
	}
129
	
130
	/* (non-Javadoc)
131
	 * Method declared on SelectionDispatchAction
132
	 */
133
	public void run(IStructuredSelection selection) {
134
		try {
135
			IField[] selectedFields= getSelectedFields(selection);
136
			// open an editor and work on a working copy
137
			IEditorPart editor= EditorUtility.openInEditor(getSelectedType(selection));	
138
			
139
			if (canRunOn(selectedFields)){
140
				run((IType)EditorUtility.getWorkingCopy(selectedFields[0].getDeclaringType()), selectedFields, editor, false);
141
				return;
142
			}	
143
			Object firstElement= selection.getFirstElement();
144
145
			if (firstElement instanceof IType)
146
				run((IType)EditorUtility.getWorkingCopy((IType)firstElement), new IField[0], editor, false);
147
			else if (firstElement instanceof ICompilationUnit)	{			
148
				IType type= ((ICompilationUnit) firstElement).findPrimaryType();
149
				if (type.isInterface()) {
150
					MessageDialog.openInformation(getShell(), fDialogTitle, ActionMessages.getString("CreateNewConstructorAction.interface_not_applicable")); //$NON-NLS-1$					
151
					return;
152
				}
153
				else 
154
					run((IType)EditorUtility.getWorkingCopy(((ICompilationUnit) firstElement).findPrimaryType()), new IField[0], editor, false);
155
			}
156
		} catch (CoreException e) {
157
			ExceptionHandler.handle(e, getShell(), fDialogTitle, ActionMessages.getString("CreateNewConstructorAction.error.actionfailed")); //$NON-NLS-1$
158
		}	
159
	}
160
161
	private IType getSelectedType(IStructuredSelection selection) throws JavaModelException {
162
		Object[] elements= selection.toArray();
163
		if (elements.length == 1 && (elements[0] instanceof IType)) {
164
			IType type= (IType) elements[0];
165
			if (type.getCompilationUnit() != null && type.isClass()) {
166
				return type;
167
			}
168
		}
169
		else if (elements[0] instanceof ICompilationUnit) {
170
			ICompilationUnit cu= (ICompilationUnit) elements[0];
171
			IType type= cu.findPrimaryType();
172
			if (!type.isInterface())
173
				return type;
174
		}
175
		return null;
176
	}
177
	
178
	private static boolean canRunOn(IField[] fields) throws JavaModelException {
179
		return fields != null && fields.length > 0;
180
	}
181
	
182
	/*
183
	 * Returns fields in the selection or <code>null</code> if the selection is 
184
	 * empty or not valid.
185
	 */
186
	private IField[] getSelectedFields(IStructuredSelection selection) {
187
		List elements= selection.toList();
188
		int nElements= elements.size();
189
		if (nElements > 0) {
190
			IField[] res= new IField[nElements];
191
			ICompilationUnit cu= null;
192
			for (int i= 0; i < nElements; i++) {
193
				Object curr= elements.get(i);
194
				if (curr instanceof IField) {
195
					IField fld= (IField)curr;
196
					
197
					if (i == 0) {
198
						// remember the cu of the first element
199
						cu= fld.getCompilationUnit();
200
						if (cu == null) {
201
							return null;
202
						}
203
					} else if (!cu.equals(fld.getCompilationUnit())) {
204
						// all fields must be in the same CU
205
						return null;
206
					}
207
					try {
208
						if (fld.getDeclaringType().isInterface()) {
209
							// no constructors for interfaces
210
							return null;
211
						}
212
					} catch (JavaModelException e) {
213
						JavaPlugin.log(e);
214
						return null;
215
					}
216
					
217
					res[i]= fld;
218
				} else {
219
					return null;
220
				}
221
			}
222
			return res;
223
		}
224
		return null;
225
	}	
226
227
	//---- Java Editior --------------------------------------------------------------
228
	
229
	/* (non-Javadoc)
230
	 * Method declared on SelectionDispatchAction
231
	 */
232
	public void selectionChanged(ITextSelection selection) {
233
	}
234
	
235
	/* (non-Javadoc)
236
	 * Method declared on SelectionDispatchAction
237
	 */
238
	public void run(ITextSelection selection) {		
239
240
		try {
241
			IJavaElement[] elements= SelectionConverter.codeResolve(fEditor);			
242
			if (elements.length == 1 && (elements[0] instanceof IField)) {
243
				IField field= (IField)elements[0];
244
				run(field.getDeclaringType(), new IField[] {field}, fEditor, false);
245
				return;
246
			}
247
			IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
248
			
249
			if (element != null){
250
				IType type= (IType)element.getAncestor(IJavaElement.TYPE);
251
				if (type != null) {
252
					if (type.getFields().length > 0) {
253
						run(type, new IField[0], fEditor, true);
254
						return;
255
					} 
256
				}
257
			} 
258
			MessageDialog.openInformation(getShell(), fDialogTitle, 
259
				ActionMessages.getString("CreateNewConstructorAction.not_applicable")); //$NON-NLS-1$
260
		} catch (CoreException e) {
261
			ExceptionHandler.handle(e, getShell(), getDialogTitle(), null);
262
		}		
263
	}
264
	
265
	private boolean checkEnabledEditor() {
266
		return fEditor != null && SelectionConverter.canOperateOn(fEditor);
267
	}	
268
	
269
	//---- Helpers -------------------------------------------------------------------
270
	
271
	private void run(IType type, IField[] preselected, IEditorPart editor, boolean activatedFromEditor) throws CoreException {
272
		if (!ElementValidator.check(type, getShell(), getDialogTitle(), activatedFromEditor)) {
273
			return;
274
		}
275
		if (!ActionUtil.isProcessable(getShell(), type)) {
276
			return;		
277
		}		
278
279
		IField[] constructorFields= type.getFields();
280
		ArrayList constructorFieldsList= new ArrayList();
281
		for (int i= 0; i < constructorFields.length; i++) {
282
			constructorFieldsList.add(constructorFields[i]);
283
		}
284
		if (constructorFieldsList.isEmpty()){
285
			MessageDialog.openInformation(getShell(), fDialogTitle, ActionMessages.getString("CreateNewConstructorAction.typeContainsNoFields.message")); //$NON-NLS-1$
286
			return;
287
		}
288
		
289
		JavaElementLabelProvider labelProvider= new JavaElementLabelProvider(JavaElementLabelProvider.SHOW_DEFAULT);
290
		CreateNewConstructorContentProvider contentProvider = new CreateNewConstructorContentProvider(constructorFieldsList);			
291
		CreateNewConstructorSelectionDialog dialog= new CreateNewConstructorSelectionDialog(getShell(), labelProvider, contentProvider, fEditor, type);
292
		dialog.setCommentString(ActionMessages.getString("SourceActionDialog.createConstructorComment")); //$NON-NLS-1$
293
		dialog.setTitle(getDialogTitle());
294
		dialog.setInitialSelections(preselected);
295
		dialog.setContainerMode(true);
296
		dialog.setSize(60, 18);			
297
		dialog.setInput(new Object());
298
		dialog.setMessage(ActionMessages.getString("CreateNewConstructorAction.dialog.label")); //$NON-NLS-1$
299
		dialog.setValidator(createValidator(constructorFields.length));
300
		
301
		IField[] selected= null;
302
		int dialogResult = dialog.open();
303
		if (dialogResult == Window.OK) {			
304
			Object[] checkedElements = dialog.getResult();
305
			if (checkedElements == null)
306
				return;
307
			ArrayList result= new ArrayList(checkedElements.length);
308
			for (int i= 0; i < checkedElements.length; i++) {
309
				Object curr= checkedElements[i];
310
				if (curr instanceof IField) {
311
					result.add(curr);
312
				}
313
			}
314
						
315
			selected= (IField[]) result.toArray(new IField[result.size()]);
316
			
317
			CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
318
			settings.createComments= dialog.getGenerateComment();
319
	
320
			IJavaElement elementPosition= dialog.getElementPosition();
321
			AddCustomConstructorOperation op= new AddCustomConstructorOperation(type, settings, selected, false, elementPosition);
322
			
323
			IRewriteTarget target= editor != null ? (IRewriteTarget) editor.getAdapter(IRewriteTarget.class) : null;
324
			if (target != null) {
325
				target.beginCompoundChange();		
326
			}
327
			try {
328
				IRunnableContext context= JavaPlugin.getActiveWorkbenchWindow();
329
				if (context == null) {
330
					context= new BusyIndicatorRunnableContext();
331
				}				
332
				context.run(false, true, new WorkbenchRunnableAdapter(op));
333
				IMethod res= op.getCreatedConstructor();
334
335
				if (res.getCompilationUnit().isWorkingCopy())  {
336
					synchronized(res.getCompilationUnit())  {
337
						res.getCompilationUnit().reconcile();
338
					}
339
				}
340
				EditorUtility.revealInEditor(editor, res);
341
342
			} catch (InvocationTargetException e) {
343
				ExceptionHandler.handle(e, getShell(), getDialogTitle(), null); 
344
			} catch (InterruptedException e) {
345
				// Do nothing. Operation has been canceled by user.
346
			} finally {
347
				if (target != null) {
348
					target.endCompoundChange();		
349
				}
350
			}		
351
		}
352
	}	
353
	
354
	private static ISelectionStatusValidator createValidator(int entries) {
355
		CreateNewConstructorValidator validator= new CreateNewConstructorValidator(entries);
356
		return validator;
357
	}
358
	
359
	private String getDialogTitle() {
360
		return fDialogTitle;
361
	}	
362
363
	private static class CreateNewConstructorContentProvider implements ITreeContentProvider {
364
		
365
		private List fFieldsList;
366
		private static final Object[] EMPTY= new Object[0];
367
		
368
		public CreateNewConstructorContentProvider(List fieldList) {
369
			fFieldsList= fieldList;
370
		}
371
		
372
		/*
373
		 * @see ITreeContentProvider#getChildren(Object)
374
		 */
375
		public Object[] getChildren(Object parentElement) {
376
			return EMPTY;
377
		}
378
379
		/*
380
		 * @see ITreeContentProvider#getParent(Object)
381
		 */
382
		public Object getParent(Object element) {
383
			return null;
384
		}
385
386
		/*
387
		 * @see ITreeContentProvider#hasChildren(Object)
388
		 */
389
		public boolean hasChildren(Object element) {
390
			return getChildren(element).length > 0;
391
		}
392
		
393
				
394
		/*
395
		 * @see IStructuredContentProvider#getElements(Object)
396
		 */
397
		public Object[] getElements(Object inputElement) {
398
			return fFieldsList.toArray();
399
		}
400
			
401
		/*
402
		 * @see IContentProvider#dispose()
403
		 */
404
		public void dispose() {
405
		}
406
407
		/*
408
		 * @see IContentProvider#inputChanged(Viewer, Object, Object)
409
		 */
410
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
411
		}
412
413
		private List moveUp(List elements, List move) {
414
			int nElements= elements.size();
415
			List res= new ArrayList(nElements);
416
			Object floating= null;
417
			for (int i= 0; i < nElements; i++) {
418
				Object curr= elements.get(i);
419
				if (move.contains(curr)) {
420
					res.add(curr);
421
				} else {
422
					if (floating != null) {
423
						res.add(floating);
424
					}
425
					floating= curr;
426
				}
427
			}
428
			if (floating != null) {
429
				res.add(floating);
430
			}
431
			return res;
432
		}
433
		
434
		private List reverse(List p) {
435
			List reverse= new ArrayList(p.size());
436
			for (int i= p.size() - 1; i >= 0; i--) {
437
				reverse.add(p.get(i));
438
			}
439
			return reverse;
440
		}
441
				
442
		public void setElements(List elements, CheckboxTreeViewer tree) {
443
			fFieldsList= new ArrayList(elements);
444
			if (tree != null)
445
				tree.refresh();
446
		}		
447
448
		public void up(List checkedElements, CheckboxTreeViewer tree) {
449
			if (checkedElements.size() > 0) {
450
				setElements(moveUp(fFieldsList, checkedElements), tree);
451
				tree.reveal(checkedElements.get(0));
452
			}			
453
		}		
454
455
		public void down(List checkedElements, CheckboxTreeViewer tree) {
456
			if (checkedElements.size() > 0) {
457
				setElements(reverse(moveUp(reverse(fFieldsList), checkedElements)), tree);
458
				tree.reveal(checkedElements.get(checkedElements.size() - 1));
459
			}
460
		}
461
	}
462
	
463
	private static class CreateNewConstructorValidator implements ISelectionStatusValidator {
464
		private static int fEntries;
465
			
466
		CreateNewConstructorValidator(int entries) {
467
			super();
468
			fEntries= entries;
469
		}
470
471
		public IStatus validate(Object[] selection) {
472
			int count= countSelectedFields(selection);
473
474
			String message= ActionMessages.getFormattedString("CreateNewConstructorAction.fields_selected", //$NON-NLS-1$
475
																new Object[] { String.valueOf(count), String.valueOf(fEntries)} ); 																	
476
			return new StatusInfo(IStatus.INFO, message);
477
		}
478
479
		private int countSelectedFields(Object[] selection){
480
			int count= 0;
481
			for (int i = 0; i < selection.length; i++) {
482
				if (selection[i] instanceof IField)
483
					count++;
484
			}
485
			return count;
486
		}		
487
	}	
488
	
489
	private static class CreateNewConstructorSelectionDialog extends SourceActionDialog {
490
		private CreateNewConstructorContentProvider fContentProvider;
491
		private static final int UP_BUTTON= IDialogConstants.CLIENT_ID + 1;
492
		private static final int DOWN_BUTTON= IDialogConstants.CLIENT_ID + 2;		
493
		
494
		public CreateNewConstructorSelectionDialog(Shell parent, ILabelProvider labelProvider, CreateNewConstructorContentProvider contentProvider, CompilationUnitEditor editor, IType type) {
495
			super(parent, labelProvider, contentProvider, editor, type);
496
			fContentProvider= contentProvider;
497
		}	
498
		
499
		protected Composite createSelectionButtons(Composite composite) {
500
			Composite buttonComposite= super.createSelectionButtons(composite);
501
502
			GridLayout layout = new GridLayout();
503
			buttonComposite.setLayout(layout);						
504
505
			createUpDownButtons(buttonComposite);
506
			
507
			layout.marginHeight= 0;
508
			layout.marginWidth= 0;						
509
			layout.numColumns= 1;
510
			
511
			return buttonComposite;
512
		}
513
		
514
		protected void createUpDownButtons(Composite buttonComposite) {
515
			createButton(buttonComposite, UP_BUTTON, ActionMessages.getString("CreateNewConstructorSelectionDialog.up_button"), false); //$NON-NLS-1$	
516
			createButton(buttonComposite, DOWN_BUTTON, ActionMessages.getString("CreateNewConstructorSelectionDialog.down_button"), false); //$NON-NLS-1$				
517
		}
518
		
519
		protected void buttonPressed(int buttonId) {
520
			super.buttonPressed(buttonId);
521
			switch(buttonId) {
522
				case UP_BUTTON: {
523
					fContentProvider.up(getElementList(), getTreeViewer());
524
					updateOKStatus();						
525
					break;
526
				}
527
				case DOWN_BUTTON: {
528
					fContentProvider.down(getElementList(), getTreeViewer());
529
					updateOKStatus();									
530
					break;
531
				}
532
			}
533
		}
534
		
535
		private List getElementList() {
536
			Object elements[]= getTreeViewer().getCheckedElements();
537
			ArrayList elementList= new ArrayList();
538
			for(int i = 0; i < elements.length; i++)
539
				elementList.add(elements[i]);			
540
			return elementList;
541
		}		
542
				
543
	}
544
	
545
}

Return to bug 39188