1 /*******************************************************************************
2  * Copyright (c) 2000, 2013 IBM Corporation and others.
3  *
4  * This program and the accompanying materials
5  * are made available under the terms of the Eclipse Public License 2.0
6  * which accompanies this distribution, and is available at
7  * https://www.eclipse.org/legal/epl-2.0/
8  *
9  * SPDX-License-Identifier: EPL-2.0
10  *
11  * Contributors:
12  *     IBM Corporation - initial API and implementation
13  *******************************************************************************/
14 package org.eclipse.jdt.internal.ui.dialogs;
15 
16 import java.lang.reflect.InvocationTargetException;
17 import java.util.ArrayList;
18 import java.util.List;
19 
20 import org.eclipse.swt.SWT;
21 import org.eclipse.swt.events.SelectionEvent;
22 import org.eclipse.swt.events.SelectionListener;
23 import org.eclipse.swt.layout.GridData;
24 import org.eclipse.swt.widgets.Composite;
25 import org.eclipse.swt.widgets.Control;
26 import org.eclipse.swt.widgets.Shell;
27 
28 import org.eclipse.core.runtime.IProgressMonitor;
29 import org.eclipse.core.runtime.IStatus;
30 import org.eclipse.core.runtime.Status;
31 import org.eclipse.core.runtime.SubProgressMonitor;
32 import org.eclipse.core.runtime.jobs.IJobManager;
33 import org.eclipse.core.runtime.jobs.Job;
34 
35 import org.eclipse.jface.dialogs.MessageDialog;
36 import org.eclipse.jface.operation.IRunnableContext;
37 import org.eclipse.jface.operation.IRunnableWithProgress;
38 import org.eclipse.jface.viewers.ISelection;
39 
40 import org.eclipse.jface.text.ITextSelection;
41 
42 import org.eclipse.ui.IWorkbenchWindow;
43 import org.eclipse.ui.PlatformUI;
44 import org.eclipse.ui.dialogs.ISelectionStatusValidator;
45 import org.eclipse.ui.dialogs.SelectionStatusDialog;
46 
47 import org.eclipse.jdt.core.IPackageFragmentRoot;
48 import org.eclipse.jdt.core.IType;
49 import org.eclipse.jdt.core.JavaConventions;
50 import org.eclipse.jdt.core.JavaCore;
51 import org.eclipse.jdt.core.JavaModelException;
52 import org.eclipse.jdt.core.search.IJavaSearchConstants;
53 import org.eclipse.jdt.core.search.IJavaSearchScope;
54 import org.eclipse.jdt.core.search.SearchEngine;
55 import org.eclipse.jdt.core.search.SearchPattern;
56 import org.eclipse.jdt.core.search.TypeNameMatch;
57 import org.eclipse.jdt.core.search.TypeNameRequestor;
58 
59 import org.eclipse.jdt.internal.corext.util.Messages;
60 import org.eclipse.jdt.internal.corext.util.OpenTypeHistory;
61 
62 import org.eclipse.jdt.ui.JavaElementLabels;
63 import org.eclipse.jdt.ui.JavaUI;
64 import org.eclipse.jdt.ui.dialogs.TypeSelectionExtension;
65 
66 import org.eclipse.jdt.internal.ui.IJavaHelpContextIds;
67 import org.eclipse.jdt.internal.ui.JavaPlugin;
68 import org.eclipse.jdt.internal.ui.JavaUIMessages;
69 import org.eclipse.jdt.internal.ui.util.ExceptionHandler;
70 
71 
72 /**
73  * DO NOT REMOVE, used in a product.
74  * @deprecated As of 3.5, replaced by {@link org.eclipse.ui.dialogs.FilteredItemsSelectionDialog}
75  */
76 @Deprecated
77 @SuppressWarnings("all")
78 public class TypeSelectionDialog2 extends SelectionStatusDialog {
79 
80 	private String fTitle;
81 
82 	private boolean fMultipleSelection;
83 	private IRunnableContext fRunnableContext;
84 	private IJavaSearchScope fScope;
85 	private int fElementKind;
86 
87 	private String fInitialFilter;
88 	private int fSelectionMode;
89 	private ISelectionStatusValidator fValidator;
90 	private TypeSelectionComponent fContent;
91 	private TypeSelectionExtension fExtension;
92 
93 	public static final int NONE= TypeSelectionComponent.NONE;
94 	public static final int CARET_BEGINNING= TypeSelectionComponent.CARET_BEGINNING;
95 	public static final int FULL_SELECTION= TypeSelectionComponent.FULL_SELECTION;
96 
97 	private static boolean fgFirstTime= true;
98 
99 	private class TitleLabel implements TypeSelectionComponent.ITitleLabel {
100 		@Override
setText(String text)101 		public void setText(String text) {
102 			if (text == null || text.length() == 0) {
103 				getShell().setText(fTitle);
104 			} else {
105 				getShell().setText(Messages.format(
106 					JavaUIMessages.TypeSelectionDialog2_title_format,
107 					new String[] { fTitle, text}));
108 			}
109 		}
110 	}
111 
TypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context, IJavaSearchScope scope, int elementKinds)112 	public TypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context,
113 			IJavaSearchScope scope, int elementKinds) {
114 		this(parent, multi, context, scope, elementKinds, null);
115 	}
116 
TypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context, IJavaSearchScope scope, int elementKinds, TypeSelectionExtension extension)117 	public TypeSelectionDialog2(Shell parent, boolean multi, IRunnableContext context,
118 			IJavaSearchScope scope, int elementKinds, TypeSelectionExtension extension) {
119 		super(parent);
120 		setShellStyle(getShellStyle() | SWT.RESIZE);
121 		fMultipleSelection= multi;
122 		fRunnableContext= context;
123 		fScope= scope;
124 		fElementKind= elementKinds;
125 		fSelectionMode= NONE;
126 		fExtension= extension;
127 		if (fExtension != null) {
128 			fValidator= fExtension.getSelectionValidator();
129 		}
130 	}
131 
setFilter(String filter)132 	public void setFilter(String filter) {
133 		setFilter(filter, FULL_SELECTION);
134 	}
135 
setFilter(String filter, int selectionMode)136 	public void setFilter(String filter, int selectionMode) {
137 		fInitialFilter= filter;
138 		fSelectionMode= selectionMode;
139 	}
140 
setValidator(ISelectionStatusValidator validator)141 	public void setValidator(ISelectionStatusValidator validator) {
142 		fValidator= validator;
143 	}
144 
getSelectedTypes()145 	protected TypeNameMatch[] getSelectedTypes() {
146 		if (fContent == null || fContent.isDisposed())
147 			return null;
148 		return fContent.getSelection();
149 	}
150 
151 	@Override
create()152 	public void create() {
153 		super.create();
154 		fContent.populate(fSelectionMode);
155 		getOkButton().setEnabled(fContent.getSelection().length > 0);
156 	}
157 
158 	@Override
configureShell(Shell shell)159 	protected void configureShell(Shell shell) {
160 		super.configureShell(shell);
161 		PlatformUI.getWorkbench().getHelpSystem().setHelp(shell, IJavaHelpContextIds.TYPE_SELECTION_DIALOG2);
162 	}
163 
164 	@Override
createDialogArea(Composite parent)165 	protected Control createDialogArea(Composite parent) {
166 		Composite area= (Composite)super.createDialogArea(parent);
167 		fContent= new TypeSelectionComponent(area, SWT.NONE, getMessage(),
168 			fMultipleSelection, fScope, fElementKind, fInitialFilter,
169 			new TitleLabel(), fExtension);
170 		GridData gd= new GridData(GridData.FILL_BOTH);
171 		fContent.setLayoutData(gd);
172 		fContent.addSelectionListener(new SelectionListener() {
173 			@Override
174 			public void widgetDefaultSelected(SelectionEvent e) {
175 				handleDefaultSelected(fContent.getSelection());
176 			}
177 			@Override
178 			public void widgetSelected(SelectionEvent e) {
179 				handleWidgetSelected(fContent.getSelection());
180 			}
181 		});
182 		return area;
183 	}
184 
handleDefaultSelected(TypeNameMatch[] selection)185 	protected void handleDefaultSelected(TypeNameMatch[] selection) {
186 		if (selection.length == 0)
187 			return;
188 		okPressed();
189 	}
190 
handleWidgetSelected(TypeNameMatch[] selection)191 	protected void handleWidgetSelected(TypeNameMatch[] selection) {
192 		IStatus status= null;
193 		if (selection.length == 0) {
194 	    	status= new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, "",null); //$NON-NLS-1$
195 	    } else {
196 		    if (fValidator != null) {
197 				List jElements= new ArrayList();
198 				for (TypeNameMatch typeInfo : selection) {
199 					IType type= typeInfo.getType();
200 					if (type != null) {
201 						jElements.add(type);
202 					} else {
203 						status= new Status(IStatus.ERROR, JavaPlugin.getPluginId(), IStatus.ERROR, Messages.format(JavaUIMessages.TypeSelectionDialog_error_type_doesnot_exist, typeInfo.getFullyQualifiedName()), null);
204 						break;
205 					}
206 				}
207 				if (status == null) {
208 					status= fValidator.validate(jElements.toArray());
209 				}
210 			} else {
211 				status= new Status(IStatus.OK, JavaPlugin.getPluginId(), IStatus.OK, "",null); //$NON-NLS-1$
212 			}
213 	    }
214     	updateStatus(status);
215 	}
216 
217 	@Override
open()218 	public int open() {
219 		try {
220 			ensureConsistency();
221 		} catch (InvocationTargetException e) {
222 			ExceptionHandler.handle(e, JavaUIMessages.TypeSelectionDialog_error3Title, JavaUIMessages.TypeSelectionDialog_error3Message);
223 			return CANCEL;
224 		} catch (InterruptedException e) {
225 			// cancelled by user
226 			return CANCEL;
227 		}
228 		if (fInitialFilter == null) {
229 			IWorkbenchWindow window= JavaPlugin.getActiveWorkbenchWindow();
230 			if (window != null) {
231 				ISelection selection= window.getSelectionService().getSelection();
232 				if (selection instanceof ITextSelection) {
233 					String text= ((ITextSelection)selection).getText();
234 					if (text != null) {
235 						text= text.trim();
236 						if (text.length() > 0 && JavaConventions.validateJavaTypeName(text, JavaCore.VERSION_1_3, JavaCore.VERSION_1_3, null).isOK()) {
237 							fInitialFilter= text;
238 							fSelectionMode= FULL_SELECTION;
239 						}
240 					}
241 				}
242 			}
243 		}
244 		return super.open();
245 	}
246 
247 	@Override
close()248 	public boolean close() {
249 		boolean result;
250 		try {
251 			if (getReturnCode() == OK) {
252 				OpenTypeHistory.getInstance().save();
253 			}
254 		} finally {
255 			result= super.close();
256 		}
257 		return result;
258 	}
259 
260 	@Override
setTitle(String title)261 	public void setTitle(String title) {
262 		super.setTitle(title);
263 		fTitle= title;
264 	}
265 
266 	@Override
computeResult()267 	protected void computeResult() {
268 		TypeNameMatch[] selected= fContent.getSelection();
269 		if (selected == null || selected.length == 0) {
270 			setResult(null);
271 			return;
272 		}
273 
274 		// If the scope is null then it got computed by the type selection component.
275 		if (fScope == null) {
276 			fScope= fContent.getScope();
277 		}
278 
279 		OpenTypeHistory history= OpenTypeHistory.getInstance();
280 		List result= new ArrayList(selected.length);
281 		for (TypeNameMatch typeInfo : selected) {
282 			IType type= typeInfo.getType();
283 			if (!type.exists()) {
284 				String title= JavaUIMessages.TypeSelectionDialog_errorTitle;
285 				IPackageFragmentRoot root= typeInfo.getPackageFragmentRoot();
286 				String containerName= JavaElementLabels.getElementLabel(root, JavaElementLabels.ROOT_QUALIFIED);
287 				String message= Messages.format(JavaUIMessages.TypeSelectionDialog_dialogMessage, new String[] { typeInfo.getFullyQualifiedName(), containerName });
288 				MessageDialog.openError(getShell(), title, message);
289 				history.remove(typeInfo);
290 				setResult(null);
291 			} else {
292 				history.accessed(typeInfo);
293 				result.add(type);
294 			}
295 		}
296 		setResult(result);
297 	}
298 
ensureConsistency()299 	private void ensureConsistency() throws InvocationTargetException, InterruptedException {
300 		// we only have to ensure history consistency here since the search engine
301 		// takes care of working copies.
302 		class ConsistencyRunnable implements IRunnableWithProgress {
303 			@Override
304 			public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
305 				if (fgFirstTime) {
306 					// Join the initialize after load job.
307 					IJobManager manager= Job.getJobManager();
308 					manager.join(JavaUI.ID_PLUGIN, monitor);
309 				}
310 				OpenTypeHistory history= OpenTypeHistory.getInstance();
311 				if (fgFirstTime || history.isEmpty()) {
312 					monitor.beginTask(JavaUIMessages.TypeSelectionDialog_progress_consistency, 100);
313 					if (history.needConsistencyCheck()) {
314 						refreshSearchIndices(new SubProgressMonitor(monitor, 90));
315 						history.checkConsistency(new SubProgressMonitor(monitor, 10));
316 					} else {
317 						refreshSearchIndices(monitor);
318 					}
319 					monitor.done();
320 					fgFirstTime= false;
321 				} else {
322 					history.checkConsistency(monitor);
323 				}
324 			}
325 			public boolean needsExecution() {
326 				OpenTypeHistory history= OpenTypeHistory.getInstance();
327 				return fgFirstTime || history.isEmpty() || history.needConsistencyCheck();
328 			}
329 			private void refreshSearchIndices(IProgressMonitor monitor) throws InvocationTargetException {
330 				try {
331 					new SearchEngine().searchAllTypeNames(
332 						null,
333 						0,
334 						// make sure we search a concrete name. This is faster according to Kent
335 						"_______________".toCharArray(), //$NON-NLS-1$
336 						SearchPattern.R_EXACT_MATCH | SearchPattern.R_CASE_SENSITIVE,
337 						IJavaSearchConstants.ENUM,
338 						SearchEngine.createWorkspaceScope(),
339 						new TypeNameRequestor() {},
340 						IJavaSearchConstants.WAIT_UNTIL_READY_TO_SEARCH,
341 						monitor);
342 				} catch (JavaModelException e) {
343 					throw new InvocationTargetException(e);
344 				}
345 			}
346 		}
347 		ConsistencyRunnable runnable= new ConsistencyRunnable();
348 		if (!runnable.needsExecution())
349 			return;
350 		IRunnableContext context= fRunnableContext != null
351 			? fRunnableContext
352 			: PlatformUI.getWorkbench().getProgressService();
353 		context.run(true, true, runnable);
354 	}
355 }
356