Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 3cc455f63ce8d1d116b0b9652fb1d909c85c55d1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/*******************************************************************************
 * Copyright (c) 2007, 2015 Wind River Systems, Inc. and others.
 *
 * This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License 2.0
 * which accompanies this distribution, and is available at
 * https://www.eclipse.org/legal/epl-2.0/
 *
 * SPDX-License-Identifier: EPL-2.0
 *
 * Contributors:
 *     Anton Leherbauer (Wind River Systems) - initial API and implementation
 *     Markus Schorn (Wind River Systems)
 *******************************************************************************/
package org.eclipse.cdt.internal.ui.browser.opentype;

import java.util.Arrays;
import java.util.HashSet;

import org.eclipse.cdt.core.CCorePlugin;
import org.eclipse.cdt.core.browser.ITypeInfo;
import org.eclipse.cdt.core.browser.IndexTypeInfo;
import org.eclipse.cdt.core.browser.QualifiedTypeName;
import org.eclipse.cdt.core.dom.ast.IBinding;
import org.eclipse.cdt.core.index.IIndex;
import org.eclipse.cdt.core.index.IIndexBinding;
import org.eclipse.cdt.core.index.IIndexMacro;
import org.eclipse.cdt.core.index.IIndexManager;
import org.eclipse.cdt.core.index.IndexFilter;
import org.eclipse.cdt.core.model.CoreModel;
import org.eclipse.cdt.core.model.ICElement;
import org.eclipse.cdt.internal.core.browser.IndexModelUtil;
import org.eclipse.cdt.internal.ui.ICHelpContextIds;
import org.eclipse.cdt.internal.ui.search.CSearchUtil;
import org.eclipse.cdt.ui.CUIPlugin;
import org.eclipse.cdt.ui.browser.typeinfo.TypeSelectionDialog;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.IJobChangeEvent;
import org.eclipse.core.runtime.jobs.ISchedulingRule;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.core.runtime.jobs.JobChangeAdapter;
import org.eclipse.jface.wizard.ProgressMonitorPart;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Listener;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.PlatformUI;

/**
 * A dialog to select an element from a filterable list of elements.
 *
 * @since 4.0
 * @noextend This class is not intended to be subclassed by clients.
 */
public class ElementSelectionDialog extends TypeSelectionDialog {
	/**
	 * Job to update the element list in the background.
	 */
	private class UpdateElementsJob extends Job {
		/**
		 * The last used prefix to query the index. <code>null</code> means
		 * the query result should be empty.
		 */
		private volatile char[] fCurrentPrefix;

		public UpdateElementsJob(String name) {
			super(name);
			setSystem(true);
			setUser(false);
			setPriority(Job.LONG);
		}

		public char[] getCurrentPrefix() {
			return fCurrentPrefix;
		}

		public void scheduleQuery(char[] prefix) {
			fCurrentPrefix = prefix;
			int delay = fCurrentPrefix == null ? 0 : (fCurrentPrefix.length < 5 ? 400 : 200);
			schedule(delay);
		}

		@Override
		public IStatus run(final IProgressMonitor monitor) {
			monitor.beginTask(OpenTypeMessages.ElementSelectionDialog_UpdateElementsJob_inProgress,
					IProgressMonitor.UNKNOWN);
			final ITypeInfo[] elements = getElementsByPrefix(fCurrentPrefix, monitor);
			if (elements != null && !monitor.isCanceled()) {
				final Shell shell = getShell();
				if (shell != null && !shell.isDisposed()) {
					Runnable update = () -> {
						if (!shell.isDisposed() && !monitor.isCanceled()) {
							setListElements(elements);
							updateOkState();
						}
					};
					shell.getDisplay().asyncExec(update);
					monitor.done();
					return Status.OK_STATUS;
				}
			}
			return Status.CANCEL_STATUS;
		}
	}

	/**
	 * A job listener for simple job status reporting.
	 */
	private final class UpdateJobListener extends JobChangeAdapter {
		boolean fDone;
		private IProgressMonitor fMonitor;

		private UpdateJobListener(IProgressMonitor monitor) {
			fMonitor = monitor;
		}

		@Override
		public void done(IJobChangeEvent event) {
			fDone = true;
			final Shell shell = getShell();
			if (shell != null && !shell.isDisposed()) {
				Runnable update = () -> {
					if (!shell.isDisposed() && fDone) {
						fMonitor.done();
					}
				};
				shell.getDisplay().asyncExec(update);
			}
		}

