View | Details | Raw Unified | Return to bug 35870 | Differences between
and this patch

Collapse All | Expand All

(-)core extension/org/eclipse/jdt/internal/corext/codemanipulation/AddGetterSetterOperation.java (-14 / +107 lines)
Lines 18-24 Link Here
18
import org.eclipse.core.runtime.IProgressMonitor;
18
import org.eclipse.core.runtime.IProgressMonitor;
19
import org.eclipse.core.runtime.NullProgressMonitor;
19
import org.eclipse.core.runtime.NullProgressMonitor;
20
import org.eclipse.core.runtime.OperationCanceledException;
20
import org.eclipse.core.runtime.OperationCanceledException;
21
22
import org.eclipse.jdt.core.Flags;
21
import org.eclipse.jdt.core.Flags;
23
import org.eclipse.jdt.core.IField;
22
import org.eclipse.jdt.core.IField;
24
import org.eclipse.jdt.core.IJavaElement;
23
import org.eclipse.jdt.core.IJavaElement;
Lines 27-46 Link Here
27
import org.eclipse.jdt.core.IType;
26
import org.eclipse.jdt.core.IType;
28
import org.eclipse.jdt.core.NamingConventions;
27
import org.eclipse.jdt.core.NamingConventions;
29
import org.eclipse.jdt.core.Signature;
28
import org.eclipse.jdt.core.Signature;
30
31
import org.eclipse.jdt.ui.CodeGeneration;
32
33
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
29
import org.eclipse.jdt.internal.corext.util.JavaModelUtil;
30
import org.eclipse.jdt.internal.corext.util.JdtFlags;
31
import org.eclipse.jdt.ui.CodeGeneration;
34
32
35
/**
33
/**
36
 * For given fields, method stubs for getters and setters are created.
34
 * For given fields, method stubs for getters and setters are created.
37
 */
35
 */
