Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 13eb49e83c96ff92b31a72eaaa219e3a35151e9d (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
/*******************************************************************************
 * Copyright (c) 2006, 2012 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:
 *    Markus Schorn - initial API and implementation
 *******************************************************************************/

package org.eclipse.cdt.internal.ui.viewsupport;

import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import org.eclipse.cdt.internal.ui.CUIMessages;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWTException;
import org.eclipse.swt.widgets.Display;

/**
 * A TreeContentProvider that supports asyncronous computation of child nodes.
 * <p>
 * While a computation for children is in progress an object of type {@link AsyncTreeWorkInProgressNode}
 * is returned as a child. On completion of the computation the viewer will be refreshed with the actual
 * children.
 */
public abstract class AsyncTreeContentProvider implements ITreeContentProvider {
	private static final int PRIORITY_LOW = 0;
	private static final int PRIORITY_HIGH = 10;
	protected static final Object[] NO_CHILDREN = new Object[0];

	private Object fInput;
	private HashMap<Object, Object[]> fChildNodes = new HashMap<Object, Object[]>();
	private HashSet<Object> fHighPriorityTasks = new HashSet<Object>();
	private HashSet<Object> fLowPriorityTasks = new HashSet<Object>();
	private HashMap<Object, Object[]> fViewUpdates = new HashMap<Object, Object[]>();
	private int fViewUpdateDelta;
	private Job fJob;
	private Display fDisplay;
	private TreeViewer fTreeViewer = null;
	private Runnable fScheduledViewupdate = null;
	private HashSet<Object> fAutoexpand;
	private Object fAutoSelect;

	public AsyncTreeContentProvider(Display disp) {
		fDisplay = disp;
		fJob = new Job(CUIMessages.AsyncTreeContentProvider_JobName) {
			@Override
			protected IStatus run(final IProgressMonitor monitor) {
				return runJob(monitor);
			}
		};
		fJob.setSystem(true);
	}

	/**
	 * {@inheritDoc}
	 * <p>
	 * This implementation returns the parent for nodes indicating asyncronous computation.
	 * It returns <code>null</code> for all other elements. It should be overridden and
	 * called by derived classes.
	 */
	@Override
	public Object getParent(Object element) {
		if (element instanceof AsyncTreeWorkInProgressNode) {
			AsyncTreeWorkInProgressNode wipNode = (AsyncTreeWorkInProgressNode) element;
			return wipNode.getParent();
		}
		return null;
	}

	/**
	 * Returns the child elements of the given parent element, or <code>null</code>.
	 * <p>
	 * The method is called within the UI-thread and shall therefore return null in case
	 * the computation of the children may take longer.
	 * </p>
	 * The result is neither modified by the content provider nor the viewer.
	 *
	 * @param parentElement the parent element
	 * @return an array of child elements, or <code>null</code>
	 */
	protected Object[] syncronouslyComputeChildren(Object parentElement) {
		return null;
	}

	/**
	 * Returns the child elements of the given parent element.
	 * <p>
	 * The method is called outside the UI-thread. There is no need to report progress, the monitor
	 * is supplied such that implementations can check for cancel requests.
	 * </p>
	 * The result is neither modified by the content provider nor the viewer.
	 *
	 * @param parentElement the parent element
	 * @param monitor the monitor that can be checked for a cancel event.
	 * @return an array of child elements.
	 */
	protected Object[] asyncronouslyComputeChildren(Object parentElement, IProgressMonitor monitor) {
		return NO_CHILDREN;
	}

	/**
	 * Clears all caches and stops asyncronous computations. As a consequence
	 * child nodes requested by the viewer have to be computed from scratch.
	 * <p>
	 * Derived classes may override this method but must call <code>super.clearCaches()</code>.
	 */
	protected void clear() {
		fChildNodes.clear();
		synchronized (fHighPriorityTasks) {
			fScheduledViewupdate = null;
			fHighPriorityTasks.clear();
			fLowPriorityTasks.clear();
			fViewUpdates.clear();
		}
	}

	/**
	 * Recomputes all of the nodes, trying to keep the expanded state even with async
	 * computations.
	 */
	public void recompute() {
		if (getInput() != null) {
			fAutoexpand = new HashSet<Object>();
			fAutoexpand.addAll(Arrays.asList(fTreeViewer.getVisibleExpandedElements()));
			fAutoSelect = null;
			fAutoSelect = ((IStructuredSelection) fTreeViewer.getSelection()).getFirstElement();
			clear();
			refreshViewer();
		}
	}

	/**
	 * Refreshes the viewer
	 */
	private void refreshViewer() {
		if (fTreeViewer != null) {
			fTreeViewer.refresh();
		}
	}

	@Override
	final public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {
		if (newInput != oldInput) {
			clear();
			fInput = newInput;
		}
		if (viewer instanceof TreeViewer) {
			fTreeViewer = (TreeViewer) viewer;
		} else {
			fTreeViewer = null;
		}
	}

	final public Object getInput() {
		return fInput;
	}

	@Override
	final public Object[] getElements(Object inputElement) {
		return getChildren(inputElement);
	}

	@Override
	final public Object[] getChildren(Object parentElement) {
		Object[] children = internalGetChildren(parentElement);
		if (children == null) {
			scheduleQuery(parentElement, PRIORITY_HIGH);
			return new Object[] { new AsyncTreeWorkInProgressNode(parentElement) };
		}
		return children;
	}

	@Override
	final public boolean hasChildren(Object element) {
		assert Display.getCurrent() != null;

		Object[] children = internalGetChildren(element);
		if (children == null) {
			scheduleQuery(element, PRIORITY_LOW);
			return true;
		}
		return children.length > 0;
	}

	@Override
	public void dispose() {
		fTreeViewer = null;
		clear();
	}

	private void scheduleQuery(Object element, int priority) {
		synchronized (fHighPriorityTasks) {
			if (priority == PRIORITY_HIGH) {
				if (!fHighPriorityTasks.contains(element)) {
					fHighPriorityTasks.add(element);
					fLowPriorityTasks.remove(element);
				}
			} else {
				if (!fHighPriorityTasks.contains(element) && !fLowPriorityTasks.contains(element)) {
					fLowPriorityTasks.add(element);
				}
			}
			fJob.schedule();
		}
	}

	private IStatus runJob(final IProgressMonitor monitor) {
		monitor.beginTask(CUIMessages.AsyncTreeContentProvider_TaskName, IProgressMonitor.UNKNOWN);
		try {
			Object parent = getParentForNextTask();
			while (parent != null) {
				Object[] children = asyncronouslyComputeChildren(parent, monitor);
				synchronized (fHighPriorityTasks) {
					if (fHighPriorityTasks.remove(parent) || fLowPriorityTasks.remove(parent)) {
						fViewUpdates.put(parent, children);
						scheduleViewerUpdate();
					}
				}
				parent = getParentForNextTask();
			}
			return Status.OK_STATUS;
		} finally {
			monitor.done();
		}
	}

	private void scheduleViewerUpdate() {
		Runnable runme = null;
		synchronized (fHighPriorityTasks) {
			if (fScheduledViewupdate != null) {
				return;
			}
			runme = fScheduledViewupdate = new Runnable() {
				@Override
				public void run() {
					HashMap<Object, Object[]> updates = null;
					synchronized (fHighPriorityTasks) {
						if (fViewUpdates.isEmpty()) {
							fScheduledViewupdate = null;
							return;
						}
						if (fScheduledViewupdate != this) {
							return;
						}
						updates = fViewUpdates;
						fViewUpdates = new HashMap<Object, Object[]>();
					}
					fChildNodes.putAll(updates);
					if (fTreeViewer instanceof ExtendedTreeViewer) {
						((ExtendedTreeViewer) fTreeViewer).refresh(updates.keySet().toArray());
					} else if (fTreeViewer != null) {
						for (Iterator<Object> iter = updates.keySet().iterator(); iter.hasNext();) {
							fTreeViewer.refresh(iter.next());
						}
					}
					for (Iterator<Object[]> iter = updates.values().iterator(); iter.hasNext();) {
						checkForAutoExpand(iter.next());
					}
					fViewUpdateDelta = Math.min(1000, fViewUpdateDelta * 2);
					fDisplay.timerExec(fViewUpdateDelta, this);
				}
			};
		}
		try {
			fViewUpdateDelta = 32;
			fDisplay.asyncExec(runme);
		} catch (SWTException e) {
			// display may have been disposed.
		}
	}

	private void checkForAutoExpand(Object[] objects) {
		if (fTreeViewer == null) {
			return;
		}
		if (fAutoexpand != null && !fAutoexpand.isEmpty()) {
			for (int i = 0; i < objects.length; i++) {
				Object object = objects[i];
				if (fAutoexpand.remove(object)) {
					fTreeViewer.setExpandedState(object, true);
				}
				if (object.equals(fAutoSelect)) {
					if (fTreeViewer.getSelection().isEmpty()) {
						fTreeViewer.setSelection(new StructuredSelection(object));
					}
					fAutoSelect = null;
				}
			}
		}
		if (fAutoSelect != null) {
			if (fTreeViewer.getSelection().isEmpty()) {
				for (int i = 0; i < objects.length; i++) {
					Object object = objects[i];
					if (object.equals(fAutoSelect)) {
						fTreeViewer.setSelection(new StructuredSelection(object));
						fAutoSelect = null;
					}
				}
			} else {
				fAutoSelect = null;
			}
		}
	}

	private final Object getParentForNextTask() {
		synchronized (fHighPriorityTasks) {
			Object parent = null;
			if (!fHighPriorityTasks.isEmpty()) {
				parent = fHighPriorityTasks.iterator().next();
			} else if (!fLowPriorityTasks.isEmpty()) {
				parent = fLowPriorityTasks.iterator().next();
			}
			return parent;
		}
	}

	private Object[] internalGetChildren(Object parentElement) {
		assert Display.getCurrent() != null;

		if (parentElement instanceof AsyncTreeWorkInProgressNode) {
			return NO_CHILDREN;
		}
		Object[] children = fChildNodes.get(parentElement);
		if (children == null) {
			children = syncronouslyComputeChildren(parentElement);
			if (children != null) {
				final Object[] finalChildren = children;
				fChildNodes.put(parentElement, children);
				fDisplay.asyncExec(new Runnable() {
					@Override
					public void run() {
						checkForAutoExpand(finalChildren);
					}
				});
			}
		}
		return children;
	}

	final protected Display getDisplay() {
		return fDisplay;
	}
}

Back to the top