		@Override
		public void running(final IJobChangeEvent event) {
			fDone = false;
			final Shell shell = getShell();
			if (shell != null && !shell.isDisposed()) {
				Runnable update = () -> {
					if (!shell.isDisposed() && !fDone) {
						fMonitor.beginTask(OpenTypeMessages.ElementSelectionDialog_UpdateElementsJob_inProgress,
								IProgressMonitor.UNKNOWN);
					}
				};
				shell.getDisplay().asyncExec(update);
			}
		}
	}

	private static final ISchedulingRule SINGLE_INSTANCE_RULE = new ISchedulingRule() {
		@Override
		public boolean contains(ISchedulingRule rule) {
			return rule == this;
		}

		@Override
		public boolean isConflicting(ISchedulingRule rule) {
			return rule == this;
		}
	};

	private UpdateElementsJob fUpdateJob;
	private boolean fAllowEmptyPrefix = true;
	private boolean fAllowEmptyString = true;
	private ProgressMonitorPart fProgressMonitorPart;

	private String fHelpContextId;

	/**
	 * Constructs an instance of <code>ElementSelectionDialog</code>.
	 *
	 * @param parent  the parent shell.
	 */
	public ElementSelectionDialog(Shell parent) {
		super(parent);
		setHelpContextId(ICHelpContextIds.OPEN_ELEMENT_DIALOG);
		setMatchEmptyString(false);
		fUpdateJob = new UpdateElementsJob(OpenTypeMessages.ElementSelectionDialog_UpdateElementsJob_name);
		fUpdateJob.setRule(SINGLE_INSTANCE_RULE);
	}

	@Override
	public void create() {
		super.create();
		// trigger initial query
		scheduleUpdate(getFilter());
	}

	@Override
	public boolean close() {
		fUpdateJob.cancel();
		return super.close();
	}

	/**
	 * Configures the help context id for this dialog.
	 *
	 * @param helpContextId
	 */
	public void setHelpContextId(String helpContextId) {
		fHelpContextId = helpContextId;
		setHelpAvailable(fHelpContextId != null);
	}

	@Override
	public void setMatchEmptyString(boolean matchEmptyString) {
		super.setMatchEmptyString(matchEmptyString);
		fAllowEmptyString = matchEmptyString;
		if (matchEmptyString) {
			setAllowEmptyPrefix(true);
		}
	}

	/**
	 * Sets whether an empty prefix should be allowed for queries.
	 *
	 * @param allowEmptyPrefix
	 */
	public void setAllowEmptyPrefix(boolean allowEmptyPrefix) {
		fAllowEmptyPrefix = allowEmptyPrefix;
	}

	@Override
	protected boolean showLowLevelFilter() {
		// The low-level filter is useless for us.
		return false;
	}

	@Override
	public Control createDialogArea(Composite parent) {
		PlatformUI.getWorkbench().getHelpSystem().setHelp(parent, fHelpContextId);
		return super.createDialogArea(parent);
	}

	@Override
	protected Table createLowerList(Composite parent) {
		Table table = super.createLowerList(parent);
		createProgressMonitorPart(parent);
		return table;
	}

	/**
	 * Creates the control for progress reporting.
	 */
	private void createProgressMonitorPart(Composite parent) {
		fProgressMonitorPart = new ProgressMonitorPart(parent, new GridLayout(2, false));
		GridData gridData = new GridData(GridData.FILL_HORIZONTAL);
		gridData.horizontalIndent = 0;
		gridData.verticalAlignment = GridData.BEGINNING;
		fProgressMonitorPart.setLayoutData(gridData);

		Label separator = new Label(parent.getParent(), SWT.SEPARATOR | SWT.HORIZONTAL);
		separator.setLayoutData(new GridData(GridData.FILL_HORIZONTAL));

		fUpdateJob.addJobChangeListener(new UpdateJobListener(fProgressMonitorPart));
	}