38
public class AddGetterSetterOperation implements IWorkspaceRunnable {
36
public class AddGetterSetterOperation implements IWorkspaceRunnable {
39
	
37
	
38
	private IJavaElement fInsertPosition;
39
	private int fVisibility;
40
	private boolean fSort;
41
	private boolean fSynchronized;
42
	private boolean fNative;
43
	private boolean fFinal;
44
40
	private final String[] EMPTY= new String[0];
45
	private final String[] EMPTY= new String[0];
41
	
46
	
42
	private IField[] fGetterFields;
47
	private IField[] fGetterFields;
43
	private IField[] fSetterFields;
48
	private IField[] fSetterFields;
49
	private IField[] fGetterSetterFields;
44
	private List fCreatedAccessors;
50
	private List fCreatedAccessors;
45
	
51
	
46
	private IRequestQuery fSkipExistingQuery;
52
	private IRequestQuery fSkipExistingQuery;
Lines 59-76 Link Here
59
	 * @param skipExistingQuery Callback to ask if setter / getters that already exist can be skipped.
65
	 * @param skipExistingQuery Callback to ask if setter / getters that already exist can be skipped.
60
	 *        Argument of the query is the existing method. <code>null</code> is a valid input and stands for skip all.
66
	 *        Argument of the query is the existing method. <code>null</code> is a valid input and stands for skip all.
61
	 */
67
	 */
62
	public AddGetterSetterOperation(IField[] fields, CodeGenerationSettings settings, IRequestQuery skipFinalSettersQuery, IRequestQuery skipExistingQuery) {
68
	public AddGetterSetterOperation(IField[] fields, CodeGenerationSettings settings, IRequestQuery skipFinalSettersQuery, IRequestQuery skipExistingQuery, IJavaElement elementPosition) {
63
		this(fields, fields, settings, skipFinalSettersQuery, skipExistingQuery);
69
		this(fields, fields, fields, settings, skipFinalSettersQuery, skipExistingQuery, elementPosition);
64
	}
70
	}
65
	
71
	
66
	public AddGetterSetterOperation(IField[] getterFields, IField[] setterFields, CodeGenerationSettings settings, IRequestQuery skipFinalSettersQuery, IRequestQuery skipExistingQuery) {
72
	public AddGetterSetterOperation(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, CodeGenerationSettings settings, IRequestQuery skipFinalSettersQuery, IRequestQuery skipExistingQuery, IJavaElement elementPosition) {
67
		super();
73
		super();
68
		fGetterFields= getterFields;
74
		fGetterFields= getterFields;
69
		fSetterFields= setterFields;
75
		fSetterFields= setterFields;
76
		fGetterSetterFields= getterSetterFields;
70
		fSkipExistingQuery= skipExistingQuery;
77
		fSkipExistingQuery= skipExistingQuery;
71
		fSkipFinalSettersQuery= skipFinalSettersQuery;
78
		fSkipFinalSettersQuery= skipFinalSettersQuery;
72
		fSettings= settings;
79
		fSettings= settings;
73
		fCreatedAccessors= new ArrayList();
80
		fCreatedAccessors= new ArrayList();
81
		fInsertPosition= elementPosition;
74
	}
82
	}
75
	
83
	
76
	/**
84
	/**
Lines 88-93 Link Here
88
			fSkipAllFinalSetters= (fSkipFinalSettersQuery == null);
96
			fSkipAllFinalSetters= (fSkipFinalSettersQuery == null);
89
			fSkipAllExisting= (fSkipExistingQuery == null);
97
			fSkipAllExisting= (fSkipExistingQuery == null);
90
			
98
			
99
			// create pairs first: http://bugs.eclipse.org/bugs/show_bug.cgi?id=35870
100
			if (!fSort) {
101
				for (int i= 0; i < fGetterSetterFields.length; i++) {
102
					generateGetter(fGetterSetterFields[i]);
103
					generateSetter(fGetterSetterFields[i]);
104
					monitor.worked(1);
105
					if (monitor.isCanceled()){
106
						throw new OperationCanceledException();
107
					}	
108
				}	
109
			}
91
			for (int i= 0; i < fGetterFields.length; i++) {
110
			for (int i= 0; i < fGetterFields.length; i++) {
92
				generateGetter(fGetterFields[i]);
111
				generateGetter(fGetterFields[i]);
93
				monitor.worked(1);
112
				monitor.worked(1);
Lines 101-113 Link Here
101
				if (monitor.isCanceled()){
120
				if (monitor.isCanceled()){
102
					throw new OperationCanceledException();
121
					throw new OperationCanceledException();
103
				}	
122
				}	
104
			}
123
			}			
105
			
106
		} finally {
124
		} finally {
107
			monitor.done();
125
			monitor.done();
108
		}
126
		}
109
	}
127
	}
110
	
128
	
129
	private IField[] getValidElementForSort() {
130
		if (fGetterSetterFields.length > 0)
131
			return fGetterSetterFields;
132
		if (fGetterFields.length > 0)
133
			return fGetterFields;
134
		if (fSetterFields.length > 0)
135
			return fSetterFields;
136
		else
137
			return null;
138
		
139
	}
140
111
	private boolean querySkipFinalSetters(IField field) throws OperationCanceledException {
141
	private boolean querySkipFinalSetters(IField field) throws OperationCanceledException {
112
		if (!fSkipAllFinalSetters) {
142
		if (!fSkipAllFinalSetters) {
113
			switch (fSkipFinalSettersQuery.doQuery(field)) {
143
			switch (fSkipFinalSettersQuery.doQuery(field)) {
Lines 163-172 Link Here
163
					buf.append('\n');
193
					buf.append('\n');
164
				}					
194
				}					
165
			}
195
			}
166
			buf.append("public "); //$NON-NLS-1$
196
197
			buf.append(JdtFlags.getVisibilityString(fVisibility));
198
			buf.append(' ');			
167
			if (isStatic) {
199
			if (isStatic) {
168
				buf.append("static "); //$NON-NLS-1$
200
				buf.append("static "); //$NON-NLS-1$
169
			}
201
			}
202
			if (fSynchronized)
203
				buf.append("synchronized "); //$NON-NLS-1$
204
			if (fFinal)
205
				buf.append("final "); //$NON-NLS-1$
206
			if (fNative)
207
				buf.append("native "); //$NON-NLS-1$
208
				
170
			buf.append(typeName);
209
			buf.append(typeName);
171
			buf.append(' '); buf.append(getterName);
210
			buf.append(' '); buf.append(getterName);
172
			buf.append("() {\nreturn "); buf.append(fieldName); buf.append(";\n}\n"); //$NON-NLS-2$ //$NON-NLS-1$
211
			buf.append("() {\nreturn "); buf.append(fieldName); buf.append(";\n}\n"); //$NON-NLS-2$ //$NON-NLS-1$
Lines 175-187 Link Here
175
			if (existingGetter != null) {
214
			if (existingGetter != null) {
176
				sibling= StubUtility.findNextSibling(existingGetter);
215
				sibling= StubUtility.findNextSibling(existingGetter);
177
				existingGetter.delete(false, null);
216
				existingGetter.delete(false, null);
178
			}				
217
			}
179
			
218
			else
219
				sibling= getInsertPosition();
220
				
180
			String formattedContent= StubUtility.codeFormat(buf.toString(), indent, lineDelim) + lineDelim;
221
			String formattedContent= StubUtility.codeFormat(buf.toString(), indent, lineDelim) + lineDelim;
181
			fCreatedAccessors.add(parentType.createMethod(formattedContent, sibling, true, null));
222
			fCreatedAccessors.add(parentType.createMethod(formattedContent, sibling, true, null));
182
		}
223
		}
183
	}
224
	}
184
	
225
185
	private void generateSetter(IField field) throws CoreException, OperationCanceledException {
226
	private void generateSetter(IField field) throws CoreException, OperationCanceledException {
186
		String fieldName= field.getElementName();
227
		String fieldName= field.getElementName();
187
		IJavaProject project= field.getJavaProject();
228
		IJavaProject project= field.getJavaProject();
Lines 219-228 Link Here
219
					buf.append('\n');
260
					buf.append('\n');
220
				}
261
				}
221
			}
262
			}
222
			buf.append("public "); //$NON-NLS-1$
263
			buf.append(JdtFlags.getVisibilityString(fVisibility));
264
			buf.append(' ');	
223
			if (isStatic) {
265
			if (isStatic) {
224
				buf.append("static "); //$NON-NLS-1$
266
				buf.append("static "); //$NON-NLS-1$
225
			}
267
			}
268
			if (fSynchronized)
269
				buf.append("synchronized "); //$NON-NLS-1$
270
			if (fFinal)
271
				buf.append("final "); //$NON-NLS-1$				
272
			if (fNative)
273
				buf.append("native "); //$NON-NLS-1$
274
				
226
			buf.append("void "); buf.append(setterName); //$NON-NLS-1$
275
			buf.append("void "); buf.append(setterName); //$NON-NLS-1$
227
			buf.append('('); buf.append(typeName); buf.append(' '); 
276
			buf.append('('); buf.append(typeName); buf.append(' '); 
228
			buf.append(argname); buf.append(") {\n"); //$NON-NLS-1$
277
			buf.append(argname); buf.append(") {\n"); //$NON-NLS-1$
Lines 241-246 Link Here
241
				sibling= StubUtility.findNextSibling(existingSetter);
290
				sibling= StubUtility.findNextSibling(existingSetter);
242
				existingSetter.delete(false, null);
291
				existingSetter.delete(false, null);
243
			}
292
			}
293
			else
294
				sibling= getInsertPosition();			
244
			
295
			
245
			String formattedContent= StubUtility.codeFormat(buf.toString(), indent, lineDelim) + lineDelim;
296
			String formattedContent= StubUtility.codeFormat(buf.toString(), indent, lineDelim) + lineDelim;
246
			fCreatedAccessors.add(parentType.createMethod(formattedContent, sibling, true, null));
297
			fCreatedAccessors.add(parentType.createMethod(formattedContent, sibling, true, null));
Lines 253-256 Link Here
253
	public IMethod[] getCreatedAccessors() {
304
	public IMethod[] getCreatedAccessors() {
254
		return (IMethod[]) fCreatedAccessors.toArray(new IMethod[fCreatedAccessors.size()]);
305
		return (IMethod[]) fCreatedAccessors.toArray(new IMethod[fCreatedAccessors.size()]);
255
	}
306
	}
307
308
	/**
309
	 * @param fSort
310
	 */
311
	public void setSort(boolean sort) {
312
		fSort = sort;
313
	}
314
315
	/**
316
	 * @param fVisibility
317
	 */
318
	public void setVisibility(int visibility) {
319
		fVisibility = visibility;
320
	}
321
	
322
	/**
323
	 * @param syncSet
324
	 */
325
	public void setSynchronized(boolean syncSet) {
326
		fSynchronized = syncSet;
327
	}
328
	
329
	/**
330
	 * @param finalSet
331
	 */
332
	public void setFinal(boolean finalSet) {
333
		fFinal = finalSet;
334
	}			
335
	/**
336
	 * @return
337
	 */
338
	public IJavaElement getInsertPosition() {
339
		return fInsertPosition;
340
	}
341
342
	/**
343
	 * @param nativeSet
344
	 */
345
	public void setNative(boolean nativeSet) {
346
		fNative= nativeSet;
347
	}
348
256
}
349
}
(-)ui/org/eclipse/jdt/internal/ui/actions/ActionMessages.properties (-5 / +15 lines)
Lines 73-89 Link Here
73
OverrideMethodsAction.error.type_removed_in_editor=Input type has been removed in editor.
73
OverrideMethodsAction.error.type_removed_in_editor=Input type has been removed in editor.
74
OverrideMethodsAction.not_applicable=Operation not applicable to current text selection. Please position the cursor inside a type.
74
OverrideMethodsAction.not_applicable=Operation not applicable to current text selection. Please position the cursor inside a type.
75
75
76
AddGetterSetterAction.label=Gene&rate Getter and Setter...
76
AddGetterSetterAction.label=Gene&rate Getters and Setters...
77
AddGetterSetterAction.description=Generate Getter and Setter methods for type's fields
77
AddGetterSetterAction.description=Generate Getter and Setter methods for type's fields
78
AddGetterSetterAction.tooltip=Generate Getter and Setter methods for the Type's Fields
78
AddGetterSetterAction.tooltip=Generate Getter and Setter methods for the type's Fields
79
79
80
AddGetterSetterAction.error.title=Generate Getter and Setter
80
AddGetterSetterAction.error.title=Generate Getters and Setters
81
AddGetterSetterAction.error.actionfailed=Generating Getter and Setter Failed.
81
AddGetterSetterAction.error.actionfailed=Generating Getters and Setters Failed.
82
AddGetterSetterAction.error.fieldNotExisting=The field ''{0}'' has been removed in the editor.
82
AddGetterSetterAction.error.fieldNotExisting=The field ''{0}'' has been removed in the editor.
83
AddGetterSetterAction.not_applicable=Operation not applicable to current text selection. A field has to be selected or a type that declares fields.
83
AddGetterSetterAction.not_applicable=Operation not applicable to current text selection. A field has to be selected or a type that declares fields.
84
AddGetterSetterAction.read_only=The compilation unit in which the field ''{0}'' is declared is read only.
84
AddGetterSetterAction.read_only=The compilation unit in which the field ''{0}'' is declared is read only.
85
85
86
AddGetterSetterAction.QueryDialog.title=Generate Getter and Setter
86
AddGetterSetterAction.QueryDialog.title=Generate Getters and Setters
87
AddGetterSetterAction.SkipSetterForFinalDialog.message=Field ''{0}'' is final.\nOK to skip creation of the setter method?
87
AddGetterSetterAction.SkipSetterForFinalDialog.message=Field ''{0}'' is final.\nOK to skip creation of the setter method?
88
AddGetterSetterAction.SkipExistingDialog.message=Method ''{0}'' already exists.\nSkip creation?
88
AddGetterSetterAction.SkipExistingDialog.message=Method ''{0}'' already exists.\nSkip creation?
89
AddGetterSetterAction.SkipExistingDialog.skip.label=&Skip
89
AddGetterSetterAction.SkipExistingDialog.skip.label=&Skip
Lines 95-100 Link Here
95
AddGetterSetterAction.methods_selected={0} methods selected.
95
AddGetterSetterAction.methods_selected={0} methods selected.
96
AddGettSetterAction.typeContainsNoFields.message=The type contains no fields or all fields have getters/setters already.
96
AddGettSetterAction.typeContainsNoFields.message=The type contains no fields or all fields have getters/setters already.
97
97
98
GetterSetterTreeSelectionDialog.select_getters=Select &Getters
99
GetterSetterTreeSelectionDialog.select_setters=Select &Setters
100
GetterSetterTreeSelectionDialog.alpha_pair_sort=Fields in getter/setter pairs
101
GetterSetterTreeSelectionDialog.alpha_method_sort=Method names alphabetically
102
GetterSetterTreeSelectionDialog.modifier_label=&Modfiers:
103
GetterSetterTreeSelectionDialog.sort_label=S&ort by:
104
GetterSetterTreeSelectionDialog.enterAt_label=&Insert point:
105
GetterSetterTreeSelectionDialog.cursor_position=Current cursor position
106
GetterSetterTreeSelectionDialog.first_method=First method
98
107
99
AddUnimplementedConstructorsAction.label=Add &Constructors from Superclass
108
AddUnimplementedConstructorsAction.label=Add &Constructors from Superclass
100
AddUnimplementedConstructorsAction.description=Evaluate and add constructors from superclass
109
AddUnimplementedConstructorsAction.description=Evaluate and add constructors from superclass
Lines 230-235 Link Here
230
PullUpAction.problem.message=Operation not possible.
239
PullUpAction.problem.message=Operation not possible.
231
240
232
OverrideMethodQuery.groupMethodsByTypes=Group methods by &types
241
OverrideMethodQuery.groupMethodsByTypes=Group methods by &types
242
OverrideMethodQuery.createComment=Generate method &comment
233
OverrideMethodQuery.dialog.title=Override/Implement Methods
243
OverrideMethodQuery.dialog.title=Override/Implement Methods
234
OverrideMethodQuery.dialog.description=&Select methods to override or implement:
244
OverrideMethodQuery.dialog.description=&Select methods to override or implement:
235
OverrideMethodQuery.selectioninfo.one={0} method selected.
245
OverrideMethodQuery.selectioninfo.one={0} method selected.
(-)ui/org/eclipse/jdt/internal/ui/actions/SelectionConverter.java (-1 / +1 lines)
Lines 217-223 Link Here
217
			return EMPTY_RESULT;
