Skip to main content
summaryrefslogtreecommitdiffstats
blob: c06c69e1b177ab79b3f3d8c09d36a5a990923026 (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
/*******************************************************************************
 * Copyright (c) 2007, 2010 BMW Car IT, Technische Universitaet Muenchen, 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:
 *     BMW Car IT - Initial API and implementation
 *     Technische Universitaet Muenchen - Major refactoring and extension
 *******************************************************************************/
package org.eclipse.emf.edapt.history.instantiation.ui;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Collections;
import java.util.EventObject;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

import org.eclipse.emf.common.command.Command;
import org.eclipse.emf.common.command.CommandStackListener;
import org.eclipse.emf.common.util.URI;

// CB Migrate
//import org.eclipse.emf.compare.diff.merge.EMFCompareEObjectCopier;
//import org.eclipse.emf.compare.diff.merge.service.MergeService;
//import org.eclipse.emf.compare.diff.metamodel.ComparisonResourceSnapshot;
//import org.eclipse.emf.compare.diff.metamodel.DiffElement;
//import org.eclipse.emf.compare.diff.metamodel.DiffFactory;
//import org.eclipse.emf.compare.diff.metamodel.DiffModel;
//import org.eclipse.emf.compare.diff.service.DiffService;
//import org.eclipse.emf.compare.match.metamodel.Match2Elements;
//import org.eclipse.emf.compare.match.metamodel.MatchModel;
//import org.eclipse.emf.compare.match.service.MatchService;
import org.eclipse.emf.ecore.EDataType;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EPackage;
import org.eclipse.emf.ecore.EcorePackage;
import org.eclipse.emf.ecore.presentation.EcoreEditor;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.edapt.common.LoggingUtils;
import org.eclipse.emf.edapt.common.ResourceUtils;
import org.eclipse.emf.edapt.common.ui.ModelSash;
import org.eclipse.emf.edapt.common.ui.PartAdapter;
import org.eclipse.emf.edapt.common.ui.StructureTreeViewer;
import org.eclipse.emf.edapt.history.HistoryFactory;
import org.eclipse.emf.edapt.history.NoChange;
import org.eclipse.emf.edapt.history.Release;
import org.eclipse.emf.edapt.history.instantiation.BreakingSwitch;
import org.eclipse.emf.edapt.history.presentation.HistoryEditorPlugin;
import org.eclipse.emf.edapt.history.reconstruction.DiffModelFilterUtils;
import org.eclipse.emf.edapt.history.reconstruction.DiffModelOrderFilter;
import org.eclipse.emf.edapt.history.reconstruction.DiffModelResourceFilter;
import org.eclipse.emf.edapt.history.reconstruction.IDiffModelFilter;
import org.eclipse.emf.edapt.history.reconstruction.Mapping;
import org.eclipse.emf.edapt.history.reconstruction.ModelAssert;
import org.eclipse.emf.edapt.history.reconstruction.ui.DiffSelectionAdapter;
import org.eclipse.emf.edapt.history.recorder.ui.EcoreEditorDetector;
import org.eclipse.emf.edit.command.ChangeCommand;
import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.viewers.DecoratingLabelProvider;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IColorDecorator;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.ILabelDecorator;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.ILabelProviderListener;
import org.eclipse.jface.viewers.ISelectionChangedListener;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.SelectionChangedEvent;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.SashForm;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IPartListener;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IWorkbenchPart;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;


/**
 * View to support the convergence of a source metamodel to a target metamodel
 * 
 * @author herrmama
 * @author $Author$
 * @version $Rev$
 * @levd.rating RED Rev:
 */
public class ConvergenceView extends ViewPart implements CommandStackListener,
		ISelectionChangedListener {

	/**
	 * Identifier of the view for convenience
	 */
	public static final String ID = ConvergenceView.class.getName();
	
	/**
	 * Viewer for the difference model
	 */
	private ModelSash differenceSash;

	/**
	 * Viewer for the target metamodel
	 */
	private ModelSash targetSash;

	/**
	 * Editor with the source metamodel
	 */
	private EcoreEditor editor;

	/**
	 * Resource containing the source metamodel
	 */
	private Resource sourceResource;

	/**
	 * Resource containing the target metamodel
	 */
	private Resource targetResource;

	/**
	 * Adapter to listen to the difference viewer that automatically updates
	 * source and target metamodel viewer
	 */
	private DiffSelectionAdapter selectionAdapter;
	
	/**
	 * Mapping between source and target metamodel
	 */
	private Mapping mapping;
	
	/**
	 * Flag whether selection is currently going on (in order to avoid {@link StackOverflowError})
	 */
	private boolean selecting = false;

	/**
	 * Set of breaking changes
	 */
	
	// CB Migrate. 
//	private Set<DiffElement> breakingChanges;

	/**
	 * Whether synchronization is turned on or off
	 */
	private boolean synchronization = true;

	/**
	 * Whether the view is currently refreshing
	 */
	private boolean refresh;

	/** Check whether the editor is closed. */
	private final IPartListener partListener = new PartAdapter() {

		/**
		 * {@inheritDoc}
		 */
		@Override
		public void partClosed(IWorkbenchPart part) {
			if (editor == part) {
				differenceSash.getStructureViewer().setInput(null);
				targetSash.getStructureViewer().setInput(null);

				detachOldEditor();
			}
		}

	};

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void createPartControl(Composite parent) {
		SashForm sash = new SashForm(parent, SWT.HORIZONTAL);
		
		differenceSash = new ModelSash(sash, SWT.None);
		StructureTreeViewer differenceViewer = differenceSash.getStructureViewer();
		differenceViewer.setLabelProvider(new DecoratingLabelProvider((ILabelProvider) differenceViewer.getLabelProvider(), new Decorator()));
		
		targetSash = new ModelSash(sash, SWT.None);
		targetSash.getStructureViewer().addSelectionChangedListener(new ISelectionChangedListener() {

			public void selectionChanged(SelectionChangedEvent event) {
				if(selecting) return;
				if(event.getSelection() instanceof IStructuredSelection) {
					IStructuredSelection selection = (IStructuredSelection) event.getSelection();
					if(selection.getFirstElement() instanceof EObject) {
						EObject element = (EObject) selection.getFirstElement();
						EObject source = mapping.getSource(element);
						if(source != null) {
							selecting = true;
							editor.setSelectionToViewer(Collections.singleton(source));
							selecting = false;
						}
					}
				}
			}
			
		});
		
		differenceViewer.addDoubleClickListener(new IDoubleClickListener() {
			public void doubleClick(DoubleClickEvent event) {
				if(event.getSelection() instanceof IStructuredSelection) {
					IStructuredSelection selection = (IStructuredSelection) event.getSelection();
					
					System.out.println("DifferenViewer doubleclick, selection" + selection);
					// CB Migrate
					// Execute a change command on the editor editing domain. 
					
//					if(selection.getFirstElement() instanceof DiffElement) {
//						final DiffElement element = (DiffElement) selection.getFirstElement();
//						
//						editor.getEditingDomain().getCommandStack().execute(new ChangeCommand(editor.getEditingDomain().getResourceSet()) {
//
//							@Override
//							protected void doExecute() {
//										fixCopier();
//										MergeService.merge(element, true);
//							}
//							
//						});
//					}
				}
			}
		});
		
		getSite().getPage().addPartListener(partListener);
		
		getViewSite().getActionBars().getToolBarManager().add(
				new Action("Sync", IAction.AS_CHECK_BOX) {

					{
						setChecked(true);
						setImageDescriptor(PlatformUI.getWorkbench()
								.getSharedImages().getImageDescriptor(
										ISharedImages.IMG_ELCL_SYNCED));
						setDisabledImageDescriptor(PlatformUI.getWorkbench()
								.getSharedImages().getImageDescriptor(
										ISharedImages.IMG_ELCL_SYNCED_DISABLED));
					}

					@Override
					public void run() {
						setSynchronization(isChecked());
					}
				});
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void setFocus() {
		if(!differenceSash.isDisposed()) {
			differenceSash.setFocus();
		}
	}

	/**
	 * Initialize the contents of the view
	 */
	public void init(URI targetURI, EcoreEditor editor) {
		detachOldEditor();		
		attachNewEditor(targetURI, editor);
	}

	/**
	 * Detach the view from the old editor
	 */
	private void detachOldEditor() {
		if(this.editor != null) {
			this.editor.getEditingDomain().getCommandStack().removeCommandStackListener(this);
			this.editor.removeSelectionChangedListener(this);
			if(!differenceSash.getStructureViewer().getTree().isDisposed()) {
				differenceSash.getStructureViewer().getTree().removeSelectionListener(selectionAdapter);
			}
			this.editor = null;
			
			// CB Migrate
//			breakingChanges = null;
		}
	}

	/**
	 * Attach the view to the new editor
	 */
	private void attachNewEditor(URI targetURI, EcoreEditor editor) {
		try {
			sourceResource = editor.getEditingDomain().getResourceSet().getResources().get(0);
			
			ResourceSet resourceSet = ResourceUtils.loadResourceSet(targetURI);
			targetResource = resourceSet.getResources().get(0);
			
			this.editor = editor;
			this.editor.getEditingDomain().getCommandStack().addCommandStackListener(this);
			selectionAdapter = new DiffSelectionAdapter(editor.getViewer(), null, targetSash.getStructureViewer(), targetSash.getPropertiesViewer()) {
				@Override
				public void widgetSelected(SelectionEvent e) {
					selecting = true;
					super.widgetSelected(e);
					selecting = false;
				}
			};
			differenceSash.getStructureViewer().getTree().addSelectionListener(selectionAdapter);
			this.editor.addSelectionChangedListener(this);
			
			refresh();
			targetSash.getStructureViewer().setInput(targetResource);
			targetSash.getStructureViewer().expandToLevel(2);
			
		} catch (IOException e) {
			LoggingUtils
					.logError(HistoryEditorPlugin.getPlugin(), e);
		}
	}

	/**
	 * {@inheritDoc}
	 */
	public void commandStackChanged(EventObject event) {
		if(!refresh && synchronization) {
			refresh();
		}
	}

	/**
	 * Refresh viewer contents
	 */
	private void refresh() {
//		try {
			refresh = true;
				
			
			// CB Migrate, we need a comparison snapshot here. 
			
			
//			ComparisonResourceSnapshot snapshot = compare();

//			if (ModelAssert.numberOfChanges(snapshot.getDiff()) == 0) {
//				if(targetResource != null) {
//					URI targetURI = targetResource.getURI();
//					Integer number = extractNumber(targetURI);
//					if(number != null) {
//						addMarker(number+1);
//						String name = targetURI.lastSegment().replace(number.toString(), "" + (number+1));
//						try {
//							targetURI = targetURI.trimSegments(1).appendSegment(name);
//							
//							ResourceSet resourceSet;
//							resourceSet = ResourceUtils.loadResourceSet(targetURI);
//							targetResource = resourceSet.getResources().get(0);
//							
//							targetSash.getStructureViewer().setInput(targetResource);
//							targetSash.getStructureViewer().expandToLevel(2);
//
//							snapshot = compare();
//						} catch (IOException e) {
//							// ignore
//						}
//					}
//				}
//			}

//			initMapping(snapshot.getMatch());
//			calculateBreaking(snapshot.getDiff());

//			differenceSash.getStructureViewer().setInput(snapshot.getDiff());
			
			
			
			differenceSash.getStructureViewer().expandToLevel(3);
			
//		} catch (InterruptedException e) {
//			LoggingUtils
//					.logError(HistoryEditorPlugin.getPlugin(), e);
//		} finally {
//			refresh = false;
//		}
	}
	
	
	/** Compare source and target resource. */
// CB Migrate
// Returns a comparison snapshot. 
	
	
//	private ComparisonResourceSnapshot compare() throws InterruptedException {
//		ComparisonResourceSnapshot snapshot = DiffFactory.eINSTANCE
//				.createComparisonResourceSnapshot();
//
//		MatchModel match = MatchService.doResourceMatch(targetResource,
//				sourceResource, null);
//		DiffModel diff = DiffService.doDiff(match);
//		IDiffModelFilter filter = DiffModelFilterUtils
//				.and(DiffModelOrderFilter.INSTANCE,
//						DiffModelResourceFilter.INSTANCE);
//		DiffModelFilterUtils.filter(diff, filter);
//
//		snapshot.setMatch(match);
//		snapshot.setDiff(diff);
//
//		return snapshot;
//
//	}

	/**
	 * Add a marker with the current revision number to the history
	 */
	private void addMarker(final Integer number) {
		final Release release = EcoreEditorDetector.getInstance().getListener(
				editor).getHistory().getLastRelease();
		Command command = new ChangeCommand(release) {
			@Override
			protected void doExecute() {
				NoChange marker = HistoryFactory.eINSTANCE.createNoChange();
				marker.setDescription(number.toString());
				release.getChanges().add(marker);
			}
		};
		editor.getEditingDomain().getCommandStack().execute(command);
	}

	/**
	 * Initialize the mapping
	 */
	
	
	// CB Migrate
//	private void initMapping(MatchModel match) {
//		mapping = new Mapping();
//		for(Iterator<EObject> i = match.eAllContents(); i.hasNext(); ) {
//			EObject element = i.next();
//			if(element instanceof Match2Elements) {
//				Match2Elements match2Elements = (Match2Elements) element;
//				mapping.map(match2Elements.getRightElement(), match2Elements
//						.getLeftElement());
//			}
//		}
//		selectionAdapter.setMapping(mapping);
//	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void dispose() {
		getSite().getPage().removePartListener(partListener);
		detachOldEditor();
		super.dispose();
	}

	/**
	 * {@inheritDoc}
	 */
	public void selectionChanged(SelectionChangedEvent event) {
		if(selecting) return;
		if(event.getSelection() instanceof IStructuredSelection) {
			IStructuredSelection selection = (IStructuredSelection) event.getSelection();
			if(selection.getFirstElement() instanceof EObject) {
				EObject element = (EObject) selection.getFirstElement();
				EObject target = mapping.getTarget(element);
				if(target != null) {
					selecting = true;
					targetSash.getStructureViewer().setSelection(new StructuredSelection(target), true);
					selecting = false;
				}
			}
		}
	}

	/**
	 * Calculate the breaking changes
	 */
	
	// CB Migrate
//	public void calculateBreaking(DiffModel model) {
//
//		breakingChanges = new HashSet<DiffElement>();
//		BreakingSwitch s = new BreakingSwitch();
//		
//		for(Iterator<EObject> i = model.eAllContents(); i.hasNext(); ) {
//			EObject eObject = i.next();
//			if(eObject instanceof DiffElement) {
//				DiffElement element = (DiffElement) eObject;
//				boolean breaking = s.doSwitch(element);
//				if(breaking) {
//					breakingChanges.add(element);
//				}
//			}
//		}
//		
//		for(DiffElement change : new HashSet<DiffElement>(breakingChanges)) {
//			while(change.eContainer() != null && change.eContainer() instanceof DiffElement) {
//				change = (DiffElement) change.eContainer();
//				breakingChanges.add(change);
//			}
//		}
//	}
	
	/**
	 * Extract the revision number from the URI
	 * 
	 * @param targetURI
	 * @return Revision number
	 */
	private Integer extractNumber(URI targetURI) {
		String name = targetURI.trimFileExtension().lastSegment();
		int index = name.indexOf('_');
		if(index >= 0) {
			name = name.substring(index+1);
			index = name.indexOf('.');
			if(index >= 0) {
				name = name.substring(index+1);
				try {
					return Integer.parseInt(name);
				}
				catch(NumberFormatException e) {
					return null;
				}
			}
		}
		return null;
	}
	
	/**
	 * Enable or disable synchronization
	 * 
	 * @param synchronization
	 */
	private void setSynchronization(boolean synchronization) {
		this.synchronization = synchronization;
		if(synchronization) {
			refresh();
		}
	}
	
	/**
	 * @return Widget for difference representation
	 */
	public ModelSash getDifferenceSash() {
		return differenceSash;
	}

	/**
	 * Fix the copier of EMF Compare
	 */
	
	// CB Migrate
//	private void fixCopier() {
//		try {
//			DiffModel diff = (DiffModel) differenceSash.getStructureViewer()
//					.getInput();
//			Field field = MergeService.class
//					.getDeclaredField("copier");
//			field.setAccessible(true);
//				field.set(null, new EMFCompareEObjectCopier(diff) {
//					@Override
//					public EObject get(Object key) {
//					EObject value = super.get(key);
//					if (value == null) {
//						if (key instanceof EDataType) {
//							EDataType type = (EDataType) key;
//							EPackage ePackage = type.getEPackage();
//							if (ePackage == EcorePackage.eINSTANCE) {
//								value = type;
//							}
//						} else if (key instanceof EObject) {
//							value = mapping.getSource((EObject) key);
//							}
//					}
//						return value;
//									}
//				});
//		} catch (SecurityException e) {
//			// ignore
//		} catch (NoSuchFieldException e) {
//			// ignore
//		} catch (IllegalArgumentException e) {
//			// ignore
//		} catch (IllegalAccessException e) {
//			// ignore
//		}
//	}

	/**
	 * Decorator for breaking changes
	 * 
	 * @author herrmama
	 * @author $Author$
	 * @version $Rev$
	 * @levd.rating RED Rev:
	 */
	public class Decorator implements ILabelDecorator, IColorDecorator {
		
		/**
		 * Color for breaking changes
		 */
		private final Color red = new Color(Display.getDefault(), 255, 0, 0);
		
		/**
		 * {@inheritDoc}
		 */
		public Color decorateBackground(Object element) {
			return null;
		}

		/**
		 * {@inheritDoc}
		 */
		public Color decorateForeground(Object element) {
			
// CB Migrate			
//			if(breakingChanges.contains(element)) {
//				return red;
//			}
			return null;
		}

		/**
		 * {@inheritDoc}
		 */
		public Image decorateImage(Image image, Object element) {
			return null;
		}

		/**
		 * {@inheritDoc}
		 */
		public String decorateText(String text, Object element) {
			return null;
		}

		/**
		 * {@inheritDoc}
		 */
		public void addListener(ILabelProviderListener listener) {
			// not required
		}

		/**
		 * {@inheritDoc}
		 */
		public void dispose() {
			red.dispose();
		}

		/**
		 * {@inheritDoc}
		 */
		public boolean isLabelProperty(Object element, String property) {
			return false;
		}

		/**
		 * {@inheritDoc}
		 */
		public void removeListener(ILabelProviderListener listener) {
			// not required
		}
	}
}

Back to the top