Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 30b06d89c0da83e202f79718c16d96954f7ea9b7 (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
/*******************************************************************************
 * Copyright (c) 2016 Red Hat 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:
 *     Mickael Istria (Red Hat Inc.) - [251156] async content assist
 *******************************************************************************/
package org.eclipse.jface.text.contentassist;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.stream.Collectors;

import org.eclipse.osgi.util.NLS;

import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Control;

import org.eclipse.core.runtime.SafeRunner;

import org.eclipse.jface.contentassist.IContentAssistSubjectControl;

import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.TextUtilities;

/**
 * This class is used to present proposals asynchronously to the user. If additional information
 * exists for a proposal, then selecting that proposal will result in the information being
 * displayed in a secondary window.
 *
 * @since 3.12
 */
class AsyncCompletionProposalPopup extends CompletionProposalPopup {

	private static final int MAX_WAIT_IN_MS= 50; // TODO make it a preference

	/**
	 * This is only used and set when populating the dialog is async (ie computation takes more than
	 * MAX_WAIT_IN_MS
	 */
	private CompletableFuture<?> fAggregatedPopulateFuture;

	private Collection<CompletableFuture<?>> toCancelFutures= new LinkedList<>();

	private static final class ComputingProposal implements ICompletionProposal, ICompletionProposalExtension {

		private final int fOffset;
		private final int fSize;
		private int fRemaining;

		ComputingProposal(int offset, int size) {
			fSize= size;
			fRemaining = size;
			fOffset = offset;
		}

		@Override
		public void apply(IDocument document) {
			// Nothing to do, maybe show some progress report?
		}

		@Override
		public Point getSelection(IDocument document) {
			return new Point(fOffset, 0);
		}

		@Override
		public IContextInformation getContextInformation() {
			return null;
		}

		@Override
		public Image getImage() {
			return null;
		}

		@Override
		public String getDisplayString() {
			return NLS.bind(JFaceTextMessages.getString("AsyncCompletionProposalPopup.computing"), Long.valueOf(Math.round(100. * (fSize - fRemaining)/fSize))); //$NON-NLS-1$
		}

		@Override
		public String getAdditionalProposalInfo() {
			 return NLS.bind(JFaceTextMessages.getString("AsyncCompletionProposalPopup.computingDetails"), new Object[] { //$NON-NLS-1$;
				Integer.valueOf(fSize),
				Integer.valueOf(fSize - fRemaining),
				Integer.valueOf(fRemaining) });
		}

		@Override
		public void apply(IDocument document, char trigger, int offset) {
			// Nothing to do
		}

		@Override
		public boolean isValidFor(IDocument document, int offset) {
			return false;
		}

		@Override
		public char[] getTriggerCharacters() {
			return null;
		}

		@Override
		public int getContextInformationPosition() {
			return -1;
		}

		void setRemaining(int size) {
			this.fRemaining = size;
		}
	}

	public AsyncCompletionProposalPopup(ContentAssistant contentAssistant, IContentAssistSubjectControl contentAssistSubjectControl, AdditionalInfoController infoController) {
		super(contentAssistant, contentAssistSubjectControl, infoController);
	}

	public AsyncCompletionProposalPopup(ContentAssistant contentAssistant, ITextViewer viewer, AdditionalInfoController infoController) {
		super(contentAssistant, viewer, infoController);
	}

	/**
	 * This methods differs from its super as it will show the list of proposals that
	 * gets augmented as the {@link IContentAssistProcessor#computeCompletionProposals(ITextViewer, int)}
	 * complete. All computations operation happen in a non-UI Thread so they're not blocking UI.
	 */
	@Override
	public String showProposals(boolean autoActivated) {
		if (fKeyListener == null)
			fKeyListener= new ProposalSelectionListener();

		final Control control= fContentAssistSubjectControlAdapter.getControl();

		if (!Helper.okToUse(fProposalShell) && control != null && !control.isDisposed()) {
			// add the listener before computing the proposals so we don't move the caret
			// when the user types fast.
			fContentAssistSubjectControlAdapter.addKeyListener(fKeyListener);

			fInvocationOffset= fContentAssistSubjectControlAdapter.getSelectedRange().x;
			fFilterOffset= fInvocationOffset;
			fLastCompletionOffset= fFilterOffset;
			// start invocation of processors as Futures, and make them populate the proposals upon completion
			computeAndPopulateProposals(fInvocationOffset, null, true, autoActivated, true);
		} else {
			fLastCompletionOffset= fFilterOffset;
			handleRepeatedInvocation();
		}

		return getErrorMessage();
	}

	@Override
	void handleRepeatedInvocation() {
		cancelFutures();
		computeAndPopulateProposals(fInvocationOffset, null, false, false, false);
	}

	private void computeAndPopulateProposals(int offset, Consumer<List<ICompletionProposal>> callback, boolean createSelector, boolean autoActivated, boolean autoInsert) {
		List<CompletableFuture<List<ICompletionProposal>>> computationFutures= buildCompletionFuturesOrJobs(offset);
		toCancelFutures.addAll(computationFutures);
		fComputedProposals= Collections.synchronizedList(new ArrayList<>());
		List<CompletableFuture<Void>> populateFutures= computationFutures.stream().map(future -> future.thenAccept(fComputedProposals::addAll)).collect(Collectors.toList());
		toCancelFutures.addAll(populateFutures);
		CompletableFuture<?> aggregatedPopulateFuture= CompletableFuture.allOf(populateFutures.toArray(new CompletableFuture[populateFutures.size()]));
		toCancelFutures.add(aggregatedPopulateFuture);

		boolean useAsyncMode= false;
		try {
			aggregatedPopulateFuture.get(MAX_WAIT_IN_MS, TimeUnit.MILLISECONDS);
		} catch (TimeoutException e) {
			useAsyncMode= true;
		} catch (ExecutionException | InterruptedException ex) {
			// nothing to do
		}
		if (!useAsyncMode) {
			int count= fComputedProposals.size();
			if (count == 0 && hideWhenNoProposals(autoActivated)) {
				return;
			}

			if (autoInsert && count == 1 && !autoActivated && canAutoInsert(fComputedProposals.get(0))) {
				insertProposal(fComputedProposals.get(0), (char) 0, 0, offset);
				hide();
			} else {
				if (createSelector) {
					createProposalSelector();
				}
				if (callback != null) {
					callback.accept(fComputedProposals);
				} else {
					setProposals(fComputedProposals, false);
					displayProposals();
				}
			}
		} else {
			if (createSelector) {
				createProposalSelector();
			}
			ComputingProposal computingProposal= new ComputingProposal(offset, populateFutures.size());
			fComputedProposals.add(0, computingProposal);
			setProposals(fComputedProposals, false);
			AtomicInteger remaining= new AtomicInteger(populateFutures.size());
			final List<ICompletionProposal> requestSpecificProposals= fComputedProposals; //fComputedProposals can be changed/reset later
			populateFutures= populateFutures.stream().map(future -> future.thenRun(() -> {
				computingProposal.setRemaining(remaining.decrementAndGet());
				if (remaining.get() == 0) {
					requestSpecificProposals.remove(computingProposal);
				}
				Control control= fContentAssistSubjectControlAdapter.getControl();
				if (!control.isDisposed() && offset == fInvocationOffset) {
					control.getDisplay().asyncExec(() -> {
						// Skip if offset has changed while runnable was scheduled
						// nor when completion "session" was modified or canceled.
						if (offset != fInvocationOffset || fComputedProposals != requestSpecificProposals) {
							return;
						}
						if (autoInsert
								&& !autoActivated
								&& !fComputedProposals.contains(computingProposal)
								&& fComputedProposals.size() == 1
								&& remaining.get() == 0
								&& canAutoInsert(fComputedProposals.get(0))) {
							if (Helper.okToUse(fProposalShell)) {
								insertProposal(fComputedProposals.get(0), (char) 0, 0, offset);
								hide();
							}
							return;
						}
						if (!fComputedProposals.contains(computingProposal) && callback != null) {
							callback.accept(fComputedProposals);
						} else {
							setProposals(fComputedProposals, false);
							displayProposals();
						}
					});
				}
			})).collect(Collectors.toList());
			toCancelFutures.addAll(populateFutures);
			fAggregatedPopulateFuture= CompletableFuture.allOf(populateFutures.toArray(new CompletableFuture[populateFutures.size()]));
			toCancelFutures.add(fAggregatedPopulateFuture);
		}
		displayProposals();
	}

	@Override
	public String incrementalComplete() {
		cancelFutures();
		if (Helper.okToUse(fProposalShell) && fFilteredProposals != null) {
			return super.incrementalComplete();
		}
		final Control control= fContentAssistSubjectControlAdapter.getControl();

		if (fKeyListener == null)
			fKeyListener= new ProposalSelectionListener();

		if (!Helper.okToUse(fProposalShell) && !control.isDisposed())
			fContentAssistSubjectControlAdapter.addKeyListener(fKeyListener);

		fInvocationOffset= fContentAssistSubjectControlAdapter.getSelectedRange().x;
		fFilterOffset= fInvocationOffset;
		fLastCompletionOffset= fFilterOffset;

		computeAndPopulateProposals(fInvocationOffset, (List<ICompletionProposal> proposals) -> {
			ensureDocumentListenerInstalled();
			fFilteredProposals= proposals;
			if (!proposals.isEmpty() && completeCommonPrefix()) {
				hide();
			} else {
				setProposals(proposals, false);
				displayProposals();
			}
		}, true, false, true);
		fFilteredProposals= new ArrayList<>(fComputedProposals != null ? fComputedProposals : Collections.emptyList());
		return getErrorMessage();
	}

	@Override
	List<ICompletionProposal> computeProposals(int offset) {
		if (fProposalShell != null) {
			fProposalShell.dispose();
		}
		showProposals(true);
		return fComputedProposals;
	}

	@Override
	void createProposalSelector() {
		super.createProposalSelector();
		fProposalShell.addDisposeListener(e -> cancelFutures());
	}

	void cancelFutures() {
		toCancelFutures.forEach(future -> future.cancel(true));
		toCancelFutures.clear();
	}

	@Override
	protected List<ICompletionProposal> computeFilteredProposals(int offset, DocumentEvent event) {
		if (fAggregatedPopulateFuture != null && !fAggregatedPopulateFuture.isDone()) {
			// user typed a char & computation still pending -> let all futures complete then invoke "filterProposals" upon completion
			fAggregatedPopulateFuture.thenRun(this::filterProposals);
			return fComputedProposals;
		}
		return super.computeFilteredProposals(offset, event);
	}

	@Override
	public void hide() {
		super.hide();
		cancelFutures();
	}

	protected List<CompletableFuture<List<ICompletionProposal>>> buildCompletionFuturesOrJobs(int invocationOffset) {
		Set<IContentAssistProcessor> processors = null;
		try {
			processors= fContentAssistant.getContentAssistProcessors(getTokenContentType(invocationOffset));
		} catch (BadLocationException e) {
			// ignore
		}
		if (processors == null) {
			return Collections.emptyList();
		}
		List<CompletableFuture<List<ICompletionProposal>>> futures = new ArrayList<>(processors.size());
		for (IContentAssistProcessor processor : processors) {
			futures.add(CompletableFuture.supplyAsync(() -> {
				AtomicReference<List<ICompletionProposal>> result= new AtomicReference<>();
				SafeRunner.run(() -> {
					ICompletionProposal[] proposals= processor.computeCompletionProposals(fViewer, invocationOffset);
					if (proposals == null) {
						result.set(Collections.emptyList());
					} else {
						result.set(Arrays.asList(proposals));
					}
				});
				List<ICompletionProposal> proposals= result.get();
				if (proposals == null) { // an error occurred during computeCompletionProposal,
					// possible improvement: give user feedback by returning an error "proposal" shown
					// in completion popup and providing details
					return Collections.emptyList();
				}
				return proposals;
			}));
		}
		return futures;
	}

	private String getTokenContentType(int invocationOffset) throws BadLocationException {
		if (fContentAssistSubjectControl != null) {
			IDocument document= fContentAssistSubjectControl.getDocument();
			if (document != null) {
				return TextUtilities.getContentType(document, fContentAssistant.getDocumentPartitioning(), invocationOffset, true);
			}
		} else {
			return TextUtilities.getContentType(fViewer.getDocument(), fContentAssistant.getDocumentPartitioning(), invocationOffset, true);
		}
		return IDocument.DEFAULT_CONTENT_TYPE;
	}

}

Back to the top