217
			return EMPTY_RESULT;
218
	}
218
	}
219
	
219
	
220
	private static IJavaElement getElementAtOffset(IJavaElement input, ITextSelection selection) throws JavaModelException {
220
	public static IJavaElement getElementAtOffset(IJavaElement input, ITextSelection selection) throws JavaModelException {
221
		if (input instanceof ICompilationUnit) {
221
		if (input instanceof ICompilationUnit) {
222
			ICompilationUnit cunit= (ICompilationUnit)input;
222
			ICompilationUnit cunit= (ICompilationUnit)input;
223
			if (cunit.isWorkingCopy()) {
223
			if (cunit.isWorkingCopy()) {
(-)ui/org/eclipse/jdt/ui/actions/AddGetterSetterAction.java (-64 / +496 lines)
Lines 12-59 Link Here
12
12
13
import java.lang.reflect.InvocationTargetException;
13
import java.lang.reflect.InvocationTargetException;
14
import java.util.ArrayList;
14
import java.util.ArrayList;
15
import java.util.Arrays;
15
import java.util.Collection;
16
import java.util.Collection;
16
import java.util.HashMap;
17
import java.util.HashMap;
18
import java.util.HashSet;
17
import java.util.List;
19
import java.util.List;
18
import java.util.Map;
20
import java.util.Map;
21
import java.util.Set;
19
22
20
import org.eclipse.core.runtime.CoreException;
23
import org.eclipse.core.runtime.CoreException;
21
import org.eclipse.core.runtime.IStatus;
24
import org.eclipse.core.runtime.IStatus;
22
23
import org.eclipse.swt.graphics.Image;
24
import org.eclipse.swt.widgets.Shell;
25
26
import org.eclipse.jface.dialogs.IDialogConstants;
27
import org.eclipse.jface.dialogs.MessageDialog;
28
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
29
import org.eclipse.jface.resource.ImageDescriptor;
30
import org.eclipse.jface.text.IRewriteTarget;
31
import org.eclipse.jface.text.ITextSelection;
32
import org.eclipse.jface.viewers.ILabelProvider;
33
import org.eclipse.jface.viewers.IStructuredSelection;
34
import org.eclipse.jface.viewers.ITreeContentProvider;
35
import org.eclipse.jface.viewers.Viewer;
36
37
import org.eclipse.ui.IEditorPart;
38
import org.eclipse.ui.IWorkbenchSite;
39
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
40
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
41
import org.eclipse.ui.help.WorkbenchHelp;
42
43
import org.eclipse.jdt.core.Flags;
25
import org.eclipse.jdt.core.Flags;
44
import org.eclipse.jdt.core.ICompilationUnit;
26
import org.eclipse.jdt.core.ICompilationUnit;
45
import org.eclipse.jdt.core.IField;
27
import org.eclipse.jdt.core.IField;
46
import org.eclipse.jdt.core.IJavaElement;
28
import org.eclipse.jdt.core.IJavaElement;
47
import org.eclipse.jdt.core.IMember;
29
import org.eclipse.jdt.core.IMember;
48
import org.eclipse.jdt.core.IMethod;
30
import org.eclipse.jdt.core.IMethod;
31
import org.eclipse.jdt.core.ISourceRange;
49
import org.eclipse.jdt.core.IType;
32
import org.eclipse.jdt.core.IType;
50
import org.eclipse.jdt.core.JavaModelException;
33
import org.eclipse.jdt.core.JavaModelException;
51
import org.eclipse.jdt.core.Signature;
34
import org.eclipse.jdt.core.Signature;
52
35
import org.eclipse.jdt.core.dom.Modifier;
53
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
36
import org.eclipse.jdt.internal.corext.SourceRange;
54
import org.eclipse.jdt.ui.JavaElementLabelProvider;
55
import org.eclipse.jdt.ui.JavaElementSorter;
56
57
import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation;
37
import org.eclipse.jdt.internal.corext.codemanipulation.AddGetterSetterOperation;
58
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
38
import org.eclipse.jdt.internal.corext.codemanipulation.CodeGenerationSettings;
59
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
39
import org.eclipse.jdt.internal.corext.codemanipulation.GetterSetterUtil;
Lines 68-78 Link Here
68
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
48
import org.eclipse.jdt.internal.ui.dialogs.StatusInfo;
69
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
49
import org.eclipse.jdt.internal.ui.javaeditor.CompilationUnitEditor;
70
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
50
import org.eclipse.jdt.internal.ui.javaeditor.EditorUtility;
51
import org.eclipse.jdt.internal.ui.javaeditor.selectionactions.GoToNextPreviousMemberAction;
71
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
52
import org.eclipse.jdt.internal.ui.preferences.JavaPreferencesSettings;
53
import org.eclipse.jdt.internal.ui.refactoring.IVisibilityChangeListener;
54
import org.eclipse.jdt.internal.ui.refactoring.VisibilityControlUtil;
72
import org.eclipse.jdt.internal.ui.util.ElementValidator;
55
import org.eclipse.jdt.internal.ui.util.ElementValidator;
73
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
56
import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
74
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
57
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementImageProvider;
75
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
58
import org.eclipse.jdt.internal.ui.viewsupport.JavaElementLabels;
59
import org.eclipse.jdt.ui.JavaElementImageDescriptor;
60
import org.eclipse.jdt.ui.JavaElementLabelProvider;
61
import org.eclipse.jdt.ui.JavaElementSorter;
62
import org.eclipse.jface.dialogs.IDialogConstants;
63
import org.eclipse.jface.dialogs.MessageDialog;
64
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
65
import org.eclipse.jface.resource.ImageDescriptor;
66
import org.eclipse.jface.text.IRewriteTarget;
67
import org.eclipse.jface.text.ITextSelection;
68
import org.eclipse.jface.text.TextSelection;
69
import org.eclipse.jface.viewers.ILabelProvider;
70
import org.eclipse.jface.viewers.IStructuredSelection;
71
import org.eclipse.jface.viewers.ITreeContentProvider;
72
import org.eclipse.jface.viewers.Viewer;
73
import org.eclipse.swt.SWT;
74
import org.eclipse.swt.events.SelectionAdapter;
75
import org.eclipse.swt.events.SelectionEvent;
76
import org.eclipse.swt.events.SelectionListener;
77
import org.eclipse.swt.graphics.Image;
78
import org.eclipse.swt.layout.GridData;
79
import org.eclipse.swt.layout.GridLayout;
80
import org.eclipse.swt.widgets.Button;
81
import org.eclipse.swt.widgets.Combo;
82
import org.eclipse.swt.widgets.Composite;
83
import org.eclipse.swt.widgets.Label;
84
import org.eclipse.swt.widgets.Shell;
85
import org.eclipse.ui.IEditorPart;
86
import org.eclipse.ui.IWorkbenchSite;
87
import org.eclipse.ui.dialogs.CheckedTreeSelectionDialog;
88
import org.eclipse.ui.dialogs.ISelectionStatusValidator;
89
import org.eclipse.ui.help.WorkbenchHelp;
76
90
77
/**
91
/**
78
 * Creates getter and setter methods for a type's fields. Opens a dialog
92
 * Creates getter and setter methods for a type's fields. Opens a dialog
Lines 94-99 Link Here
94
 */
108
 */
95
public class AddGetterSetterAction extends SelectionDispatchAction {
109
public class AddGetterSetterAction extends SelectionDispatchAction {
96
	
110
	
111
	private int fVisibility;
112
	private boolean fSort;
113
	private boolean fSynchronized;
114
	private boolean fFinal;	
115
	private boolean fNative;
97
	private CompilationUnitEditor fEditor;
116
	private CompilationUnitEditor fEditor;
98
	private static final String dialogTitle= ActionMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$
117
	private static final String dialogTitle= ActionMessages.getString("AddGetterSetterAction.error.title"); //$NON-NLS-1$
99
118
Lines 120-125 Link Here
120
		this(editor.getEditorSite());
139
		this(editor.getEditorSite());
121
		fEditor= editor;
140
		fEditor= editor;
122
		setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null);
141
		setEnabled(SelectionConverter.getInputAsCompilationUnit(editor) != null);
142
		fEditor.getEditorSite();
123
	}
143
	}
124
	
144
	
125
	//---- Structured Viewer -----------------------------------------------------------
145
	//---- Structured Viewer -----------------------------------------------------------
Lines 149-154 Link Here
149
				return;
169
				return;
150
			}	
170
			}	
151
			Object firstElement= selection.getFirstElement();
171
			Object firstElement= selection.getFirstElement();
172
152
			if (firstElement instanceof IType)
173
			if (firstElement instanceof IType)
153
				run((IType)firstElement, new IField[0], false);
174
				run((IType)firstElement, new IField[0], false);
154
			else if (firstElement instanceof ICompilationUnit)	
175
			else if (firstElement instanceof ICompilationUnit)	
Lines 186-206 Link Here
186
		return fields != null && fields.length > 0;
207
		return fields != null && fields.length > 0;
187
	}
208
	}
188
	
209
	
189
	private void run(IType type, IField[] preselected, boolean editor) throws CoreException {
210
	private void run(IType type, IField[] preselected, boolean editor) throws CoreException {		
190
		if (!ElementValidator.check(type, getShell(), dialogTitle, editor))
211
		if (!ElementValidator.check(type, getShell(), dialogTitle, editor))
191
			return;
212
			return;
192
		if (!ActionUtil.isProcessable(getShell(), type))
213
		if (!ActionUtil.isProcessable(getShell(), type))
193
			return;			
214
			return;			
194
		
215
		
195
		CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
196
		ILabelProvider lp= new AddGetterSetterLabelProvider();
216
		ILabelProvider lp= new AddGetterSetterLabelProvider();
197
		Map entries= createGetterSetterMapping(type, settings);
217
		Map entries= createGetterSetterMapping(type);
198
		if (entries.isEmpty()){
218
		if (entries.isEmpty()){
199
			MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGettSetterAction.typeContainsNoFields.message")); //$NON-NLS-1$
219
			MessageDialog.openInformation(getShell(), dialogTitle, ActionMessages.getString("AddGettSetterAction.typeContainsNoFields.message")); //$NON-NLS-1$
200
			return;
220
			return;
201
		}	
221
		}	
202
		ITreeContentProvider cp= new AddGetterSetterContentProvider(entries);
222
		ITreeContentProvider cp= new AddGetterSetterContentProvider(entries);
203
		CheckedTreeSelectionDialog dialog= new CheckedTreeSelectionDialog(getShell(), lp, cp);
223
		GetterSetterTreeSelectionDialog dialog= new GetterSetterTreeSelectionDialog(getShell(), lp, cp, fEditor);
204
		dialog.setSorter(new JavaElementSorter());
224
		dialog.setSorter(new JavaElementSorter());
205
		dialog.setTitle(dialogTitle);
225
		dialog.setTitle(dialogTitle);
206
		String message= ActionMessages.getString("AddGetterSetterAction.dialog.title");//$NON-NLS-1$
226
		String message= ActionMessages.getString("AddGetterSetterAction.dialog.title");//$NON-NLS-1$
Lines 215-225 Link Here
215
		Object[] result= dialog.getResult();
235
		Object[] result= dialog.getResult();
216
		if (result == null)
236
		if (result == null)
217
			return;
237
			return;
218
		IField[] getterFields= getGetterFields(result);
238
		fSort= dialog.getSort();
219
		IField[] setterFields= getSetterFields(result);
239
		fVisibility= dialog.getVisibility();
220
		generate(getterFields, setterFields);
240
		fSynchronized= dialog.getSynchronized();
241
		fNative= dialog.getNative();
242
		fFinal= dialog.getFinal();
243
		IField[] getterFields, setterFields, getterSetterFields;
244
		if (fSort) {
245
			getterFields= getGetterFields(result);
246
			setterFields= getSetterFields(result);
247
			getterSetterFields= new IField[0];
248
		}
249
		else {
250
			getterFields= getGetterOnlyFields(result);
251
			setterFields= getSetterOnlyFields(result);
252
			getterSetterFields= getGetterSetterFields(result);			
253
		}
254
		IField[][] allFields= new IField[][] {preselected, getterFields, setterFields, getterSetterFields};
255
		
256
		IJavaElement elementPosition= calculateElementPosition(dialog.getInsertionIndex(), allFields);
257
		
258
		generate(getterFields, setterFields, getterSetterFields, elementPosition);
221
	}
259
	}
222
260
261
	private boolean isEditorAvailable() {
262
		return fEditor != null;
263
	}	
264
	
265
	private IMethod asFirstMethod(IField[][] allFields) {
266
		try {
267
			for (int i=0; i < allFields.length; i++) {
268
				if (allFields[i].length  > 0) {
269
					IMethod methods[]= allFields[i][0].getDeclaringType().getMethods();
270
					return methods[0];				
271
				}
272
			}
273
		} catch (JavaModelException e) {
274
		}
275
		return null;
276
	}
277
	
278
	private IMethod atMethodPosition(IField[][] allFields, int index) {
279
		try {
280
			for (int i=0; i < allFields.length; i++) {
281
				if (allFields[i].length  > 0) {
282
					IMethod methods[]= allFields[i][0].getDeclaringType().getMethods();
283
					return methods[index-1];				
284
				}
285
			}
286
		} catch (JavaModelException e) {
287
		}
288
		return null;
289
	}
290
	/*
291
	 * Determine where in the file to enter the newly created methods. Result depends
292
	 * on whether to enter at the current cursor position or to enter at a chosen
293
	 * method.
294
	 */
295
	private IJavaElement calculateElementPosition(int comboBoxIndex, IField[][] allFields) {		
296
		try {
297
			if (isEditorAvailable()) {
298
				if (comboBoxIndex == 0) {			// at cursor position
299
					return setElementPosition(SelectionConverter.getElementAtOffset(fEditor));		
300
				}
301
				else if (comboBoxIndex == 1)	 	// as first method
302
					return asFirstMethod(allFields);
303
				else								// method position
304
					return atMethodPosition(allFields, comboBoxIndex-1);
305
			}
306
			else {									// run from a view part
307
				if (comboBoxIndex == 0)				// as first method
308
					return asFirstMethod(allFields);
309
				else {								// method position
310
					return atMethodPosition(allFields, comboBoxIndex);			
311
				}
312
			}
313
		}
314
		catch (JavaModelException e) {
315
		}
316
		return null;
317
	}
318
	
223
	private static ISelectionStatusValidator createValidator() {
319
	private static ISelectionStatusValidator createValidator() {
224
		return new ISelectionStatusValidator(){
320
		return new ISelectionStatusValidator(){
225
			public IStatus validate(Object[] selection) {
321
			public IStatus validate(Object[] selection) {
Lines 245-294 Link Here
245
		};
341
		};
246
	}
342
	}
247
343
344
	//	returns a list of fields with setter entries checked
345
	private static IField[] getSetterFields(Object[] result){
346
		Collection list= new ArrayList(0);
347
		Object each= null;
348
		GetterSetterEntry entry= null;
349
		for (int i = 0; i < result.length; i++) {
350
			each= result[i];
351
			if ((each instanceof GetterSetterEntry)){ 
352
				entry= (GetterSetterEntry)each;
353
				if (! entry.isGetterEntry) {
354
					list.add(entry.field);
355
				}
356
			}
357
		}
358
		return (IField[]) list.toArray(new IField[list.size()]);			
359
	}
360
	
361
	//	returns a list of fields with getter entries checked
248
	private static IField[] getGetterFields(Object[] result){
362
	private static IField[] getGetterFields(Object[] result){
249
		Collection list= new ArrayList(0);
363
		Collection list= new ArrayList(0);
364
		Object each= null;
365
		GetterSetterEntry entry= null;
250
		for (int i = 0; i < result.length; i++) {
366
		for (int i = 0; i < result.length; i++) {
251
			Object each= result[i];
367
			each= result[i];
252
			if ((each instanceof GetterSetterEntry)){ 
368
			if ((each instanceof GetterSetterEntry)){ 
253
				GetterSetterEntry entry= (GetterSetterEntry)each;
369
				entry= (GetterSetterEntry)each;
254
				if (entry.isGetterEntry)
370
				if (entry.isGetterEntry) {
255
					list.add(entry.field);
371
					list.add(entry.field);
256
			}	
372
				}
373
			}
257
		}
374
		}
258
		return (IField[]) list.toArray(new IField[list.size()]);			
375
		return (IField[]) list.toArray(new IField[list.size()]);			
259
	}
376
	}
260
	
377
	
261
	private static IField[] getSetterFields(Object[] result){
378
	//	returns a list of fields with only getter entires checked
379
	private static IField[] getGetterOnlyFields(Object[] result){
262
		Collection list= new ArrayList(0);
380
		Collection list= new ArrayList(0);
381
		Object each= null;
382
		GetterSetterEntry entry= null;
383
		boolean getterSet= false;
263
		for (int i = 0; i < result.length; i++) {
384
		for (int i = 0; i < result.length; i++) {
264
			Object each= result[i];
385
			each= result[i];
265
			if ((each instanceof GetterSetterEntry)){ 
386
			if ((each instanceof GetterSetterEntry)){ 
266
				GetterSetterEntry entry= (GetterSetterEntry)each;
387
				entry= (GetterSetterEntry)each;
267
				if (! entry.isGetterEntry)
388
				if (entry.isGetterEntry) {
268
					list.add(entry.field);
389
					list.add(entry.field);
269
			}	
390
					getterSet= true;
391
				}
392
				if ((! entry.isGetterEntry) && (getterSet == true)) {
393
					list.remove(entry.field);
394
					getterSet= false;
395
				}
396
			}
397
			else
398
				getterSet= false;	
399
		}
400
		return (IField[]) list.toArray(new IField[list.size()]);			
401
	}
402
	
403
	//	returns a list of fields with only setter entries checked
404
	private static IField[] getSetterOnlyFields(Object[] result){
405
		Collection list= new ArrayList(0);
406
		Object each= null;	
407
		GetterSetterEntry entry= null;
408
		boolean getterSet= false;
409
		for (int i = 0; i < result.length; i++) {
410
			each= result[i];
411
			if ((each instanceof GetterSetterEntry)){ 
412
				entry= (GetterSetterEntry)each;
413
				if (entry.isGetterEntry) {
414
					getterSet= true;
415
				}
416
				if ((! entry.isGetterEntry) && (getterSet != true)) {
417
					list.add(entry.field);
418
					getterSet= false;
419
				}
420
			}
421
			else
422
				getterSet= false;	
423
		}
424
		return (IField[]) list.toArray(new IField[list.size()]);					
425
	}
426
	
427
	// returns a list of fields with both entries checked
428
	private static IField[] getGetterSetterFields(Object[] result){
429
		Collection list= new ArrayList(0);
430
		Object each= null;		
431
		GetterSetterEntry entry= null;
432
		boolean getterSet= false;
433
		for (int i = 0; i < result.length; i++) {
434
			each= result[i];
435
			if ((each instanceof GetterSetterEntry)){ 
436
				entry= (GetterSetterEntry)each;
437
				if (entry.isGetterEntry) {
438
					getterSet= true;
439
				}
440
				if ((! entry.isGetterEntry) && (getterSet == true)) {
441
					list.add(entry.field);
442
					getterSet= false;
443
				}
444
			}
445
			else
446
				getterSet= false;	
270
		}
447
		}
271
		return (IField[]) list.toArray(new IField[list.size()]);			
448
		return (IField[]) list.toArray(new IField[list.size()]);			
272
	}
449
	}
273
	
450
	
274
	private void generate(IField[] getterFields, IField[] setterFields) throws CoreException{
451
	private void generate(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IJavaElement elementPosition) throws CoreException{
275
		if (getterFields.length == 0 && setterFields.length == 0)
452
		if (getterFields.length == 0 && setterFields.length == 0 && getterSetterFields.length == 0)
276
			return;
453
			return;
277
		
454
		
278
		ICompilationUnit cu= null;
455
		ICompilationUnit cu= null;
279
		if (getterFields.length != 0)
456
		if (getterFields.length != 0)
280
			cu= getterFields[0].getCompilationUnit();
457
			cu= getterFields[0].getCompilationUnit();
281
		else
458
		else if (setterFields.length != 0)
282
			cu= setterFields[0].getCompilationUnit();
459
			cu= setterFields[0].getCompilationUnit();
460
		else
461
			cu= getterSetterFields[0].getCompilationUnit();
283
		//open the editor, forces the creation of a working copy
462
		//open the editor, forces the creation of a working copy
284
		IEditorPart editor= EditorUtility.openInEditor(cu);
463
		IEditorPart editor= EditorUtility.openInEditor(cu);
285
		
464
		
286
		IField[] workingCopyGetterFields= getWorkingCopyFields(getterFields);
465
		IField[] workingCopyGetterFields= getWorkingCopyFields(getterFields);
287
		IField[] workingCopySetterFields= getWorkingCopyFields(setterFields);
466
		IField[] workingCopySetterFields= getWorkingCopyFields(setterFields);
288
		if (workingCopyGetterFields != null && workingCopySetterFields != null)
467
		IField[] workingCopyGetterSetterFields= getWorkingCopyFields(getterSetterFields);
289
			run(workingCopyGetterFields, workingCopySetterFields, editor);
468
		IJavaElement workingCopyElementPosition= getWorkingCopy(elementPosition);
469
470
		if (workingCopyGetterFields != null && workingCopySetterFields != null && workingCopyGetterSetterFields != null)
471
			run(workingCopyGetterFields, workingCopySetterFields, workingCopyGetterSetterFields, editor, workingCopyElementPosition);			
290
	}
472
	}
291
	
473
	
474
	private static IJavaElement getWorkingCopy(IJavaElement elementPosition) {
475
		if(elementPosition instanceof IMember)
476
			return JavaModelUtil.toWorkingCopy((IMember)elementPosition);
477
		return elementPosition;
478
	}
479
292
	private IField[] getWorkingCopyFields(IField[] fields) throws CoreException{
480
	private IField[] getWorkingCopyFields(IField[] fields) throws CoreException{
293
		if (fields.length == 0)
481
		if (fields.length == 0)
294
			return new IField[0];
482
			return new IField[0];
Lines 342-347 Link Here
342
				return;
530
				return;
343
			}
531
			}
344
			IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
532
			IJavaElement element= SelectionConverter.getElementAtOffset(fEditor);
533
			
345
			if (element != null){
534
			if (element != null){
346
				IType type= (IType)element.getAncestor(IJavaElement.TYPE);
535
				IType type= (IType)element.getAncestor(IJavaElement.TYPE);
347
				if (type != null){
536
				if (type != null){
Lines 360-372 Link Here
360
		
549
		
361
	//---- Helpers -------------------------------------------------------------------
550
	//---- Helpers -------------------------------------------------------------------
362
	
551
	
363
	private void run(IField[] getterFields, IField[] setterFields, IEditorPart editor) {
552
	private void run(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IEditorPart editor, IJavaElement elementPosition) {
364
		IRewriteTarget target= (IRewriteTarget) editor.getAdapter(IRewriteTarget.class);
553
		IRewriteTarget target= (IRewriteTarget) editor.getAdapter(IRewriteTarget.class);
365
		if (target != null) {
554
		if (target != null) {
366
			target.beginCompoundChange();
555
			target.beginCompoundChange();
367
		}
556
		}
368
		try {
557
		try {
369
			AddGetterSetterOperation op= createAddGetterSetterOperation(getterFields, setterFields);
558
			AddGetterSetterOperation op= createAddGetterSetterOperation(getterFields, setterFields, getterSetterFields, elementPosition);
559
			// Set the status fields corresponding to the visibility and modifiers set
560
			op.setSort(fSort);
561
			op.setVisibility(fVisibility);
562
			op.setSynchronized(fSynchronized);
563
			op.setFinal(fFinal);
564
			op.setNative(fNative);
370
			new ProgressMonitorDialog(getShell()).run(false, true, new WorkbenchRunnableAdapter(op));
565
			new ProgressMonitorDialog(getShell()).run(false, true, new WorkbenchRunnableAdapter(op));
371
		
566
		
372
			IMethod[] createdMethods= op.getCreatedAccessors();
567
			IMethod[] createdMethods= op.getCreatedAccessors();
Lines 385-395 Link Here
385
		}
580
		}
386
	}
581
	}
387
582
388
	private AddGetterSetterOperation createAddGetterSetterOperation(IField[] getterFields, IField[] setterFields) {
583
	private AddGetterSetterOperation createAddGetterSetterOperation(IField[] getterFields, IField[] setterFields, IField[] getterSetterFields, IJavaElement elementPosition) {
389
		IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery();
584
		IRequestQuery skipSetterForFinalQuery= skipSetterForFinalQuery();
390
		IRequestQuery skipReplaceQuery= skipReplaceQuery();
585
		IRequestQuery skipReplaceQuery= skipReplaceQuery();
391
		CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
586
		CodeGenerationSettings settings= JavaPreferencesSettings.getCodeGenerationSettings();
392
		return new AddGetterSetterOperation(getterFields, setterFields, settings, skipSetterForFinalQuery, skipReplaceQuery);
587
		return new AddGetterSetterOperation(getterFields, setterFields, getterSetterFields, settings, skipSetterForFinalQuery, skipReplaceQuery, elementPosition);
393
	}
588
	}
394
	
589
	
395
	private IRequestQuery skipSetterForFinalQuery() {
590
	private IRequestQuery skipSetterForFinalQuery() {
Lines 488-502 Link Here
488
		return null;
683
		return null;
489
	}
684
	}
490
	
685
	
491
	private static class GetterSetterEntry {
492
		public final IField field;
493
		public final boolean isGetterEntry;
494
		GetterSetterEntry(IField field, boolean isGetterEntry){
495
			this.field= field;
496
			this.isGetterEntry= isGetterEntry;
497
		}
498
	}
499
	
500
	private static class AddGetterSetterLabelProvider extends JavaElementLabelProvider {
686
	private static class AddGetterSetterLabelProvider extends JavaElementLabelProvider {
501
		
687
		
502
		AddGetterSetterLabelProvider() {
688
		AddGetterSetterLabelProvider() {
Lines 545-551 Link Here
545
	/**
731
	/**
546
	 * @return map IField -> GetterSetterEntry[]
732
	 * @return map IField -> GetterSetterEntry[]
547
	 */
733
	 */
548
	private static Map createGetterSetterMapping(IType type, CodeGenerationSettings settings) throws JavaModelException{
734
	private static Map createGetterSetterMapping(IType type) throws JavaModelException{
549
		IField[] fields= type.getFields();
735
		IField[] fields= type.getFields();
550
		Map result= new HashMap();
736
		Map result= new HashMap();
551
		for (int i= 0; i < fields.length; i++) {
737
		for (int i= 0; i < fields.length; i++) {
Lines 563-570 Link Here
563
	}
749
	}
564
	
750
	
565
	private static class AddGetterSetterContentProvider implements ITreeContentProvider{
751
	private static class AddGetterSetterContentProvider implements ITreeContentProvider{
752
		private boolean fsortAlphabetically;
566
		private static final Object[] EMPTY= new Object[0];
753
		private static final Object[] EMPTY= new Object[0];
567
		private Map fGetterSetterEntries;
754
		private Map fGetterSetterEntries;//IField -> Object[] (with 0 to 2 elements of type GetterSetterEntry)
568
		public AddGetterSetterContentProvider(Map entries) throws JavaModelException {
755
		public AddGetterSetterContentProvider(Map entries) throws JavaModelException {
569
			fGetterSetterEntries= entries;
756
			fGetterSetterEntries= entries;
570
		}
757
		}
Lines 595-608 Link Here
595
		public boolean hasChildren(Object element) {
782
		public boolean hasChildren(Object element) {
596
			return getChildren(element).length > 0;
783
			return getChildren(element).length > 0;
597
		}
784
		}
598
785
		
786
		/* Enter the getter/setter methods alphabetically into file */
787
		public void enterAlphabetically(boolean alpha) {
788
			fsortAlphabetically= alpha;
789
		}
790
				
599
		/*
791
		/*
600
		 * @see IStructuredContentProvider#getElements(Object)
792
		 * @see IStructuredContentProvider#getElements(Object)
601
		 */
793
		 */
602
		public Object[] getElements(Object inputElement) {
794
		public Object[] getElements(Object inputElement) {
603
			return fGetterSetterEntries.keySet().toArray();
795
			return fGetterSetterEntries.keySet().toArray();
604
		}
796
		}
605
797
		
798
		
606
		/*
799
		/*
607
		 * @see IContentProvider#dispose()
800
		 * @see IContentProvider#dispose()
608
		 */
801
		 */
Lines 616-621 Link Here
616
		 */
809
		 */
617
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
810
		public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
618
		}
811
		}
812
	}
813
	
814
	private static class GetterSetterTreeSelectionDialog extends CheckedTreeSelectionDialog {
815
816
		private boolean fSort;
817
		private int fVisibility;
818
		private boolean fNative;
819
		private boolean fFinal;
820
		private boolean fSynchronized;
821
		private int fInsertionIndex;
822
		private CompilationUnitEditor fEditor;
823
		
824
		public GetterSetterTreeSelectionDialog(Shell parent, ILabelProvider labelProvider, ITreeContentProvider contentProvider, CompilationUnitEditor editor) {
825
			super(parent, labelProvider, contentProvider);
826
			fEditor= editor;
827
		}
828
829
		public int getInsertionIndex() {
830
			return fInsertionIndex;
831
		}
832
		
833
		public int getVisibility() {
834
			return fVisibility;
835
		}
836
837
		public boolean getSort() {
838
			return fSort;
839
		}
840
		
841
		public boolean getFinal() {
842
			return fFinal;
843
		}		
844
845
		public boolean getNative() {
846
			return fNative;
847
		}	
848
		
849
		public boolean getSynchronized() {
850
			return fSynchronized;
851
		}	
852
853
		private boolean isEditorAvailable() {
854
			return fEditor != null;
855
		}	
856
						
857
		/**
858
		 * Adds the Select Getters and Select Setters buttons.
859
		 * Adds modifiers radio buttons and alphabetical order radio buttons. 
860
		 * 
861
		 * @param composite the parent composite
862
		 */
863
		protected Composite createSelectionButtons(Composite composite) {
864
			Composite buttonComposite = super.createSelectionButtons(composite); 
865
					
866
			addGetSetSelectButtons(buttonComposite);
867
			addOrderEntryChoices(buttonComposite);	
868
			addVisibilityAndModifiersChoices(buttonComposite);
869
										
870
			((GridLayout) buttonComposite.getLayout()).numColumns= 4;
871
			return buttonComposite;
872
		}
873
		
874
		private Composite addGetSetSelectButtons(Composite buttonComposite) {
875
			// Add buttons for selecting getters or setters only: http://bugs.eclipse.org/bugs/show_bug.cgi?id=35870
876
			int id = IDialogConstants.CLIENT_ID + 1;
877
			Button gettersButton = createButton(buttonComposite, id++, ActionMessages.getString("GetterSetterTreeSelectionDialog.select_getters"), false); //$NON-NLS-1$	
878
879
			SelectionListener listener = new SelectionAdapter() {
880
				public void widgetSelected(SelectionEvent e) {
881
					getTreeViewer().setCheckedElements(getGetterSetterElements(true));
882
					updateOKStatus();
883
				}
884
			};
885
			gettersButton.addSelectionListener(listener);
886
		
887
			Button settersButton = createButton(buttonComposite, id++, ActionMessages.getString("GetterSetterTreeSelectionDialog.select_setters"), false); //$NON-NLS-1$	
888
889
			listener = new SelectionAdapter() {
890
				public void widgetSelected(SelectionEvent e) {					
891
					getTreeViewer().setCheckedElements(getGetterSetterElements(false));
892
					updateOKStatus();
893
				}
894
			};
895
			settersButton.addSelectionListener(listener);
896
			
897
			return buttonComposite;			
898
		}
899
		
900
		private Composite addVisibilityAndModifiersChoices(Composite buttonComposite) {
901
			// Add visibility and modifiers buttons: http://bugs.eclipse.org/bugs/show_bug.cgi?id=35870
902
			IVisibilityChangeListener visibilityChangeListener = new IVisibilityChangeListener(){
903
				public void visibilityChanged(int newVisibility) {
904
					fVisibility= newVisibility;
905
				}
906
				public void modifierChanged(int modifier, boolean isChecked) {	
907
					switch (modifier) {
908
						case Modifier.FINAL: fFinal= isChecked; return;
909
						case Modifier.SYNCHRONIZED: fSynchronized= isChecked; return;
910
						case Modifier.NATIVE: fNative= isChecked; return;
911
						default: return;
912
					}
913
				}
914
			};
915
			int correctVisibility= Modifier.PUBLIC;
916
			int[] availableVisibilities= new int[]{Modifier.PUBLIC, Modifier.PROTECTED, Modifier.PRIVATE, Modifier.NONE};
917
			int[] availableModifiers= new int[] {Modifier.FINAL, Modifier.SYNCHRONIZED, Modifier.NATIVE};
918
			
919
			Composite visibilityComposite= VisibilityControlUtil.createVisibilityControlAndModifiers(buttonComposite, visibilityChangeListener, availableVisibilities, correctVisibility, availableModifiers);
920
			((GridData)visibilityComposite.getLayoutData()).horizontalSpan = 4;		
921
			
922
			return visibilityComposite;				
923
		}
924
		
925
		private Composite addOrderEntryChoices(Composite buttonComposite) {
926
			// Add order entry choices: http://bugs.eclipse.org/bugs/show_bug.cgi?id=35870
927
			Label enterLabel= new Label(buttonComposite, SWT.NONE);
928
			enterLabel.setText(ActionMessages.getString("GetterSetterTreeSelectionDialog.enterAt_label")); //$NON-NLS-1$
929
			GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
930
			gd.horizontalSpan= 1;
931
			enterLabel.setLayoutData(gd);
932
933
			final Combo enterCombo= new Combo(buttonComposite, SWT.READ_ONLY);
934
			fillWithPossibleInsertPositions(enterCombo);
935
			//enterCombo.setText(enterCombo.getItem(0));
936
			gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
937
			gd.horizontalSpan= 3;
938
			enterCombo.setLayoutData(gd);
939
			enterCombo.addSelectionListener(new SelectionAdapter(){
940
				public void widgetSelected(SelectionEvent e) {
941
					fInsertionIndex= enterCombo.getSelectionIndex();
942
				}
943
			});
944
945
			Label label= new Label(buttonComposite, SWT.NONE);
946
			label.setText(ActionMessages.getString("GetterSetterTreeSelectionDialog.sort_label")); //$NON-NLS-1$
947
			gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
948
			gd.horizontalSpan= 1;
949
			label.setLayoutData(gd);
950
951
			final Combo combo= new Combo(buttonComposite, SWT.READ_ONLY);
952
			combo.setItems(new String[]{ActionMessages.getString("GetterSetterTreeSelectionDialog.alpha_pair_sort"), //$NON-NLS-1$
953
										ActionMessages.getString("GetterSetterTreeSelectionDialog.alpha_method_sort")});  //$NON-NLS-1$  
954
			final int methodIndex= 1;	// Hard-coded. Change this if the list gets more complicated.
955
			combo.setText(combo.getItem(0));
956
			gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
957
			gd.horizontalSpan= 3;
958
			combo.setLayoutData(gd);
959
			combo.addSelectionListener(new SelectionAdapter(){
960
				public void widgetSelected(SelectionEvent e) {
961
					fSort= (combo.getSelectionIndex() == methodIndex);
962
				}
963
			});	
964
965
			return buttonComposite;			
966
		}
619
		
967
		
968
		private void fillWithPossibleInsertPositions(Combo combo) {
969
			Object allFields[]= getContentProvider().getElements(null);
970
			IField field= (IField)allFields[0];
971
972
			if (isEditorAvailable())
973
				combo.add(ActionMessages.getString("GetterSetterTreeSelectionDialog.cursor_position")); //$NON-NLS-1$	
974
975
			combo.add(ActionMessages.getString("GetterSetterTreeSelectionDialog.first_method")); //$NON-NLS-1$
976
			try {
977
				IMethod[] methods= field.getDeclaringType().getMethods();
978
				for (int i= 0; i < methods.length; i++) {
979
					combo.add(JavaElementLabels.getElementLabel(methods[i], JavaElementLabels.M_PARAMETER_TYPES));
980
				}		
981
			} catch (JavaModelException e) {
982
			}
983
			combo.select(0);
984
		}		
985
986
		private Object[] getGetterSetterElements(boolean isGetter){
987
			Object[] allFields= getContentProvider().getElements(null);
988
			Set result= new HashSet();
989
			for (int i = 0; i < allFields.length; i++) {
990
				IField field= (IField)allFields[i];
991
				GetterSetterEntry[] entries= getEntries(field);
992
				for (int j = 0; j < entries.length; j++) {
993
					AddGetterSetterAction.GetterSetterEntry entry= entries[j];
994
					if (entry.isGetterEntry == isGetter)
995
						result.add(entry);
996
				}
997
			}
998
			return result.toArray();
999
		}
1000
1001
		private GetterSetterEntry[] getEntries(IField field) {
1002
			List result= Arrays.asList(getContentProvider().getChildren(field));
1003
			return (GetterSetterEntry[]) result.toArray(new GetterSetterEntry[result.size()]);
1004
		}
1005
1006
	}
1007
1008
	private static class GetterSetterEntry {
1009
		public final IField field;
1010
		public final boolean isGetterEntry;
1011
1012
		GetterSetterEntry(IField field, boolean isGetterEntry){
1013
			this.field= field;
1014
			this.isGetterEntry= isGetterEntry;
1015
		}
1016
	}
1017
1018
	/**
1019
	 * Sets the location where the new getter/setter methods will be entered. 
1020
	 */
1021
	private IJavaElement setElementPosition(IJavaElement element) {
1022
		try {
1023
			if (element == null) {
1024
				return null;
1025
			}
1026
			int type = element.getElementType();
1027
			if (type == IJavaElement.METHOD || type == IJavaElement.FIELD)
1028
				return element;
1029
			else {		
1030
				ITextSelection textSelect= (ITextSelection)fEditor.getSelectionProvider().getSelection();	
1031
				GoToNextPreviousMemberAction action= GoToNextPreviousMemberAction.newGoToNextMemberAction(fEditor);
1032
				ISourceRange sourceRange= action.getNewSelectionRange(createSourceRange(textSelect), null);
1033
				IJavaElement nextElement= SelectionConverter.getElementAtOffset(SelectionConverter.getInput(fEditor), createTextSelection(sourceRange));
1034
				type= nextElement.getElementType();
1035
				if (type == IJavaElement.METHOD || type == IJavaElement.FIELD)
1036
					return nextElement;
1037
				else		// end of file
1038
					return null;
1039
1040
			}
1041
		} catch (JavaModelException e) {
1042
		}
1043
		return null;
1044
	}
1045
	
1046
	private static ISourceRange createSourceRange(ITextSelection textSelection){
1047
		return new SourceRange(textSelection.getOffset(), textSelection.getLength());
1048
	}
1049
	
1050
	private static ITextSelection createTextSelection(ISourceRange sourceRange){
1051
		return new TextSelection(sourceRange.getOffset(), sourceRange.getLength());
620
	}
1052
	}
621
}
1053
}
(-)ui refactoring/org/eclipse/jdt/internal/ui/refactoring/IVisibilityChangeListener.java (+1 lines)
Lines 11-14 Link Here
11
package org.eclipse.jdt.internal.ui.refactoring;
11
package org.eclipse.jdt.internal.ui.refactoring;
12
public interface IVisibilityChangeListener{
12
public interface IVisibilityChangeListener{
13
	void visibilityChanged(int newVisibility);
13
	void visibilityChanged(int newVisibility);
14
	void modifierChanged(int modifier, boolean isChecked);
14
}
15
}
(-)ui refactoring/org/eclipse/jdt/internal/ui/refactoring/VisibilityControlUtil.java (-6 / +53 lines)
Lines 13-34 Link Here
13
import java.util.ArrayList;
13
import java.util.ArrayList;
14
import java.util.List;
14
import java.util.List;
15
15
16
import org.eclipse.jdt.core.dom.Modifier;
16
import org.eclipse.swt.SWT;
17
import org.eclipse.swt.SWT;
17
import org.eclipse.swt.events.SelectionAdapter;
18
import org.eclipse.swt.events.SelectionAdapter;
18
import org.eclipse.swt.events.SelectionEvent;
19
import org.eclipse.swt.events.SelectionEvent;
20
import org.eclipse.swt.events.SelectionListener;
19
import org.eclipse.swt.layout.GridData;
21
import org.eclipse.swt.layout.GridData;
20
import org.eclipse.swt.layout.GridLayout;
22
import org.eclipse.swt.layout.GridLayout;
21
import org.eclipse.swt.widgets.Button;
23
import org.eclipse.swt.widgets.Button;
22
import org.eclipse.swt.widgets.Composite;
24
import org.eclipse.swt.widgets.Composite;
23
import org.eclipse.swt.widgets.Group;
25
import org.eclipse.swt.widgets.Group;
24
26
25
import org.eclipse.jdt.core.dom.Modifier;
27
public class VisibilityControlUtil {
26
import org.eclipse.jdt.internal.ui.refactoring.RefactoringMessages;
27
28
class VisibilityControlUtil {
29
	private VisibilityControlUtil(){}
28
	private VisibilityControlUtil(){}
30
	
29
	
31
	public static Composite createVisibilityControl(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int currectVisibility) {
30
	public static Composite createVisibilityControl(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility) {
32
		List allowedVisibilities= convertToIntegerList(availableVisibilities);
31
		List allowedVisibilities= convertToIntegerList(availableVisibilities);
33
		if (allowedVisibilities.size() == 1)
32
		if (allowedVisibilities.size() == 1)
34
			return null;
33
			return null;
Lines 38-43 Link Here
38
		GridData gd= new GridData(GridData.FILL_HORIZONTAL);
37
		GridData gd= new GridData(GridData.FILL_HORIZONTAL);
39
		group.setLayoutData(gd);
38
		group.setLayoutData(gd);
40
		GridLayout layout= new GridLayout();
39
		GridLayout layout= new GridLayout();
40
		layout.makeColumnsEqualWidth= true;
41
		layout.numColumns= 4; layout.marginWidth= 0;
41
		layout.numColumns= 4; layout.marginWidth= 0;
42
		group.setLayout(layout);
42
		group.setLayout(layout);
43
		
43
		
Lines 52-58 Link Here
52
					new Integer(Modifier.PROTECTED),
52
					new Integer(Modifier.PROTECTED),
53
					new Integer(Modifier.NONE),
53
					new Integer(Modifier.NONE),
54
					new Integer(Modifier.PRIVATE)};
54
					new Integer(Modifier.PRIVATE)};
55
		Integer initialVisibility= new Integer(currectVisibility);
55
		Integer initialVisibility= new Integer(correctVisibility);
56
		for (int i= 0; i < labels.length; i++) {
56
		for (int i= 0; i < labels.length; i++) {
57
			Button radio= new Button(group, SWT.RADIO);
57
			Button radio= new Button(group, SWT.RADIO);
58
			Integer visibilityCode= data[i];
58
			Integer visibilityCode= data[i];
Lines 69-74 Link Here
69
		group.setLayoutData((new GridData(GridData.FILL_HORIZONTAL)));
69
		group.setLayoutData((new GridData(GridData.FILL_HORIZONTAL)));
70
		return group;
70
		return group;
71
	}
71
	}
72
73
	public static Composite createVisibilityControlAndModifiers(Composite parent, final IVisibilityChangeListener visibilityChangeListener, int[] availableVisibilities, int correctVisibility, int[] availableModifiers) {
74
		Composite visibilityComposite= createVisibilityControl(parent, visibilityChangeListener, availableVisibilities, correctVisibility);
75
76
		List allowedModifiers= convertToIntegerList(availableModifiers);
77
		if (allowedModifiers.size() == 1)
78
			return null;
79
			
80
		String[] labels= new String[] {
81
			RefactoringMessages.getString("VisibilityControlUtil.abstract"), //$NON-NLS-1$
82
			RefactoringMessages.getString("VisibilityControlUtil.static"), //$NON-NLS-1$
83
			RefactoringMessages.getString("VisibilityControlUtil.final"), //$NON-NLS-1$
84
			RefactoringMessages.getString("VisibilityControlUtil.synchronized"), //$NON-NLS-1$
85
			RefactoringMessages.getString("VisibilityControlUtil.native"), //$NON-NLS-1$
86
		};		
87
		Integer[] data= new Integer[] {
88
					new Integer(Modifier.ABSTRACT),
89
					new Integer(Modifier.STATIC),
90
					new Integer(Modifier.FINAL),
91
					new Integer(Modifier.SYNCHRONIZED),
92
					new Integer(Modifier.NATIVE)};
93
		
94
		for (int i=0; i < labels.length; i++) {
95
			if (allowedModifiers.contains(data[i])) {
96
				Button checkboxButton= new Button(visibilityComposite, SWT.CHECK);
97
				checkboxButton.setText(labels[i]);
98
				GridData gd= new GridData(GridData.HORIZONTAL_ALIGN_FILL);
99
				checkboxButton.setLayoutData(gd);
100
				checkboxButton.setData(data[i]);
101
				checkboxButton.setEnabled(true);
102
				checkboxButton.setSelection(false);
103
				checkboxButton.addSelectionListener(new SelectionListener() {
104
					private Object modifiers;
105
	
106
					public void widgetSelected(SelectionEvent event) {
107
						visibilityChangeListener.modifierChanged(((Integer)event.widget.getData()).intValue(), ((Button) event.widget).getSelection());
108
					}
109
		
110
					public void widgetDefaultSelected(SelectionEvent event) {
111
						widgetSelected(event);
112
					}
113
				});				
114
			}
115
		}				
116
		return visibilityComposite;			
117
	}
118
72
	private static List convertToIntegerList(int[] array) {
119
	private static List convertToIntegerList(int[] array) {
73
		List result= new ArrayList(array.length);
120
		List result= new ArrayList(array.length);
74
		for (int i= 0; i < array.length; i++) {
121
		for (int i= 0; i < array.length; i++) {
(-)ui refactoring/org/eclipse/jdt/internal/ui/refactoring/refactoringui.properties (+5 lines)
Lines 386-391 Link Here
386
386
387
VisibilityControlUtil.Access_modifier=Access modifier
387
VisibilityControlUtil.Access_modifier=Access modifier
388
VisibilityControlUtil.defa&ult_4=de&fault
388
VisibilityControlUtil.defa&ult_4=de&fault
389
VisibilityControlUtil.abstract=&abstract
390
VisibilityControlUtil.final=f&inal
391
VisibilityControlUtil.static=stati&c
392
VisibilityControlUtil.synchronized=s&ynchronized
393
VisibilityControlUtil.native=&native
389
394
390
PullUpInputPage1.pull_up=pull up
395
PullUpInputPage1.pull_up=pull up
391
PullUpInputPage1.declare_abstract=declare abstract in destination
396
PullUpInputPage1.declare_abstract=declare abstract in destination

Return to bug 35870