Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: f3273f0865c0ed3df04328251f87e65eb4fef6d8 (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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
/*******************************************************************************
 * Copyright (c) 2011, 2013 Wind River Systems, Inc. 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:
 * Wind River Systems - initial API and implementation
 *******************************************************************************/
package org.eclipse.tcf.te.tcf.ui.navigator;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

import org.eclipse.core.runtime.Assert;
import org.eclipse.core.runtime.Platform;
import org.eclipse.jface.dialogs.IDialogSettings;
import org.eclipse.jface.viewers.ITreePathContentProvider;
import org.eclipse.jface.viewers.TreePath;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.tcf.protocol.IPeer;
import org.eclipse.tcf.protocol.Protocol;
import org.eclipse.tcf.te.runtime.concurrent.util.ExecutorsUtil;
import org.eclipse.tcf.te.tcf.locator.interfaces.IModelListener;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.ILocatorModel;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerModel;
import org.eclipse.tcf.te.tcf.locator.interfaces.nodes.IPeerRedirector;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.ILocatorModelLookupService;
import org.eclipse.tcf.te.tcf.locator.interfaces.services.ILocatorModelRefreshService;
import org.eclipse.tcf.te.tcf.locator.model.Model;
import org.eclipse.tcf.te.tcf.ui.activator.UIPlugin;
import org.eclipse.tcf.te.tcf.ui.internal.preferences.IPreferenceKeys;
import org.eclipse.tcf.te.tcf.ui.navigator.nodes.PeerRedirectorGroupNode;
import org.eclipse.tcf.te.ui.swt.DisplayUtil;
import org.eclipse.tcf.te.ui.views.Managers;
import org.eclipse.tcf.te.ui.views.extensions.CategoriesExtensionPointManager;
import org.eclipse.tcf.te.ui.views.interfaces.ICategory;
import org.eclipse.tcf.te.ui.views.interfaces.IRoot;
import org.eclipse.tcf.te.ui.views.interfaces.IUIConstants;
import org.eclipse.tcf.te.ui.views.interfaces.categories.ICategorizable;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.internal.navigator.NavigatorFilterService;
import org.eclipse.ui.navigator.CommonViewer;
import org.eclipse.ui.navigator.ICommonContentExtensionSite;
import org.eclipse.ui.navigator.ICommonContentProvider;
import org.eclipse.ui.navigator.ICommonFilterDescriptor;
import org.eclipse.ui.navigator.INavigatorContentService;
import org.eclipse.ui.navigator.INavigatorFilterService;


/**
 * Content provider delegate implementation.
 */
@SuppressWarnings("restriction")
public class ContentProviderDelegate implements ICommonContentProvider, ITreePathContentProvider {
	private final static Object[] NO_ELEMENTS = new Object[0];

	// The "Redirected Peers" filter id
	private final static String REDIRECT_PEERS_FILTER_ID = "org.eclipse.tcf.te.tcf.ui.navigator.RedirectPeersFilter"; //$NON-NLS-1$
	// The current user filter id
	private final static String CURRENT_USER_FILTER_ID = "org.eclipse.tcf.te.tcf.ui.navigator.PeersByCurrentUserFilter"; //$NON-NLS-1$


	// The locator model listener instance
	/* default */ IModelListener modelListener = null;

	// Internal map of RemotePeerDiscoverRootNodes per peer id
	private final Map<String, PeerRedirectorGroupNode> roots = new HashMap<String, PeerRedirectorGroupNode>();

	// Flag to remember if invisible nodes are to be included in the list of
	// returned children.
	private final boolean showInvisible;

	INavigatorFilterService navFilterService = null;

	/**
	 * Constructor.
	 */
	public ContentProviderDelegate() {
		this(false);
	}

	/**
	 * Constructor.
	 *
	 * @param showInvisible If <code>true</code>, {@link #getChildren(Object)} will include invisible nodes too.
	 */
	public ContentProviderDelegate(boolean showInvisible) {
		super();
		this.showInvisible = showInvisible;
	}

	/**
	 * Determines if the given peer model node is a value-add.
	 *
	 * @param peerModel The peer model node. Must not be <code>null</code>.
	 * @return <code>True</code> if the peer model node is a value-add, <code>false</code> otherwise.
	 */
	/* default */ final boolean isValueAdd(IPeerModel peerModel) {
		Assert.isNotNull(peerModel);

		String value = peerModel.getPeer().getAttributes().get("ValueAdd"); //$NON-NLS-1$
		boolean isValueAdd = value != null && ("1".equals(value.trim()) || Boolean.parseBoolean(value.trim())); //$NON-NLS-1$

		return isValueAdd;
	}

	/**
	 * Determines if the given peer model node is filtered from the view completely.
	 *
	 * @param peerModel The peer model node. Must not be <code>null</code>.
	 * @return <code>True</code> if filtered, <code>false</code> otherwise.
	 */
	/* default */ final boolean isFiltered(IPeerModel peerModel) {
		Assert.isNotNull(peerModel);

		boolean filtered = false;

		filtered |= isValueAdd(peerModel) && UIPlugin.getDefault().getPreferenceStore().getBoolean(IPreferenceKeys.PREF_HIDE_PROXIES_AND_VALUEADDS);
		if (!showInvisible) {
			filtered |= !peerModel.isVisible();
		}

		return filtered;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreeContentProvider#getChildren(java.lang.Object)
	 */
	@Override
	public Object[] getChildren(Object parentElement) {
		Object[] children = NO_ELEMENTS;

		// The category element if the parent element is a category node
		final ICategory category = parentElement instanceof ICategory ? (ICategory)parentElement : null;
		// The category id if the parent element is a category node
		final String catID = category != null ? category.getId() : null;

		// Determine if both the "My Targets" and "Neighborhood" categories are hidden
		boolean allHidden = false;

		ICategory myTargetsCat = CategoriesExtensionPointManager.getInstance().getCategory(IUIConstants.ID_CAT_MY_TARGETS, false);
		ICategory neighborhoodCat = CategoriesExtensionPointManager.getInstance().getCategory(IUIConstants.ID_CAT_NEIGHBORHOOD, false);

		allHidden = neighborhoodCat != null && !neighborhoodCat.isEnabled() && myTargetsCat != null && !myTargetsCat.isEnabled();

		// If the parent element is a category, than we assume
		// the locator model as parent element.
		if (parentElement instanceof ICategory) {
			parentElement = Model.getModel();
		}
		// If the parent element is the root element and "all"
		// categories are hidden, assume the locator model as parent element
		if (parentElement instanceof IRoot && allHidden) {
			parentElement = Model.getModel();
		}

		// If it is the locator model, get the peers
		if (parentElement instanceof ILocatorModel) {
			final ILocatorModel model = (ILocatorModel)parentElement;
			final IPeerModel[] peers = model.getPeers();
			final List<IPeerModel> candidates = new ArrayList<IPeerModel>();

			if (IUIConstants.ID_CAT_FAVORITES.equals(catID)) {
				for (IPeerModel peer : peers) {
					ICategorizable categorizable = (ICategorizable)peer.getAdapter(ICategorizable.class);
					if (categorizable == null) {
						categorizable = (ICategorizable)Platform.getAdapterManager().getAdapter(peer, ICategorizable.class);
					}
					Assert.isNotNull(categorizable);

					boolean isFavorite = Managers.getCategoryManager().belongsTo(catID, categorizable.getId());
					if (isFavorite && !candidates.contains(peer)) {
						candidates.add(peer);
					}
				}
			}
			else if (IUIConstants.ID_CAT_MY_TARGETS.equals(catID)) {
				for (IPeerModel peer : peers) {
					// Check for filtered nodes (Value-add's and Proxies)
					if (isFiltered(peer)) {
						continue;
					}

					ICategorizable categorizable = (ICategorizable)peer.getAdapter(ICategorizable.class);
					if (categorizable == null) {
						categorizable = (ICategorizable)Platform.getAdapterManager().getAdapter(peer, ICategorizable.class);
					}
					Assert.isNotNull(categorizable);

					boolean isStatic = peer.isStatic();

					// Static peers, or if launched by current user -> add automatically to "My Targets"
					boolean startedByCurrentUser = System.getProperty("user.name").equals(peer.getPeer().getUserName()); //$NON-NLS-1$
					if (!startedByCurrentUser) {
						// If the "Neighborhood" category is not visible, ignore the startedByCurrentUser flag
						if (neighborhoodCat != null && !neighborhoodCat.isEnabled()) {
							startedByCurrentUser = true;
						}
					}

					boolean isMyTargets = Managers.getCategoryManager().belongsTo(catID, categorizable.getId());
					if (!isMyTargets && (isStatic || startedByCurrentUser)) {
						// "Value-add's" are not saved to the category persistence automatically
						if (isValueAdd(peer)) {
							Managers.getCategoryManager().addTransient(catID, categorizable.getId());
						} else {
							Managers.getCategoryManager().add(catID, categorizable.getId());
						}
						isMyTargets = true;
					}

					if (isMyTargets && !candidates.contains(peer)) {
						candidates.add(peer);
					}
				}
			}
			else if (IUIConstants.ID_CAT_NEIGHBORHOOD.equals(catID)) {
				for (IPeerModel peer : peers) {
					// Check for filtered nodes (Value-add's and Proxies)
					if (isFiltered(peer)) {
						continue;
					}

					ICategorizable categorizable = (ICategorizable)peer.getAdapter(ICategorizable.class);
					if (categorizable == null) {
						categorizable = (ICategorizable)Platform.getAdapterManager().getAdapter(peer, ICategorizable.class);
					}
					Assert.isNotNull(categorizable);

					boolean isStatic = peer.isStatic();

					boolean startedByCurrentUser = System.getProperty("user.name").equals(peer.getPeer().getUserName()); //$NON-NLS-1$
					if (startedByCurrentUser) {
						// If the "My Targets" category is not visible, ignore the startedByCurrentUser flag
						if (myTargetsCat != null && !myTargetsCat.isEnabled()) {
							startedByCurrentUser = false;
						}
					}

					boolean isNeighborhood = Managers.getCategoryManager().belongsTo(catID, categorizable.getId());
					if (!isNeighborhood && !isStatic && !startedByCurrentUser) {
						// "Neighborhood" is always transient
						Managers.getCategoryManager().addTransient(catID, categorizable.getId());
						isNeighborhood = true;
					}

					if (isNeighborhood && !candidates.contains(peer)) {
						candidates.add(peer);
					}
				}
			}
			else if (catID != null) {
				for (IPeerModel peer : peers) {
					ICategorizable categorizable = (ICategorizable)peer.getAdapter(ICategorizable.class);
					if (categorizable == null) {
						categorizable = (ICategorizable)Platform.getAdapterManager().getAdapter(peer, ICategorizable.class);
					}
					Assert.isNotNull(categorizable);

					boolean belongsTo = category.belongsTo(peer);
					if (belongsTo) {
						candidates.add(peer);
					}
				}
			}
			else {
				for (IPeerModel peer : peers) {
					// Check for filtered nodes (Value-add's and Proxies)
					if (isFiltered(peer)) {
						continue;
					}
					candidates.add(peer);
				}
			}

			children = candidates.toArray(new IPeerModel[candidates.size()]);
		}
		// If it is a peer model itself, get the child peers
		else if (parentElement instanceof IPeerModel) {
			String parentPeerId = ((IPeerModel)parentElement).getPeerId();
			List<IPeerModel> candidates = Model.getModel().getChildren(parentPeerId);
			if (candidates != null && candidates.size() > 0) {
				PeerRedirectorGroupNode rootNode = roots.get(parentPeerId);
				if (rootNode == null) {
					rootNode = new PeerRedirectorGroupNode(parentPeerId);
					roots.put(parentPeerId, rootNode);
				}
				children = new Object[] { rootNode };
			} else {
				roots.remove(parentPeerId);
			}
		}
		// If it is a remote peer discover root node, return the children
		// for the associated peer id.
		else if (parentElement instanceof PeerRedirectorGroupNode) {
			List<IPeerModel> candidates = Model.getModel().getChildren(((PeerRedirectorGroupNode)parentElement).peerId);
			if (candidates != null && candidates.size() > 0) {
				children = candidates.toArray();
			}
		}

		return children;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreePathContentProvider#getChildren(org.eclipse.jface.viewers.TreePath)
	 */
	@Override
	public Object[] getChildren(TreePath parentPath) {
		// getChildren is independent of the elements tree path
		return parentPath != null ? getChildren(parentPath.getLastSegment()) : NO_ELEMENTS;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreeContentProvider#getParent(java.lang.Object)
	 */
	@Override
	public Object getParent(final Object element) {
		// If it is a peer model node, return the parent locator model
		if (element instanceof IPeerModel) {
			// If it is a peer redirector, return the parent remote peer discover root node
			if (((IPeerModel)element).getPeer() instanceof IPeerRedirector) {
				IPeer parentPeer =  ((IPeerRedirector)((IPeerModel)element).getPeer()).getParent();
				String parentPeerId = parentPeer.getID();
				if (!roots.containsKey(parentPeerId)) {
					roots.put(parentPeer.getID(), new PeerRedirectorGroupNode(parentPeerId));
				}
				return roots.get(parentPeerId);
			}

			// Determine the parent category node
			ICategory category = null;
			String[] categoryIds = Managers.getCategoryManager().getCategoryIds(((IPeerModel)element).getPeerId());
			// If we have more than one, take the first one as parent category.
			// To get all parents, the getParents(Object) method must be called
			if (categoryIds != null && categoryIds.length > 0) {
				category = CategoriesExtensionPointManager.getInstance().getCategory(categoryIds[0], false);
			}

			return category != null ? category : ((IPeerModel)element).getModel();
		} else if (element instanceof PeerRedirectorGroupNode) {
			// Return the parent peer model node
			final AtomicReference<IPeerModel> parent = new AtomicReference<IPeerModel>();
			final Runnable runnable = new Runnable() {
				@Override
				public void run() {
					parent.set(Model.getModel().getService(ILocatorModelLookupService.class).lkupPeerModelById(((PeerRedirectorGroupNode)element).peerId));
				}
			};

			Assert.isTrue(!Protocol.isDispatchThread());

			// The caller thread is very likely the display thread. We have to us a little
			// trick here to avoid blocking the display thread via a wait on a monitor as
			// this can (and has) lead to dead-locks with the TCF event dispatch thread if
			// something fatal (OutOfMemoryError in example) happens in-between.
			ExecutorsUtil.executeWait(new Runnable() {
				@Override
				public void run() {
					Protocol.invokeAndWait(runnable);
				}
			});

			return parent.get();
		}
		return null;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreePathContentProvider#getParents(java.lang.Object)
	 */
	@Override
	public TreePath[] getParents(Object element) {
		// Not sure if we ever have to calculate the _full_ tree path. The parent NavigatorContentServiceContentProvider
		// is consuming only the last segment.
		List<TreePath> pathes = new ArrayList<TreePath>();

		if (element instanceof IPeerModel) {
			if (Managers.getCategoryManager().belongsTo(IUIConstants.ID_CAT_FAVORITES, ((IPeerModel)element).getPeerId())) {
				// Get the "Favorites" category
				ICategory favCategory = CategoriesExtensionPointManager.getInstance().getCategory(IUIConstants.ID_CAT_FAVORITES, false);
				if (favCategory != null) {
					pathes.add(new TreePath(new Object[] { favCategory }));
				}
			}

			// Determine the default parent
			Object parent = getParent(element);
			if (parent != null) {
				pathes.add(new TreePath(new Object[] { parent }));
			}
		}

		return pathes.toArray(new TreePath[pathes.size()]);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreeContentProvider#hasChildren(java.lang.Object)
	 */
	@Override
	public boolean hasChildren(Object element) {
		Object[] children = getChildren(element);

		if (children != null && children.length > 0 && navFilterService != null) {
			for (ViewerFilter filter : navFilterService.getVisibleFilters(true)) {
				children = filter.filter(null, element, children);
			}
		}

		return children != null && children.length > 0;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.ITreePathContentProvider#hasChildren(org.eclipse.jface.viewers.TreePath)
	 */
	@Override
	public boolean hasChildren(TreePath path) {
		// hasChildren is independent of the elements tree path
		return path != null ? hasChildren(path.getLastSegment()) : false;
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.IStructuredContentProvider#getElements(java.lang.Object)
	 */
	@Override
	public Object[] getElements(Object inputElement) {
		return getChildren(inputElement);
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.IContentProvider#dispose()
	 */
	@Override
	public void dispose() {
		roots.clear();
	}

	/* (non-Javadoc)
	 * @see org.eclipse.jface.viewers.IContentProvider#inputChanged(org.eclipse.jface.viewers.Viewer, java.lang.Object, java.lang.Object)
	 */
	@Override
	public void inputChanged(final Viewer viewer, Object oldInput, Object newInput) {
		final ILocatorModel model = Model.getModel();

		// Create and attach the model listener if not yet done
		if (modelListener == null && model != null && viewer instanceof CommonViewer) {
			modelListener = new ModelListener(model, (CommonViewer)viewer);
			Protocol.invokeLater(new Runnable() {
				@Override
				public void run() {
					model.addListener(modelListener);
				}
			});
		}

		if (model != null && newInput instanceof IRoot) {
			// Refresh the model asynchronously
			Protocol.invokeLater(new Runnable() {
				@Override
				public void run() {
					model.getService(ILocatorModelRefreshService.class).refresh(null);
				}
			});
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.navigator.ICommonContentProvider#init(org.eclipse.ui.navigator.ICommonContentExtensionSite)
	 */
	@Override
	public void init(ICommonContentExtensionSite config) {
		Assert.isNotNull(config);

		// Make sure that the hidden "Redirected Peers" filter is active
		INavigatorContentService cs = config.getService();
		navFilterService = cs != null ? cs.getFilterService() : null;
		if (navFilterService instanceof NavigatorFilterService) {
			final NavigatorFilterService filterService = (NavigatorFilterService)navFilterService;
			boolean activeFiltersChanged = false;

			// Reconstruct the list of active filters based on the visible filter descriptors
			List<String> activeFilderIds = new ArrayList<String>();

			ICommonFilterDescriptor[] descriptors = filterService.getVisibleFilterDescriptors();
			for (ICommonFilterDescriptor descriptor : descriptors) {
				if (descriptor.getId() != null && !"".equals(descriptor.getId()) && filterService.isActive(descriptor.getId())) { //$NON-NLS-1$
					activeFilderIds.add(descriptor.getId());
				}
			}

			if (!activeFilderIds.contains(REDIRECT_PEERS_FILTER_ID)) {
				activeFilderIds.add(REDIRECT_PEERS_FILTER_ID);
				activeFiltersChanged = true;
			}

			if (UIPlugin.getDefault().getPreferenceStore().getBoolean(IPreferenceKeys.PREF_ACTIVATE_CURRENT_USER_FILTER)
					&& !navFilterService.isActive(CURRENT_USER_FILTER_ID)) {
				IDialogSettings settings = UIPlugin.getDefault().getDialogSettings();
				IDialogSettings section = settings.getSection(this.getClass().getSimpleName());
				if (section == null) section = settings.addNewSection(this.getClass().getSimpleName());
				if (!section.getBoolean(IPreferenceKeys.PREF_ACTIVATE_CURRENT_USER_FILTER + ".done")) { //$NON-NLS-1$
					activeFilderIds.add(CURRENT_USER_FILTER_ID);
					activeFiltersChanged = true;
					section.put(IPreferenceKeys.PREF_ACTIVATE_CURRENT_USER_FILTER + ".done", true); //$NON-NLS-1$
				}
			}

			if (activeFiltersChanged) {
				final String[] finActiveFilterIds = activeFilderIds.toArray(new String[activeFilderIds.size()]);
				// Do the update view asynchronous to avoid reentrant viewer calls
				DisplayUtil.safeAsyncExec(new Runnable() {
					@Override
					public void run() {
						filterService.activateFilterIdsAndUpdateViewer(finActiveFilterIds);
					}
				});
			}
		}
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.navigator.IMementoAware#restoreState(org.eclipse.ui.IMemento)
	 */
	@Override
	public void restoreState(IMemento aMemento) {
	}

	/* (non-Javadoc)
	 * @see org.eclipse.ui.navigator.IMementoAware#saveState(org.eclipse.ui.IMemento)
	 */
	@Override
	public void saveState(IMemento aMemento) {
	}
}

Back to the top