Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: d1527c546a9b6fdbdd5b02c61fa15d530e8272e6 (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
/*******************************************************************************
 *  Copyright (c) 2008, 2018 IBM Corporation and others.
 *  All rights reserved. This program and the accompanying materials
 *  are made available under the terms of the Eclipse Public License v1.0
 *  which accompanies this distribution, and is available at
 *  http://www.eclipse.org/legal/epl-v10.html
 * 
 *  Contributors:
 *      IBM Corporation - initial API and implementation
 *******************************************************************************/
package org.eclipse.equinox.internal.p2.ui.dialogs;

import java.util.*;
import org.eclipse.core.runtime.jobs.*;
import org.eclipse.equinox.internal.p2.ui.viewers.DeferredQueryContentProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.widgets.*;
import org.eclipse.ui.dialogs.FilteredTree;
import org.eclipse.ui.dialogs.PatternFilter;
import org.eclipse.ui.progress.WorkbenchJob;

/**
 * FilteredTree extension that creates a ContainerCheckedTreeViewer, manages the
 * check state across filtering (working around bugs in ContainerCheckedTreeViewer),
 * and preloads all metadata repositories before allowing filtering, in order to 
 * coordinate background fetch and filtering.  It also manages a cache of expanded
 * elements that can survive a change of input.
 * 
 * @since 3.4
 *
 */
public class DelayedFilterCheckboxTree extends FilteredTree {

	private static final long FILTER_DELAY = 800;

	public static final Object ALL_ITEMS_HACK = new Object();

	ToolBar toolBar;
	Display display;
	PatternFilter patternFilter;
	IPreFilterJobProvider jobProvider;
	DeferredQueryContentProvider contentProvider;
	String savedFilterText;
	Job preFilterJob;
	WorkbenchJob filterJob;
	boolean ignoreFiltering = true;
	Object viewerInput;
	HashSet<Object> checkState = new HashSet<>();
	Set<Object> expanded = new HashSet<>();
	ContainerCheckedTreeViewer checkboxViewer;

	public DelayedFilterCheckboxTree(Composite parent, int treeStyle, PatternFilter filter, IPreFilterJobProvider jobProvider) {
		super(parent, true);
		this.display = parent.getDisplay();
		this.patternFilter = filter;
		init(treeStyle, filter);
	}

	@Override
	protected TreeViewer doCreateTreeViewer(Composite composite, int style) {
		checkboxViewer = new ContainerCheckedTreeViewer(composite, style);
		checkboxViewer.addCheckStateListener(event -> {
			// We use an additive check state cache so we need to remove
			// previously checked items if the user unchecked them.
			if (!event.getChecked() && checkState != null) {
				if (event.getElement() == ALL_ITEMS_HACK) {
					clearCheckStateCache();
				} else {
					ArrayList<Object> toRemove = new ArrayList<>(1);
					// See bug 258117.  Ideally we would get check state changes 
					// for children when the parent state changed, but we aren't, so
					// we need to remove all children from the additive check state
					// cache.
					if (contentProvider.hasChildren(event.getElement())) {
						Set<Object> unchecked = new HashSet<>();
						Object[] children = contentProvider.getChildren(event.getElement());
						for (Object element1 : children) {
							unchecked.add(element1);
						}
						Iterator<Object> iter = checkState.iterator();
						while (iter.hasNext()) {
							Object current = iter.next();
							if (current != null && unchecked.contains(current)) {
								toRemove.add(current);
							}
						}
					} else {
						for (Object element2 : checkState) {
							if (checkboxViewer.getComparer().equals(element2, event.getElement())) {
								toRemove.add(element2);
								// Do not break out of the loop.  We may have duplicate equal
								// elements in the cache.  Since the cache is additive, we want
								// to be sure we've gotten everything.
							}
						}
					}
					checkState.removeAll(toRemove);
				}
			} else if (event.getChecked()) {
				rememberLeafCheckState();
			}
		});
		return checkboxViewer;
	}

	@Override
	protected Composite createFilterControls(Composite filterParent) {
		super.createFilterControls(filterParent);
		filterParent.addDisposeListener(e -> cancelPreFilterJob());
		return filterParent;
	}

	public void contentProviderSet(final DeferredQueryContentProvider deferredProvider) {
		this.contentProvider = deferredProvider;
		deferredProvider.addListener((v, oldInput, newInput) -> {
			if (newInput == null) {
				return;
			}
			// Store the input because it's not reset in the viewer until
			// after this listener is run.
			viewerInput = newInput;

			// If we were loading repos, we want to cancel because there may be more.
			cancelPreFilterJob();
			// Cancel any filtering
			cancelAndResetFilterJob();
			contentProvider.setSynchronous(false);
			// Remember any previous expansions
			rememberExpansions();
			// If there are remembered check states, try to restore them.
			// Must be done in an async because we are in the middle of a buggy
			// selection preserving viewer refresh.
			checkboxViewer.getTree().setRedraw(false);
			display.asyncExec(() -> {
				if (checkboxViewer.getTree().isDisposed()) {
					return;
				}
				rememberExpansions();
				restoreLeafCheckState();
				rememberExpansions();
				restoreExpansions();
				checkboxViewer.getTree().setRedraw(true);
			});
		});
	}

	public void clearCheckStateCache() {
		checkState = null;
	}

	/*
	 * Overridden to hook a listener on the job and set the deferred content provider
	 * to synchronous mode before a filter is done.
	 * @see org.eclipse.ui.dialogs.FilteredTree#doCreateRefreshJob()
	 */
	@Override
	protected WorkbenchJob doCreateRefreshJob() {
		filterJob = super.doCreateRefreshJob();

		filterJob.addJobChangeListener(new JobChangeAdapter() {
			@Override
			public void aboutToRun(final IJobChangeEvent event) {
				// If we know we've already filtered and loaded repos, nothing more to do
				if (!ignoreFiltering) {
					return;
				}
				final boolean[] shouldPreFilter = new boolean[1];
				shouldPreFilter[0] = false;
				display.syncExec(() -> {
					if (filterText != null && !filterText.isDisposed()) {
						String text = getFilterString();
						// If we are about to filter and there is
						// actually filtering to do, check for a prefilter
						// job and the content  provider to synchronous mode.
						// We want the prefilter job to complete before continuing with filtering.
						if (text == null || (initialText != null && initialText.equals(text))) {
							return;
						}
						if (!contentProvider.getSynchronous() && preFilterJob == null) {
							if (filterText != null && !filterText.isDisposed()) {
								shouldPreFilter[0] = true;
							}
						}
					}
				});
				if (shouldPreFilter[0]) {
					event.getJob().sleep();
					schedulePreFilterJob();
				} else if (ignoreFiltering) {
					event.getJob().sleep();
				} else {
					// shouldn't get here unless the prefilter job finished 
					// and ignoreFiltering became false since we entered this listener.
					rememberLeafCheckState();
				}
			}

			@Override
			public void running(IJobChangeEvent event) {
				display.syncExec(() -> rememberLeafCheckState());
			}

			@Override
			public void done(IJobChangeEvent event) {
				if (event.getResult().isOK()) {
					display.asyncExec(() -> {
						if (checkboxViewer.getTree().isDisposed()) {
							return;
						}

						checkboxViewer.getTree().setRedraw(false);
						// remember things expanded by the filter
						rememberExpansions();
						restoreLeafCheckState();
						// now restore expansions because we may have
						// had others
						restoreExpansions();
						checkboxViewer.getTree().setRedraw(true);
					});
				}
			}
		});
		return filterJob;
	}

	void schedulePreFilterJob() {
		// cancel any existing jobs
		cancelPreFilterJob();
		ignoreFiltering = false;
		preFilterJob = jobProvider == null ? null : jobProvider.getPreFilterJob();
		if (preFilterJob == null) {
			if (filterJob != null) {
				filterJob.wakeUp();
			}
			return;
		}
		ignoreFiltering = true;
		preFilterJob.addJobChangeListener(new JobChangeAdapter() {
			@Override
			public void done(IJobChangeEvent event) {
				ignoreFiltering = false;
				contentProvider.setSynchronous(true);
				if (filterJob != null) {
					filterJob.wakeUp();
				}
				preFilterJob = null;
			}
		});
		preFilterJob.setSystem(true);
		preFilterJob.setUser(false);
		preFilterJob.schedule();
	}

	void cancelPreFilterJob() {
		if (preFilterJob != null) {
			preFilterJob.cancel();
			preFilterJob = null;
		}
	}

	void cancelAndResetFilterJob() {
		if (filterJob != null) {
			filterJob.cancel();
		}
	}

	void rememberLeafCheckState() {
		ContainerCheckedTreeViewer v = (ContainerCheckedTreeViewer) getViewer();
		Object[] checked = v.getCheckedElements();
		if (checkState == null) {
			checkState = new HashSet<>(checked.length);
		}
		for (int i = 0; i < checked.length; i++) {
			if (!v.getGrayed(checked[i]) && contentProvider.getChildren(checked[i]).length == 0) {
				if (!checkState.contains(checked[i])) {
					checkState.add(checked[i]);
				}
			}
		}
	}

	void restoreLeafCheckState() {
		if (checkboxViewer == null || checkboxViewer.getTree().isDisposed()) {
			return;
		}
		if (checkState == null) {
			return;
		}

		checkboxViewer.setCheckedElements(new Object[0]);
		checkboxViewer.setGrayedElements(new Object[0]);
		// Now we are only going to set the check state of the leaf nodes
		// and rely on our container checked code to update the parents properly.
		Iterator<Object> iter = checkState.iterator();
		Object element = null;
		if (iter.hasNext()) {
			checkboxViewer.expandAll();
		}
		while (iter.hasNext()) {
			element = iter.next();
			checkboxViewer.setChecked(element, true);
		}
		// We are only firing one event, knowing that this is enough for our listeners.
		if (element != null) {
			checkboxViewer.fireCheckStateChanged(element, true);
		}
	}

	void rememberExpansions() {
		// The expansions are additive, but we are using a set to keep out
		// duplicates.  In practice, this means expanded items from different
		// inputs will remain expanded, such as categories with the same name
		// in different repos.
		expanded.addAll(Arrays.asList(getViewer().getExpandedElements()));
	}

	void restoreExpansions() {
		getViewer().setExpandedElements(expanded.toArray());
	}

	public ContainerCheckedTreeViewer getCheckboxTreeViewer() {
		return checkboxViewer;
	}

	@Override
	protected long getRefreshJobDelay() {
		return FILTER_DELAY;
	}

	public Object[] getCheckedElements() {
		if (this.checkState != null) {
			return this.checkState.toArray();
		}
		return new Object[0];
	}

	@Override
	protected String getFilterString() {
		return super.getFilterString();
	}
}

Back to the top