	/**
	 * Queries the elements for the given prefix.
	 */
	protected ITypeInfo[] getElementsByPrefix(char[] prefix, IProgressMonitor monitor) {
		if (monitor.isCanceled()) {
			return null;
		}
		HashSet<IndexTypeInfo> types = new HashSet<>();
		if (prefix != null) {
			final IndexFilter filter = new IndexFilter() {
				@Override
				public boolean acceptBinding(IBinding binding) throws CoreException {
					if (isVisibleType(IndexModelUtil.getElementType(binding))) {
						return IndexFilter.ALL_DECLARED.acceptBinding(binding);
					}
					return false;
				}
			};
			try {
				IIndex index = CCorePlugin.getIndexManager().getIndex(CoreModel.getDefault().getCModel().getCProjects(),
						IIndexManager.ADD_EXTENSION_FRAGMENTS_NAVIGATION);
				index.acquireReadLock();
				try {
					IIndexBinding[] bindings = index.findBindingsForPrefix(prefix, false, filter, monitor);
					for (int i = 0; i < bindings.length; i++) {
						if (i % 0x1000 == 0 && monitor.isCanceled()) {
							return null;
						}
						final IndexTypeInfo typeinfo = IndexTypeInfo.create(index, bindings[i]);
						types.add(typeinfo);
					}

					if (isVisibleType(ICElement.C_MACRO)) {
						IIndexMacro[] macros = index.findMacrosForPrefix(prefix, IndexFilter.ALL_DECLARED, monitor);
						for (int i = 0; i < macros.length; i++) {
							if (i % 0x1000 == 0 && monitor.isCanceled()) {
								return null;
							}
							final IndexTypeInfo typeinfo = IndexTypeInfo.create(index, macros[i]);
							types.add(typeinfo);
						}
					}
				} finally {
					index.releaseReadLock();
				}
			} catch (CoreException | InterruptedException e) {
				CUIPlugin.log(e);
			}
		}
		return types.toArray(new ITypeInfo[types.size()]);
	}

	/**
	 * @deprecated Unsupported
	 */
	@Deprecated
	@Override
	public void setElements(Object[] elements) {
		throw new UnsupportedOperationException();
	}

	@Override
	protected void handleElementsChanged() {
		updateOkState();
	}

	@Override
	protected void handleEmptyList() {
		updateOkState();
	}

	@Override
	protected Text createFilterText(Composite parent) {
		final Text result = super.createFilterText(parent);
		Listener listener = e -> scheduleUpdate(result.getText());
		result.addListener(SWT.Modify, listener);
		return result;
	}

	protected void scheduleUpdate(String filterText) {
		filterText = CSearchUtil.adjustSearchStringForOperators(filterText);
		char[] newPrefix = toPrefix(filterText);
		final char[] currentPrefix = fUpdateJob.getCurrentPrefix();
		final boolean equivalentPrefix = isEquivalentPrefix(currentPrefix, newPrefix);
		boolean emptyQuery = newPrefix.length == 0 && !fAllowEmptyPrefix
				|| filterText.length() == 0 && !fAllowEmptyString;
		final int jobState = fUpdateJob.getState();
		boolean needQuery = !equivalentPrefix
				|| (currentPrefix.length < newPrefix.length && currentPrefix.length < 5 && jobState == Job.RUNNING);
		if (emptyQuery) {
			newPrefix = null;
			needQuery = needQuery || currentPrefix != null;
		}
		if (needQuery || jobState == Job.WAITING || jobState == Job.SLEEPING) {
			fUpdateJob.cancel();
			fUpdateJob.scheduleQuery(newPrefix);
		}
	}

	private char[] toPrefix(String userFilter) {
		QualifiedTypeName qualifiedName = new QualifiedTypeName(userFilter);
		if (qualifiedName.segmentCount() > 1) {
			userFilter = qualifiedName.lastSegment();
		}
		if (userFilter.endsWith("<")) { //$NON-NLS-1$
			userFilter = userFilter.substring(0, userFilter.length() - 1);
		}
		int asterisk = userFilter.indexOf("*"); //$NON-NLS-1$
		int questionMark = userFilter.indexOf("?"); //$NON-NLS-1$
		int prefixEnd = asterisk < 0 ? questionMark : questionMark < 0 ? asterisk : Math.min(asterisk, questionMark);
		return (prefixEnd == -1 ? userFilter : userFilter.substring(0, prefixEnd)).toCharArray();
	}

	private boolean isEquivalentPrefix(char[] currentPrefix, char[] newPrefix) {
		if (currentPrefix == null || currentPrefix.length > newPrefix.length) {
			return false;
		} else if (newPrefix.length == currentPrefix.length) {
			return Arrays.equals(currentPrefix, newPrefix);
		}
		return new String(currentPrefix).equals(new String(newPrefix, 0, currentPrefix.length));
	}
}

Back to the top