Skip to main content
summaryrefslogtreecommitdiffstats
blob: 72ff5fe3bae7027be18d8956c4bfcff49fc7a85a (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
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
/*******************************************************************************
 * Copyright (c) 2013 Obeo.
 * 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:
 *     Obeo - initial API and implementation
 *******************************************************************************/
package org.eclipse.emf.compare.ide.ui.internal.structuremergeviewer;

import static com.google.common.collect.Iterables.getFirst;
import static com.google.common.collect.Sets.newLinkedHashSet;

import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.eventbus.EventBus;
import com.google.common.eventbus.Subscribe;

import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.EventObject;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.eclipse.compare.CompareConfiguration;
import org.eclipse.compare.CompareUI;
import org.eclipse.compare.CompareViewerPane;
import org.eclipse.compare.INavigatable;
import org.eclipse.compare.ITypedElement;
import org.eclipse.compare.internal.CompareHandlerService;
import org.eclipse.compare.structuremergeviewer.ICompareInput;
import org.eclipse.compare.structuremergeviewer.ICompareInputChangeListener;
import org.eclipse.core.resources.IStorage;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.jobs.Job;
import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStack;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.ui.dialogs.DiagnosticDialog;
import org.eclipse.emf.common.util.BasicMonitor;
import org.eclipse.emf.compare.Comparison;
import org.eclipse.emf.compare.EMFCompare;
import org.eclipse.emf.compare.Match;
import org.eclipse.emf.compare.command.ICompareCopyCommand;
import org.eclipse.emf.compare.domain.ICompareEditingDomain;
import org.eclipse.emf.compare.domain.impl.EMFCompareEditingDomain;
import org.eclipse.emf.compare.ide.ui.internal.EMFCompareIDEUIPlugin;
import org.eclipse.emf.compare.ide.ui.internal.configuration.EMFCompareConfiguration;
import org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.util.RedoAction;
import org.eclipse.emf.compare.ide.ui.internal.contentmergeviewer.util.UndoAction;
import org.eclipse.emf.compare.ide.ui.internal.editor.ComparisonScopeInput;
import org.eclipse.emf.compare.ide.ui.internal.logical.ComparisonScopeBuilder;
import org.eclipse.emf.compare.ide.ui.internal.logical.IdenticalResourceMinimizer;
import org.eclipse.emf.compare.ide.ui.internal.logical.StreamAccessorStorage;
import org.eclipse.emf.compare.ide.ui.internal.logical.SubscriberStorageAccessor;
import org.eclipse.emf.compare.ide.ui.internal.util.ExceptionUtil;
import org.eclipse.emf.compare.ide.ui.internal.util.PlatformElementUtil;
import org.eclipse.emf.compare.ide.ui.internal.util.SWTUtil;
import org.eclipse.emf.compare.ide.ui.logical.IModelResolver;
import org.eclipse.emf.compare.ide.ui.logical.IStorageProviderAccessor;
import org.eclipse.emf.compare.internal.merge.MergeMode;
import org.eclipse.emf.compare.internal.utils.ComparisonUtil;
import org.eclipse.emf.compare.rcp.EMFCompareRCPPlugin;
import org.eclipse.emf.compare.rcp.ui.internal.configuration.EMFCompareConfigurationChangeListener;
import org.eclipse.emf.compare.rcp.ui.internal.configuration.IEMFCompareConfigurationChangeListener;
import org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.filters.IDifferenceFilter;
import org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.filters.IDifferenceFilterSelectionChangeEvent;
import org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.filters.StructureMergeViewerFilter;
import org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.groups.IDifferenceGroupProvider;
import org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.groups.StructureMergeViewerGrouper;
import org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.groups.impl.DefaultGroupProvider;
import org.eclipse.emf.compare.rcp.ui.internal.structuremergeviewer.groups.provider.TreeItemProviderAdapterFactorySpec;
import org.eclipse.emf.compare.scope.IComparisonScope;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
import org.eclipse.emf.edit.provider.IDisposable;
import org.eclipse.emf.edit.provider.ReflectiveItemProviderAdapterFactory;
import org.eclipse.emf.edit.provider.resource.ResourceItemProviderAdapterFactory;
import org.eclipse.emf.edit.tree.TreeFactory;
import org.eclipse.emf.edit.tree.TreeNode;
import org.eclipse.jface.viewers.ITreeViewerListener;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TreeExpansionEvent;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
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.TreeItem;
import org.eclipse.team.core.subscribers.Subscriber;
import org.eclipse.team.core.subscribers.SubscriberMergeContext;
import org.eclipse.team.internal.ui.mapping.ModelCompareEditorInput;
import org.eclipse.team.ui.synchronize.ISynchronizeParticipant;
import org.eclipse.team.ui.synchronize.ModelSynchronizeParticipant;
import org.eclipse.ui.actions.ActionFactory;

/**
 * Implementation of {@link AbstractViewerWrapper}.
 * 
 * @author <a href="mailto:axel.richard@obeo.fr">Axel Richard</a>
 */
public class EMFCompareStructureMergeViewer extends AbstractViewerWrapper implements CommandStackListener {

	/**
	 * @author <a href="mailto:mikael.barbero@obeo.fr">Mikael Barbero</a>
	 */
	private final class EMFCompareStructureMergeViewerConfigurationChangeListener extends EMFCompareConfigurationChangeListener {
		@Override
		public void mergePreviewModeChange(MergeMode oldValue, MergeMode newValue) {
			treeRuler.computeConsequences();
			treeRuler.redraw();
		}

		@Override
		public void selectedDifferenceGroupProviderChange(IDifferenceGroupProvider oldValue,
				IDifferenceGroupProvider newValue) {
			treeRuler.computeConsequences();
			treeRuler.redraw();
		}

		@Override
		public void aggregatedViewerPredicateChange(Predicate<? super EObject> oldValue,
				Predicate<? super EObject> newValue) {
			treeRuler.computeConsequences();
			treeRuler.redraw();
		}
	}

	/** The width of the tree ruler. */
	private static final int TREE_RULER_WIDTH = 17;

	/** The adapter factory. */
	private ComposedAdapterFactory fAdapterFactory;

	/** The tree ruler associated with this viewer. */
	private EMFCompareDiffTreeRuler treeRuler;

	private ICompareInputChangeListener fCompareInputChangeListener;

	/** The expand/collapse item listener. */
	private ITreeViewerListener fWrappedTreeListener;

	/** The compare configuration property change listener. */
	private IEMFCompareConfigurationChangeListener fCompareConfigurationPropertyChangeListener;

	/** The tree viewer. */
	private EMFCompareDiffTreeViewer diffTreeViewer;

	/** The undo action. */
	private UndoAction undoAction;

	/** The redo action. */
	private RedoAction redoAction;

	/** The compare handler service. */
	private CompareHandlerService fHandlerService;

	/**
	 * When comparing EObjects from a resource, the resource involved doesn't need to be unload by EMF
	 * Compare.
	 */
	private boolean resourcesShouldBeUnload;

	/**
	 * Constructor.
	 * 
	 * @param parent
	 *            the SWT parent control under which to create the viewer's SWT control.
	 * @param config
	 *            a compare configuration the newly created viewer might want to use.
	 */
	public EMFCompareStructureMergeViewer(Composite parent, EMFCompareConfiguration config) {
		super(parent, config);

		fCompareConfigurationPropertyChangeListener = new EMFCompareStructureMergeViewerConfigurationChangeListener();
		getCompareConfiguration().addChangeListener(fCompareConfigurationPropertyChangeListener);

		inputChangedTask.setPriority(Job.LONG);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see 
	 *      org.eclipse.emf.compare.ide.ui.internal.structuremergeviewer.ViewerWrapper.createControl(Composite,
	 *      CompareConfiguration)
	 */
	@Override
	protected Control createControl(Composite parent, CompareConfiguration config) {
		Composite control = new Composite(parent, SWT.NONE);

		fAdapterFactory = new ComposedAdapterFactory(EMFCompareRCPPlugin.getDefault()
				.getAdapterFactoryRegistry());

		fAdapterFactory.addAdapterFactory(new TreeItemProviderAdapterFactorySpec());
		fAdapterFactory.addAdapterFactory(new ReflectiveItemProviderAdapterFactory());
		fAdapterFactory.addAdapterFactory(new ResourceItemProviderAdapterFactory());
		getCompareConfiguration().setAdapterFactory(fAdapterFactory);

		GridLayout layout = new GridLayout(2, false);
		layout.marginWidth = 0;
		layout.marginHeight = 0;
		layout.horizontalSpacing = 0;
		layout.verticalSpacing = 0;
		GridData data = new GridData(SWT.FILL, SWT.FILL, true, true);
		control.setLayout(layout);
		control.setLayoutData(data);
		diffTreeViewer = new EMFCompareDiffTreeViewer(control, fAdapterFactory, getCompareConfiguration());
		setViewer(diffTreeViewer);
		INavigatable nav = new Navigatable(fAdapterFactory, diffTreeViewer);
		control.setData(INavigatable.NAVIGATOR_PROPERTY, nav);
		control.setData(CompareUI.COMPARE_VIEWER_TITLE, "Model differences");
		diffTreeViewer.getControl().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
		GridData layoutData = new GridData(SWT.FILL, SWT.FILL, false, true);
		layoutData.widthHint = TREE_RULER_WIDTH;
		layoutData.minimumWidth = TREE_RULER_WIDTH;
		treeRuler = new EMFCompareDiffTreeRuler(control, SWT.NONE, layoutData.widthHint, diffTreeViewer,
				getCompareConfiguration());
		treeRuler.setLayoutData(layoutData);

		fCompareInputChangeListener = new ICompareInputChangeListener() {
			public void compareInputChanged(ICompareInput input) {
				EMFCompareStructureMergeViewer.this.compareInputChanged(input);
			}
		};

		fWrappedTreeListener = new ITreeViewerListener() {

			public void treeExpanded(TreeExpansionEvent event) {
				treeRuler.redraw();
			}

			public void treeCollapsed(TreeExpansionEvent event) {
				treeRuler.redraw();
			}
		};
		diffTreeViewer.addTreeListener(fWrappedTreeListener);

		fHandlerService = CompareHandlerService.createFor(getCompareConfiguration().getContainer(),
				diffTreeViewer.getControl().getShell());

		EventBus eventBus = new EventBus();
		eventBus.register(this);

		StructureMergeViewerFilter structureMergeViewerFilter = new StructureMergeViewerFilter(eventBus);
		structureMergeViewerFilter.install(diffTreeViewer);

		StructureMergeViewerGrouper structureMergeViewerGrouper = new StructureMergeViewerGrouper(eventBus);
		structureMergeViewerGrouper.install(diffTreeViewer);

		toolBar = new CompareToolBar(diffTreeViewer, CompareViewerPane.getToolBarManager(parent),
				structureMergeViewerGrouper, structureMergeViewerFilter, getCompareConfiguration());

		return control;
	}

	@Subscribe
	public void recordFilterSelectionChange(IDifferenceFilterSelectionChangeEvent event) {
		final Set<IDifferenceFilter> property = getCompareConfiguration().getSelectedDifferenceFilters();

		final Set<IDifferenceFilter> selectedFilters = newLinkedHashSet(property);
		switch (event.getAction()) {
			case SELECTED:
				selectedFilters.add(event.getFilter());
				break;
			case DESELECTED:
				selectedFilters.remove(event.getFilter());
				break;
			default:
				throw new IllegalStateException();
		}

		getCompareConfiguration().setSelectedDifferenceFilters(ImmutableSet.copyOf(selectedFilters));
		getCompareConfiguration().setAggregatedViewerPredicate(event.getAggregatedPredicate());
	}

	@Subscribe
	public void recordGroupProviderSelectionChange(IDifferenceGroupProvider differenceGroupProvider) {
		List<Adapter> eAdapters = ((Adapter)diffTreeViewer.getRoot()).getTarget().eAdapters();
		IDifferenceGroupProvider oldDifferenceGroupProvider = (IDifferenceGroupProvider)EcoreUtil.getAdapter(
				eAdapters, IDifferenceGroupProvider.class);
		if (oldDifferenceGroupProvider != null) {
			eAdapters.remove(oldDifferenceGroupProvider);
		}
		eAdapters.add(differenceGroupProvider);

		getCompareConfiguration().setSelectedDifferenceGroupProvider(differenceGroupProvider);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.jface.viewers.Viewer#fireSelectionChanged(SelectionChangedEvent)
	 */
	@Override
	protected void fireSelectionChanged(SelectionChangedEvent event) {
		super.fireSelectionChanged(event);
		treeRuler.selectionChanged(event);
		treeRuler.redraw();
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.jface.viewers.Viewer#inputChanged(Object, Object)
	 */
	@Override
	protected void inputChanged(Object input, Object oldInput) {
		if (oldInput instanceof ICompareInput) {
			ICompareInput old = (ICompareInput)oldInput;
			old.removeCompareInputChangeListener(fCompareInputChangeListener);
		}
		if (input instanceof ICompareInput) {
			getViewer().setInput(input); // set input of EMFCompareDiffTreeViewer (useful for next/previous
											// diff buttons)
			ICompareInput ci = (ICompareInput)input;
			ci.addCompareInputChangeListener(fCompareInputChangeListener);

			// Hack to display a message in the tree viewer while the differences are being computed.
			TreeItem item = new TreeItem(diffTreeViewer.getTree(), SWT.NONE);
			item.setText("Computing model differences...");

			compareInputChanged(ci);
		}
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.emf.compare.ide.ui.internal.structuremergeviewer.AbstractViewerWrapper#handleDispose(DisposeEvent)
	 */
	@Override
	protected void handleDispose(DisposeEvent event) {
		if (fHandlerService != null) {
			fHandlerService.dispose();
		}
		getCompareConfiguration().removeChangeListener(fCompareConfigurationPropertyChangeListener);
		diffTreeViewer.removeTreeListener(fWrappedTreeListener);
		Object input = getInput();
		if (input instanceof ICompareInput) {
			ICompareInput ci = (ICompareInput)input;
			ci.removeCompareInputChangeListener(fCompareInputChangeListener);
		}
		compareInputChanged((ICompareInput)null);
		treeRuler.handleDispose();
		fAdapterFactory.dispose();
		toolBar.dispose();
		super.handleDispose(event);
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.emf.common.command.CommandStackListener#commandStackChanged(java.util.EventObject)
	 */
	public void commandStackChanged(EventObject event) {
		if (undoAction != null) {
			undoAction.update();
		}
		if (redoAction != null) {
			redoAction.update();
		}

		Command mostRecentCommand = ((CommandStack)event.getSource()).getMostRecentCommand();
		if (mostRecentCommand instanceof ICompareCopyCommand) {
			Collection<?> affectedObjects = mostRecentCommand.getAffectedObjects();

			SWTUtil.safeAsyncExec(new Runnable() {
				public void run() {
					treeRuler.computeConsequences();
					treeRuler.redraw();
				}
			});
			if (!affectedObjects.isEmpty()) {
				// MUST NOT call a setSelection with a list, o.e.compare does not handle it (cf
				// org.eclipse.compare.CompareEditorInput#getElement(ISelection))
				Object first = getFirst(affectedObjects, null);
				if (first instanceof EObject) {
					IDifferenceGroupProvider groupProvider = getCompareConfiguration()
							.getSelectedDifferenceGroupProvider();
					Iterable<TreeNode> treeNodes = groupProvider.getTreeNodes((EObject)first);
					TreeNode treeNode = getFirst(treeNodes, null);
					if (treeNode != null) {
						final Object adaptedAffectedObject = fAdapterFactory.adapt(treeNode,
								ICompareInput.class);
						SWTUtil.safeAsyncExec(new Runnable() {
							public void run() {
								refresh();
								setSelection(new StructuredSelection(adaptedAffectedObject), true);
							}
						});
					}
				}
			}
		} else {
			// FIXME, should recompute the difference, something happened outside of this compare editor
		}

	}

	private Job inputChangedTask = new Job("Compute Model Differences") {
		@Override
		public IStatus run(IProgressMonitor monitor) {
			SubMonitor subMonitor = SubMonitor.convert(monitor, "Computing Model Differences", 100);
			compareInputChanged((ICompareInput)getInput(), subMonitor.newChild(100));
			return Status.OK_STATUS;
		}
	};

	private CompareToolBar toolBar;

	/**
	 * Triggered by fCompareInputChangeListener and {@link #inputChanged(Object, Object)}.
	 */
	void compareInputChanged(ICompareInput input) {
		if (input == null) {
			// When closing, we don't need a progress monitor to handle the input change
			compareInputChanged((ICompareInput)null, new NullProgressMonitor());
			return;
		}
		// The compare configuration is nulled when the viewer is disposed
		if (getCompareConfiguration() != null) {
			inputChangedTask.schedule();
		}
	}

	void compareInputChanged(CompareInputAdapter input, IProgressMonitor monitor) {
		ICompareEditingDomain editingDomain = getCompareConfiguration().getEditingDomain();
		editingDomain.getCommandStack().addCommandStackListener(this);

		compareInputChanged(null, (Comparison)input.getComparisonObject());
	}

	void compareInputChanged(ComparisonScopeInput input, IProgressMonitor monitor) {
		ICompareEditingDomain editingDomain = getCompareConfiguration().getEditingDomain();
		editingDomain.getCommandStack().addCommandStackListener(this);

		EMFCompare comparator = getCompareConfiguration().getComparator();

		IComparisonScope comparisonScope = input.getComparisonScope();
		Comparison comparison = comparator.compare(comparisonScope, BasicMonitor.toMonitor(monitor));

		reportErrors(comparison);

		compareInputChanged(input.getComparisonScope(), comparison);
	}

	void compareInputChanged(final IComparisonScope scope, final Comparison comparison) {
		if (!getControl().isDisposed()) { // guard against disposal
			IDifferenceGroupProvider selectedGroup = getCompareConfiguration()
					.getSelectedDifferenceGroupProvider();
			final TreeNode treeNode = TreeFactory.eINSTANCE.createTreeNode();
			treeNode.setData(comparison);
			if (selectedGroup == IDifferenceGroupProvider.EMPTY) {
				selectedGroup = new DefaultGroupProvider();
			}
			treeNode.eAdapters().add(selectedGroup);

			diffTreeViewer.setRoot(fAdapterFactory.adapt(treeNode, ICompareInput.class));
			getCompareConfiguration().setComparison(comparison);
			getCompareConfiguration().setComparisonScope(scope);

			SWTUtil.safeAsyncExec(new Runnable() {
				public void run() {
					// Mandatory for the EMFCompareDiffTreeRuler, all TreeItems must have been created
					diffTreeViewer.createChildrenSilently(diffTreeViewer.getTree());
					diffTreeViewer.refreshAfterDiff(diffTreeViewer.getRoot());
					diffTreeViewer.initialSelection();
				}
			});

			ICompareEditingDomain editingDomain = getCompareConfiguration().getEditingDomain();

			undoAction = new UndoAction(editingDomain);
			redoAction = new RedoAction(editingDomain);

			SWTUtil.safeAsyncExec(new Runnable() {
				public void run() {
					fHandlerService.updatePaneActionHandlers(new Runnable() {
						public void run() {
							fHandlerService.setGlobalActionHandler(ActionFactory.UNDO.getId(), undoAction);
							fHandlerService.setGlobalActionHandler(ActionFactory.REDO.getId(), redoAction);

						}
					});
				}
			});

		}
	}

	void compareInputChanged(ICompareInput input, IProgressMonitor monitor) {
		if (input != null) {
			if (input instanceof CompareInputAdapter) {
				resourcesShouldBeUnload = false;
				compareInputChanged((CompareInputAdapter)input, monitor);
			} else if (input instanceof ComparisonScopeInput) {
				resourcesShouldBeUnload = false;
				compareInputChanged((ComparisonScopeInput)input, monitor);
			} else {
				resourcesShouldBeUnload = true;
				SubMonitor subMonitor = SubMonitor.convert(monitor, 100);

				final ITypedElement left = input.getLeft();
				final ITypedElement right = input.getRight();
				final ITypedElement origin = input.getAncestor();

				IComparisonScope scope = null;
				try {
					scope = buildComparisonScope(left, right, origin, subMonitor.newChild(85));
				} catch (Exception e) {
					ExceptionUtil.handleException(e, getCompareConfiguration(), true);
					return;
				}
				final Comparison compareResult = EMFCompare
						.builder()
						.setMatchEngineFactoryRegistry(
								EMFCompareRCPPlugin.getDefault().getMatchEngineFactoryRegistry())
						.setPostProcessorRegistry(EMFCompareRCPPlugin.getDefault().getPostProcessorRegistry())
						.build().compare(scope, BasicMonitor.toMonitor(subMonitor.newChild(15)));

				reportErrors(compareResult);

				final ResourceSet leftResourceSet = (ResourceSet)scope.getLeft();
				final ResourceSet rightResourceSet = (ResourceSet)scope.getRight();
				final ResourceSet originResourceSet = (ResourceSet)scope.getOrigin();

				if (getCompareConfiguration() != null) {
					ICompareEditingDomain editingDomain = getCompareConfiguration().getEditingDomain();
					if (editingDomain != null) {
						editingDomain.getCommandStack().removeCommandStackListener(this);
						if (editingDomain instanceof IDisposable) {
							((IDisposable)editingDomain).dispose();
						}
					}

					editingDomain = EMFCompareEditingDomain.create(leftResourceSet, rightResourceSet,
							originResourceSet);
					editingDomain.getCommandStack().addCommandStackListener(this);
					getCompareConfiguration().setEditingDomain(editingDomain);
				}

				compareInputChanged(scope, compareResult);
			}
		} else {
			ResourceSet leftResourceSet = null;
			ResourceSet rightResourceSet = null;
			ResourceSet originResourceSet = null;

			if (getCompareConfiguration().getComparison() != null) {
				Comparison comparison = getCompareConfiguration().getComparison();
				Iterator<Match> matchIt = comparison.getMatches().iterator();
				if (comparison.isThreeWay()) {
					while (matchIt.hasNext()
							&& (leftResourceSet == null || rightResourceSet == null || originResourceSet == null)) {
						Match match = matchIt.next();
						if (leftResourceSet == null) {
							leftResourceSet = getResourceSet(match.getLeft());
						}
						if (rightResourceSet == null) {
							rightResourceSet = getResourceSet(match.getRight());
						}
						if (originResourceSet == null) {
							originResourceSet = getResourceSet(match.getOrigin());
						}
					}
				} else {
					while (matchIt.hasNext() && (leftResourceSet == null || rightResourceSet == null)) {
						Match match = matchIt.next();
						if (leftResourceSet == null) {
							leftResourceSet = getResourceSet(match.getLeft());
						}
						if (rightResourceSet == null) {
							rightResourceSet = getResourceSet(match.getRight());
						}
					}
				}
			}

			ICompareEditingDomain editingDomain = getCompareConfiguration().getEditingDomain();
			if (editingDomain != null) {
				editingDomain.getCommandStack().removeCommandStackListener(this);
				getCompareConfiguration().setEditingDomain(null);
				if (editingDomain instanceof IDisposable) {
					((IDisposable)editingDomain).dispose();
				}
				editingDomain = null;
			}

			if (resourcesShouldBeUnload) {
				unload(leftResourceSet);
				unload(rightResourceSet);
				unload(originResourceSet);
			}

			if (getCompareConfiguration() != null) {
				getCompareConfiguration().dispose();
			}
			diffTreeViewer.setRoot(null);
		}
	}

	private void reportErrors(final Comparison comparison) {
		if (ComparisonUtil.containsErrors(comparison)) {
			SWTUtil.safeAsyncExec(new Runnable() {
				public void run() {
					DiagnosticDialog.open(getControl().getShell(), "Comparison report", //$NON-NLS-1$
							"Some issues were detected.", comparison.getDiagnostic()); //$NON-NLS-1$
				}
			});
		}
	}

	/**
	 * Constructs the comparison scope corresponding to the given typed elements.
	 * 
	 * @param left
	 *            Left of the compared elements.
	 * @param right
	 *            Right of the compared elements.
	 * @param origin
	 *            Common ancestor of the <code>left</code> and <code>right</code> compared elements.
	 * @param monitor
	 *            Monitor to report progress on.
	 * @return The created comparison scope.
	 */
	private IComparisonScope buildComparisonScope(ITypedElement left, ITypedElement right,
			ITypedElement origin, IProgressMonitor monitor) {
		IStorageProviderAccessor storageAccessor = null;
		if (getSubscriber() != null) {
			storageAccessor = new SubscriberStorageAccessor(getSubscriber());
		}
		IStorage leftStorage = PlatformElementUtil.findFile(left);
		if (leftStorage == null) {
			leftStorage = StreamAccessorStorage.fromTypedElement(left);
		}
		IModelResolver resolver = EMFCompareIDEUIPlugin.getDefault().getModelResolverRegistry()
				.getBestResolverFor(leftStorage);
		final ComparisonScopeBuilder scopeBuilder = new ComparisonScopeBuilder(resolver,
				new IdenticalResourceMinimizer(), storageAccessor);
		return scopeBuilder.build(left, right, origin, monitor);
	}

	/**
	 * Team left us with absolutely no way to determine whether our supplied input is the result of a
	 * synchronization or not.
	 * <p>
	 * In order to properly resolve the logical model of the resource currently being compared we need to know
	 * what "other" resources were part of its logical model, and we need to know the revisions of these
	 * resources we are to load. All of this has already been computed by Team, but it would not let us know.
	 * This method uses discouraged means to get around this "black box" locking from Team.
	 * </p>
	 * <p>
	 * The basic need here is to retrieve the Subscriber from this point. We have a lot of accessible
	 * variables, the two most important being the CompareConfiguration and ICompareInput... I could find no
	 * way around the privileged access to the private ModelCompareEditorInput.participant field. There does
	 * not seem to be any adapter (or Platform.getAdapterManager().getAdapter(...)) that would allow for this,
	 * so I'm taking the long way 'round.
	 * </p>
	 * 
	 * @return The subscriber used for this comparison if any could be found, <code>null</code> otherwise.
	 */
	@SuppressWarnings("restriction")
	private Subscriber getSubscriber() {
		if (getCompareConfiguration().getContainer() instanceof ModelCompareEditorInput) {
			final ModelCompareEditorInput modelInput = (ModelCompareEditorInput)getCompareConfiguration()
					.getContainer();
			ISynchronizeParticipant participant = null;
			try {
				final Field field = ModelCompareEditorInput.class.getDeclaredField("participant"); //$NON-NLS-1$
				AccessController.doPrivileged(new PrivilegedAction<Object>() {
					public Object run() {
						field.setAccessible(true);
						return null;
					}
				});
				participant = (ISynchronizeParticipant)field.get(modelInput);
			} catch (NoSuchFieldException e) {
				// Swallow this, this private field was there at least from 3.5 to 4.3
			} catch (IllegalArgumentException e) {
				// Cannot happen
			} catch (IllegalAccessException e) {
				// "Should" not happen, but ignore it anyway
			}
			if (participant instanceof ModelSynchronizeParticipant
					&& ((ModelSynchronizeParticipant)participant).getContext() instanceof SubscriberMergeContext) {
				return ((SubscriberMergeContext)((ModelSynchronizeParticipant)participant).getContext())
						.getSubscriber();
			}
		}
		return null;
	}

	private static void unload(ResourceSet resourceSet) {
		if (resourceSet != null) {
			for (Resource resource : resourceSet.getResources()) {
				resource.unload();
			}
			resourceSet.getResources().clear();
		}
	}

	private static ResourceSet getResourceSet(EObject eObject) {
		if (eObject != null) {
			Resource eResource = eObject.eResource();
			if (eResource != null) {
				return eResource.getResourceSet();
			}
		}
		return null;
	}

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.emf.compare.ide.ui.internal.structuremergeviewer.AbstractViewerWrapper#getCompareConfiguration()
	 */
	@Override
	public EMFCompareConfiguration getCompareConfiguration() {
		return (EMFCompareConfiguration)super.getCompareConfiguration();
	}
}

Back to the top