View | Details | Raw Unified | Return to bug 148836 | Differences between
and this patch

Collapse All | Expand All

(-)src/org/eclipse/gmf/codegen/gmfgen/presentation/GMFGenModelWizard.java (-369 / +81 lines)
Lines 7-21 Link Here
7
package org.eclipse.gmf.codegen.gmfgen.presentation;
7
package org.eclipse.gmf.codegen.gmfgen.presentation;
8
8
9
9
10
import java.util.ArrayList;
11
import java.util.Collection;
12
import java.util.Collections;
13
import java.util.HashMap;
10
import java.util.HashMap;
14
import java.util.Iterator;
15
import java.util.List;
16
import java.util.Map;
11
import java.util.Map;
17
import java.util.MissingResourceException;
18
import java.util.StringTokenizer;
19
12
20
import org.eclipse.core.resources.IContainer;
13
import org.eclipse.core.resources.IContainer;
21
import org.eclipse.core.resources.IFile;
14
import org.eclipse.core.resources.IFile;
Lines 26-58 Link Here
26
import org.eclipse.core.runtime.IProgressMonitor;
19
import org.eclipse.core.runtime.IProgressMonitor;
27
import org.eclipse.core.runtime.Path;
20
import org.eclipse.core.runtime.Path;
28
import org.eclipse.emf.common.util.URI;
21
import org.eclipse.emf.common.util.URI;
29
import org.eclipse.emf.ecore.EClass;
30
import org.eclipse.emf.ecore.EClassifier;
31
import org.eclipse.emf.ecore.EObject;
22
import org.eclipse.emf.ecore.EObject;
32
import org.eclipse.emf.ecore.resource.Resource;
23
import org.eclipse.emf.ecore.resource.Resource;
33
import org.eclipse.emf.ecore.resource.ResourceSet;
24
import org.eclipse.emf.ecore.resource.ResourceSet;
34
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
25
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
35
import org.eclipse.emf.ecore.xmi.XMLResource;
26
import org.eclipse.emf.ecore.xmi.XMLResource;
36
import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry;
27
import org.eclipse.emf.edit.ui.provider.ExtendedImageRegistry;
37
import org.eclipse.gmf.codegen.gmfgen.GMFGenFactory;
38
import org.eclipse.gmf.codegen.gmfgen.GMFGenPackage;
28
import org.eclipse.gmf.codegen.gmfgen.GMFGenPackage;
39
import org.eclipse.gmf.codegen.gmfgen.presentation.EditorPlugin;
40
41
42
import org.eclipse.jface.dialogs.MessageDialog;
29
import org.eclipse.jface.dialogs.MessageDialog;
43
import org.eclipse.jface.viewers.ISelection;
30
import org.eclipse.jface.viewers.ISelection;
44
import org.eclipse.jface.viewers.IStructuredSelection;
31
import org.eclipse.jface.viewers.IStructuredSelection;
45
import org.eclipse.jface.viewers.StructuredSelection;
32
import org.eclipse.jface.viewers.StructuredSelection;
46
import org.eclipse.jface.wizard.Wizard;
33
import org.eclipse.jface.wizard.Wizard;
47
import org.eclipse.jface.wizard.WizardPage;
48
import org.eclipse.swt.SWT;
49
import org.eclipse.swt.events.ModifyEvent;
50
import org.eclipse.swt.events.ModifyListener;
51
import org.eclipse.swt.layout.GridData;
52
import org.eclipse.swt.layout.GridLayout;
53
import org.eclipse.swt.widgets.Combo;
54
import org.eclipse.swt.widgets.Composite;
55
import org.eclipse.swt.widgets.Label;
56
import org.eclipse.ui.INewWizard;
34
import org.eclipse.ui.INewWizard;
57
import org.eclipse.ui.IWorkbench;
35
import org.eclipse.ui.IWorkbench;
58
import org.eclipse.ui.IWorkbenchPage;
36
import org.eclipse.ui.IWorkbenchPage;
Lines 69-94 Link Here
69
 * This is a simple wizard for creating a new model file.
47
 * This is a simple wizard for creating a new model file.
70
 * <!-- begin-user-doc -->
48
 * <!-- begin-user-doc -->
71
 * <!-- end-user-doc -->
49
 * <!-- end-user-doc -->
72
 * @generated
50
 * @generated NOT
73
 */
51
 */
74
public class GMFGenModelWizard extends Wizard implements INewWizard {
52
public class GMFGenModelWizard extends Wizard implements INewWizard {
75
	/**
53
	/**
76
	 * This caches an instance of the model package.
77
	 * <!-- begin-user-doc -->
78
	 * <!-- end-user-doc -->
79
	 * @generated
80
	 */
81
	protected GMFGenPackage gmfGenPackage = GMFGenPackage.eINSTANCE;
82
83
	/**
84
	 * This caches an instance of the model factory.
85
	 * <!-- begin-user-doc -->
86
	 * <!-- end-user-doc -->
87
	 * @generated
88
	 */
89
	protected GMFGenFactory gmfGenFactory = gmfGenPackage.getGMFGenFactory();
90
91
	/**
92
	 * This is the file creation page.
54
	 * This is the file creation page.
93
	 * <!-- begin-user-doc -->
55
	 * <!-- begin-user-doc -->
94
	 * <!-- end-user-doc -->
56
	 * <!-- end-user-doc -->
Lines 97-110 Link Here
97
	protected GMFGenModelWizardNewFileCreationPage newFileCreationPage;
59
	protected GMFGenModelWizardNewFileCreationPage newFileCreationPage;
98
60
99
	/**
61
	/**
100
	 * This is the initial object creation page.
101
	 * <!-- begin-user-doc -->
102
	 * <!-- end-user-doc -->
103
	 * @generated
104
	 */
105
	protected GMFGenModelWizardInitialObjectCreationPage initialObjectCreationPage;
106
107
	/**
108
	 * Remember the selection during initialization for populating the default container.
62
	 * Remember the selection during initialization for populating the default container.
109
	 * <!-- begin-user-doc -->
63
	 * <!-- begin-user-doc -->
110
	 * <!-- end-user-doc -->
64
	 * <!-- end-user-doc -->
Lines 121-134 Link Here
121
	protected IWorkbench workbench;
75
	protected IWorkbench workbench;
122
76
123
	/**
77
	/**
124
	 * Caches the names of the types that can be created as the root object.
125
	 * <!-- begin-user-doc -->
126
	 * <!-- end-user-doc -->
127
	 * @generated
128
	 */
129
	protected List initialObjectNames;
130
131
	/**
132
	 * This just records the information.
78
	 * This just records the information.
133
	 * <!-- begin-user-doc -->
79
	 * <!-- begin-user-doc -->
134
	 * <!-- end-user-doc -->
80
	 * <!-- end-user-doc -->
Lines 142-263 Link Here
142
	}
88
	}
143
89
144
	/**
90
	/**
145
	 * Returns the names of the types that can be created as the root object.
146
	 * <!-- begin-user-doc -->
147
	 * <!-- end-user-doc -->
148
	 * @generated
149
	 */
150
	protected Collection getInitialObjectNames() {
151
		if (initialObjectNames == null) {
152
			initialObjectNames = new ArrayList();
153
			for (Iterator classifiers = gmfGenPackage.getEClassifiers().iterator(); classifiers.hasNext(); ) {
154
				EClassifier eClassifier = (EClassifier)classifiers.next();
155
				if (eClassifier instanceof EClass) {
156
					EClass eClass = (EClass)eClassifier;
157
					if (!eClass.isAbstract()) {
158
						initialObjectNames.add(eClass.getName());
159
					}
160
				}
161
			}
162
			Collections.sort(initialObjectNames, java.text.Collator.getInstance());
163
		}
164
		return initialObjectNames;
165
	}
166
167
	/**
168
	 * Create a new model.
91
	 * Create a new model.
169
	 * <!-- begin-user-doc -->
92
	 * <!-- begin-user-doc -->
170
	 * <!-- end-user-doc -->
93
	 * <!-- end-user-doc -->
171
	 * @generated
94
	 * @generated NOT
172
	 */
95
	 */
173
	protected EObject createInitialModel() {
96
	protected EObject createInitialModel() {
174
		EClass eClass = (EClass)gmfGenPackage.getEClassifier(initialObjectCreationPage.getInitialObjectName());
97
		return GMFGenPackage.eINSTANCE.getGMFGenFactory().createGenEditorGenerator();
175
		EObject rootObject = gmfGenFactory.create(eClass);
176
		return rootObject;
177
	}
98
	}
178
99
179
	/**
100
	/**
180
	 * Do the work after everything is specified.
101
	 * Do the work after everything is specified.
181
	 * <!-- begin-user-doc -->
102
	 * <!-- begin-user-doc -->
182
	 * <!-- end-user-doc -->
103
	 * <!-- end-user-doc -->
183
	 * @generated
104
	 * @generated NOT
184
	 */
105
	 */
185
	public boolean performFinish() {
106
	public boolean performFinish() {
186
		try {
107
		try {
187
			// Remember the file.
188
			//
189
			final IFile modelFile = getModelFile();
108
			final IFile modelFile = getModelFile();
190
109
			createModelFile(modelFile);
191
			// Do the work within an operation.
110
			return openEditor(modelFile);
192
			//
193
			WorkspaceModifyOperation operation =
194
				new WorkspaceModifyOperation() {
195
					protected void execute(IProgressMonitor progressMonitor) {
196
						try {
197
							// Create a resource set
198
							//
199
							ResourceSet resourceSet = new ResourceSetImpl();
200
201
							// Get the URI of the model file.
202
							//
203
							URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString());
204
205
							// Create a resource for this file.
206
							//
207
							Resource resource = resourceSet.createResource(fileURI);
208
209
							// Add the initial model object to the contents.
210
							//
211
							EObject rootObject = createInitialModel();
212
							if (rootObject != null) {
213
								resource.getContents().add(rootObject);
214
							}
215
216
							// Save the contents of the resource to the file system.
217
							//
218
							Map options = new HashMap();
219
							options.put(XMLResource.OPTION_ENCODING, initialObjectCreationPage.getEncoding());
220
							resource.save(options);
221
						}
222
						catch (Exception exception) {
223
							EditorPlugin.INSTANCE.log(exception);
224
						}
225
						finally {
226
							progressMonitor.done();
227
						}
228
					}
229
				};
230
231
			getContainer().run(false, false, operation);
232
233
			// Select the new file resource in the current view.
234
			//
235
			IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
236
			IWorkbenchPage page = workbenchWindow.getActivePage();
237
			final IWorkbenchPart activePart = page.getActivePart();
238
			if (activePart instanceof ISetSelectionTarget) {
239
				final ISelection targetSelection = new StructuredSelection(modelFile);
240
				getShell().getDisplay().asyncExec
241
					(new Runnable() {
242
						 public void run() {
243
							 ((ISetSelectionTarget)activePart).selectReveal(targetSelection);
244
						 }
245
					 });
246
			}
247
248
			// Open an editor on the new file.
249
			//
250
			try {
251
				page.openEditor
252
					(new FileEditorInput(modelFile),
253
					 workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId());
254
			}
255
			catch (PartInitException exception) {
256
				MessageDialog.openError(workbenchWindow.getShell(), EditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage());
257
				return false;
258
			}
259
260
			return true;
261
		}
111
		}
262
		catch (Exception exception) {
112
		catch (Exception exception) {
263
			EditorPlugin.INSTANCE.log(exception);
113
			EditorPlugin.INSTANCE.log(exception);
Lines 265-270 Link Here
265
		}
115
		}
266
	}
116
	}
267
117
118
	protected boolean openEditor(final IFile modelFile) {
119
		// Select the new file resource in the current view.
120
		//
121
		IWorkbenchWindow workbenchWindow = workbench.getActiveWorkbenchWindow();
122
		IWorkbenchPage page = workbenchWindow.getActivePage();
123
		final IWorkbenchPart activePart = page.getActivePart();
124
		if (activePart instanceof ISetSelectionTarget) {
125
			final ISelection targetSelection = new StructuredSelection(modelFile);
126
			getShell().getDisplay().asyncExec
127
				(new Runnable() {
128
					 public void run() {
129
						 ((ISetSelectionTarget)activePart).selectReveal(targetSelection);
130
					 }
131
				 });
132
		}
133
134
		// Open an editor on the new file.
135
		//
136
		try {
137
			page.openEditor
138
				(new FileEditorInput(modelFile),
139
				 workbench.getEditorRegistry().getDefaultEditor(modelFile.getFullPath().toString()).getId());
140
		}
141
		catch (PartInitException exception) {
142
			MessageDialog.openError(workbenchWindow.getShell(), EditorPlugin.INSTANCE.getString("_UI_OpenEditorError_label"), exception.getMessage());
143
			return false;
144
		}
145
146
		return true;
147
	}
148
149
	protected void createModelFile(final IFile modelFile) throws Exception {
150
		// Do the work within an operation.
151
		//
152
		WorkspaceModifyOperation operation =
153
			new WorkspaceModifyOperation() {
154
				protected void execute(IProgressMonitor progressMonitor) {
155
					try {
156
						// Create a resource set
157
						//
158
						ResourceSet resourceSet = new ResourceSetImpl();
159
160
						// Get the URI of the model file.
161
						//
162
						URI fileURI = URI.createPlatformResourceURI(modelFile.getFullPath().toString());
163
164
						// Create a resource for this file.
165
						//
166
						Resource resource = resourceSet.createResource(fileURI);
167
168
						// Add the initial model object to the contents.
169
						//
170
						EObject rootObject = createInitialModel();
171
						if (rootObject != null) {
172
							resource.getContents().add(rootObject);
173
						}
174
175
						// Save the contents of the resource to the file system.
176
						//
177
						Map options = new HashMap();
178
						options.put(XMLResource.OPTION_ENCODING, "UTF-8");
179
						resource.save(options);
180
					}
181
					catch (Exception exception) {
182
						EditorPlugin.INSTANCE.log(exception);
183
					}
184
					finally {
185
						progressMonitor.done();
186
					}
187
				}
188
			};
189
190
		getContainer().run(false, false, operation);
191
	}
192
268
	/**
193
	/**
269
	 * This is the one page of the wizard.
194
	 * This is the one page of the wizard.
270
	 * <!-- begin-user-doc -->
195
	 * <!-- begin-user-doc -->
Lines 318-532 Link Here
318
	}
243
	}
319
244
320
	/**
245
	/**
321
	 * This is the page where the type of object to create is selected.
322
	 * <!-- begin-user-doc -->
323
	 * <!-- end-user-doc -->
324
	 * @generated
325
	 */
326
	public class GMFGenModelWizardInitialObjectCreationPage extends WizardPage {
327
		/**
328
		 * <!-- begin-user-doc -->
329
		 * <!-- end-user-doc -->
330
		 * @generated
331
		 */
332
		protected Combo initialObjectField;
333
334
		/**
335
		 * @generated
336
		 * <!-- begin-user-doc -->
337
		 * <!-- end-user-doc -->
338
		 */
339
		protected List encodings;
340
341
		/**
342
		 * <!-- begin-user-doc -->
343
		 * <!-- end-user-doc -->
344
		 * @generated
345
		 */
346
		protected Combo encodingField;
347
348
		/**
349
		 * Pass in the selection.
350
		 * <!-- begin-user-doc -->
351
		 * <!-- end-user-doc -->
352
		 * @generated
353
		 */
354
		public GMFGenModelWizardInitialObjectCreationPage(String pageId) {
355
			super(pageId);
356
		}
357
358
		/**
359
		 * <!-- begin-user-doc -->
360
		 * <!-- end-user-doc -->
361
		 * @generated
362
		 */
363
		public void createControl(Composite parent) {
364
			Composite composite = new Composite(parent, SWT.NONE);
365
			{
366
				GridLayout layout = new GridLayout();
367
				layout.numColumns = 1;
368
				layout.verticalSpacing = 12;
369
				composite.setLayout(layout);
370
371
				GridData data = new GridData();
372
				data.verticalAlignment = GridData.FILL;
373
				data.grabExcessVerticalSpace = true;
374
				data.horizontalAlignment = GridData.FILL;
375
				composite.setLayoutData(data);
376
			}
377
378
			Label containerLabel = new Label(composite, SWT.LEFT);
379
			{
380
				containerLabel.setText(EditorPlugin.INSTANCE.getString("_UI_ModelObject"));
381
382
				GridData data = new GridData();
383
				data.horizontalAlignment = GridData.FILL;
384
				containerLabel.setLayoutData(data);
385
			}
386
387
			initialObjectField = new Combo(composite, SWT.BORDER);
388
			{
389
				GridData data = new GridData();
390
				data.horizontalAlignment = GridData.FILL;
391
				data.grabExcessHorizontalSpace = true;
392
				initialObjectField.setLayoutData(data);
393
			}
394
395
			for (Iterator i = getInitialObjectNames().iterator(); i.hasNext(); ) {
396
				initialObjectField.add(getLabel((String)i.next()));
397
			}
398
399
			if (initialObjectField.getItemCount() == 1) {
400
				initialObjectField.select(0);
401
			}
402
			initialObjectField.addModifyListener(validator);
403
404
			Label encodingLabel = new Label(composite, SWT.LEFT);
405
			{
406
				encodingLabel.setText(EditorPlugin.INSTANCE.getString("_UI_XMLEncoding"));
407
408
				GridData data = new GridData();
409
				data.horizontalAlignment = GridData.FILL;
410
				encodingLabel.setLayoutData(data);
411
			}
412
			encodingField = new Combo(composite, SWT.BORDER);
413
			{
414
				GridData data = new GridData();
415
				data.horizontalAlignment = GridData.FILL;
416
				data.grabExcessHorizontalSpace = true;
417
				encodingField.setLayoutData(data);
418
			}
419
420
			for (Iterator i = getEncodings().iterator(); i.hasNext(); ) {
421
				encodingField.add((String)i.next());
422
			}
423
424
			encodingField.select(0);
425
			encodingField.addModifyListener(validator);
426
427
			setPageComplete(validatePage());
428
			setControl(composite);
429
		}
430
431
		/**
432
		 * <!-- begin-user-doc -->
433
		 * <!-- end-user-doc -->
434
		 * @generated
435
		 */
436
		protected ModifyListener validator =
437
			new ModifyListener() {
438
				public void modifyText(ModifyEvent e) {
439
					setPageComplete(validatePage());
440
				}
441
			};
442
443
		/**
444
		 * <!-- begin-user-doc -->
445
		 * <!-- end-user-doc -->
446
		 * @generated
447
		 */
448
		protected boolean validatePage() {
449
			return getInitialObjectName() != null && getEncodings().contains(encodingField.getText());
450
		}
451
452
		/**
453
		 * <!-- begin-user-doc -->
454
		 * <!-- end-user-doc -->
455
		 * @generated
456
		 */
457
		public void setVisible(boolean visible) {
458
			super.setVisible(visible);
459
			if (visible) {
460
				if (initialObjectField.getItemCount() == 1) {
461
					initialObjectField.clearSelection();
462
					encodingField.setFocus();
463
				}
464
				else {
465
					encodingField.clearSelection();
466
					initialObjectField.setFocus();
467
				}
468
			}
469
		}
470
471
		/**
472
		 * <!-- begin-user-doc -->
473
		 * <!-- end-user-doc -->
474
		 * @generated
475
		 */
476
		public String getInitialObjectName() {
477
			String label = initialObjectField.getText();
478
479
			for (Iterator i = getInitialObjectNames().iterator(); i.hasNext(); ) {
480
				String name = (String)i.next();
481
				if (getLabel(name).equals(label)) {
482
					return name;
483
				}
484
			}
485
			return null;
486
		}
487
488
		/**
489
		 * <!-- begin-user-doc -->
490
		 * <!-- end-user-doc -->
491
		 * @generated
492
		 */
493
		public String getEncoding() {
494
			return encodingField.getText();
495
		}
496
497
		/**
498
		 * Returns the label for the specified type name.
499
		 * <!-- begin-user-doc -->
500
		 * <!-- end-user-doc -->
501
		 * @generated
502
		 */
503
		protected String getLabel(String typeName) {
504
			try {
505
				return EditorPlugin.INSTANCE.getString("_UI_" + typeName + "_type");
506
			}
507
			catch(MissingResourceException mre) {
508
				EditorPlugin.INSTANCE.log(mre);
509
			}
510
			return typeName;
511
		}
512
513
		/**
514
		 * <!-- begin-user-doc -->
515
		 * <!-- end-user-doc -->
516
		 * @generated
517
		 */
518
		protected Collection getEncodings() {
519
			if (encodings == null) {
520
				encodings = new ArrayList();
521
				for (StringTokenizer stringTokenizer = new StringTokenizer(EditorPlugin.INSTANCE.getString("_UI_XMLEncodingChoices")); stringTokenizer.hasMoreTokens(); ) {
522
					encodings.add(stringTokenizer.nextToken());
523
				}
524
			}
525
			return encodings;
526
		}
527
	}
528
529
	/**
530
	 * The framework calls this to create the contents of the wizard.
246
	 * The framework calls this to create the contents of the wizard.
531
	 * <!-- begin-user-doc -->
247
	 * <!-- begin-user-doc -->
532
	 * <!-- end-user-doc -->
248
	 * <!-- end-user-doc -->
Lines 574-583 Link Here
574
				}
290
				}
575
			}
291
			}
576
		}
292
		}
577
		initialObjectCreationPage = new GMFGenModelWizardInitialObjectCreationPage("Whatever2");
578
		initialObjectCreationPage.setTitle(EditorPlugin.INSTANCE.getString("_UI_GMFGenModelWizard_label"));
579
		initialObjectCreationPage.setDescription(EditorPlugin.INSTANCE.getString("_UI_Wizard_initial_object_description"));
580
		addPage(initialObjectCreationPage);
581
	}
293
	}
582
294
583
	/**
295
	/**
(-)plugin.xml (+21 lines)
Lines 67-70 Link Here
67
    </wizard>
67
    </wizard>
68
  </extension>
68
  </extension>
69
69
70
   <extension
71
         point="org.eclipse.ui.popupMenus">
72
      <objectContribution
73
            adaptable="true"
74
            id="gmf.codegen.ui.transformToGenModelFile"
75
            nameFilter="*.gmfmap"
76
            objectClass="org.eclipse.core.resources.IFile">
77
         <action
78
               class="org.eclipse.gmf.internal.bridge.transform.TransformToGenModelAction"
79
               enablesFor="1"
80
               id="gmf.bridge.ui.transformToGenModelFileActionExperimental"
81
               label="%transform.action.experimental"
82
               menubarPath="additions">
83
         </action>
84
      </objectContribution>
85
   </extension>
86
   <extension
87
         point="org.eclipse.core.runtime.preferences">
88
      <initializer class="org.eclipse.gmf.internal.bridge.transform.TransformOptions"/>
89
   </extension>
90
70
</plugin>
91
</plugin>
(-)plugin.properties (+2 lines)
Lines 31-33 Link Here
31
showDashboardPage.name=Show Dashboard
31
showDashboardPage.name=Show Dashboard
32
showDashboardPage.desc=Show dashboard view for the created project
32
showDashboardPage.desc=Show dashboard view for the created project
33
showDashboardPage.text=Show dashboard view for the created project
33
showDashboardPage.text=Show dashboard view for the created project
34
35
transform.action.experimental=Create generator model (experimental)...
(-)src/org/eclipse/gmf/internal/bridge/ui/Plugin.java (-1 / +25 lines)
Lines 59-64 Link Here
59
		return myContainmentClosure;
59
		return myContainmentClosure;
60
	}
60
	}
61
61
62
	public static IStatus createStatus(int statusCode, String message, Throwable ex) {
63
		return new Status(statusCode, getPluginID(), 0, message, ex);
64
	}
65
66
	public static IStatus createError(String message, Throwable ex) {
67
		return createStatus(IStatus.ERROR, message, ex);
68
	}
69
70
	public static IStatus createWarning(String message) {
71
		return createStatus(IStatus.WARNING, message, null);
72
	}
73
74
	public static IStatus createInfo(String message) {
75
		return createStatus(IStatus.INFO, message, null);
76
	}
77
78
	public static IStatus createCancel(String message) {
79
		return createStatus(IStatus.CANCEL, message, null);
80
	}
81
62
	public static Plugin getDefault() {
82
	public static Plugin getDefault() {
63
		return plugin;
83
		return plugin;
64
	}
84
	}
Lines 103-109 Link Here
103
		if (ex instanceof CoreException) {
123
		if (ex instanceof CoreException) {
104
			log((CoreException) ex);
124
			log((CoreException) ex);
105
		} else {
125
		} else {
106
			log(new Status(IStatus.ERROR, getPluginID(), 0, ex.getMessage(), ex));
126
			log(createError(ex.getMessage(), ex));
107
		}
127
		}
108
	}
128
	}
109
129
Lines 115-120 Link Here
115
		getDefault().getLog().log(s);
135
		getDefault().getLog().log(s);
116
	}
136
	}
117
137
138
	public static boolean needsReconcile() {
139
		return !Boolean.FALSE.toString().equals(Platform.getDebugOption(getPluginID() + "/reconcile"));
140
	}
141
118
	/**
142
	/**
119
	 * Returns an image descriptor for the image file at the given plug-in relative path.
143
	 * Returns an image descriptor for the image file at the given plug-in relative path.
120
	 * 
144
	 * 
(-)META-INF/MANIFEST.MF (-1 / +4 lines)
Lines 17-25 Link Here
17
 org.eclipse.gmf.graphdef.edit;bundle-version="[1.0.0,2.0.0)",
17
 org.eclipse.gmf.graphdef.edit;bundle-version="[1.0.0,2.0.0)",
18
 org.eclipse.gmf.tooldef.edit;bundle-version="[1.0.0,2.0.0)",
18
 org.eclipse.gmf.tooldef.edit;bundle-version="[1.0.0,2.0.0)",
19
 org.eclipse.gmf.map.edit;bundle-version="[1.0.0,2.0.0)",
19
 org.eclipse.gmf.map.edit;bundle-version="[1.0.0,2.0.0)",
20
 org.eclipse.emf.codegen.ecore.ui;bundle-version="[2.2.0,3.0.0)"
20
 org.eclipse.emf.codegen.ecore.ui;bundle-version="[2.2.0,3.0.0)",
21
 org.eclipse.gmf.codegen.edit,
22
 org.eclipse.emf.importer
21
Eclipse-LazyStart: true
23
Eclipse-LazyStart: true
22
Export-Package: org.eclipse.gmf.internal.bridge.resolver;x-internal:=true,
24
Export-Package: org.eclipse.gmf.internal.bridge.resolver;x-internal:=true,
25
 org.eclipse.gmf.internal.bridge.transform,
23
 org.eclipse.gmf.internal.bridge.ui;x-friends:="org.eclipse.gmf.bridge.ui.dashboard,org.eclipse.gmf.doc.ui",
26
 org.eclipse.gmf.internal.bridge.ui;x-friends:="org.eclipse.gmf.bridge.ui.dashboard,org.eclipse.gmf.doc.ui",
24
 org.eclipse.gmf.internal.bridge.wizards;x-friends:="org.eclipse.gmf.bridge.ui.dashboard,org.eclipse.gmf.doc.ui",
27
 org.eclipse.gmf.internal.bridge.wizards;x-friends:="org.eclipse.gmf.bridge.ui.dashboard,org.eclipse.gmf.doc.ui",
25
 org.eclipse.gmf.internal.bridge.wizards.pages;x-friends:="org.eclipse.gmf.doc.ui",
28
 org.eclipse.gmf.internal.bridge.wizards.pages;x-friends:="org.eclipse.gmf.doc.ui",
(-)src/org/eclipse/gmf/internal/bridge/transform/VisualIdentifierDispenserProvider.java (+61 lines)
Added Link Here
1
package org.eclipse.gmf.internal.bridge.transform;
2
3
import org.eclipse.core.runtime.Platform;
4
import org.eclipse.emf.common.util.URI;
5
import org.eclipse.gmf.internal.bridge.NaiveIdentifierDispenser;
6
import org.eclipse.gmf.internal.bridge.StatefulVisualIdentifierDispencer;
7
import org.eclipse.gmf.internal.bridge.VisualIdentifierDispenser;
8
import org.eclipse.gmf.internal.bridge.ui.Plugin;
9
import org.osgi.framework.Bundle;
10
11
/**
12
 * holds additional logic to pre/post process dispensers
13
 */
14
class VisualIdentifierDispenserProvider {
15
	private VisualIdentifierDispenser dispenser;
16
	private final URI myStateBaseURI;
17
18
	VisualIdentifierDispenserProvider(URI stateBaseURI) {
19
		myStateBaseURI = stateBaseURI;
20
	}
21
22
	private VisualIdentifierDispenser initialize() {
23
		Bundle tracePluginBundle = Platform.getBundle("org.eclipse.gmf.bridge.trace"); //$NON-NLS-1$
24
		if (tracePluginBundle != null) {
25
			try {
26
				Class despenserClass = tracePluginBundle.loadClass("org.eclipse.gmf.internal.bridge.trace.MergingIdentifierDispenser"); //$NON-NLS-1$
27
				return (VisualIdentifierDispenser) despenserClass.newInstance();
28
			} catch (ClassNotFoundException e) {
29
				Plugin.log(Plugin.createError(Messages.getString("VisualIdentifierDispenserProvider.error_not_found"), e)); //$NON-NLS-1$
30
			} catch (InstantiationException e) {
31
				Plugin.log(Plugin.createError(Messages.getString("VisualIdentifierDispenserProvider.error_instantiation"), e)); //$NON-NLS-1$
32
			} catch (IllegalAccessException e) {
33
				Plugin.log(Plugin.createError(Messages.getString("VisualIdentifierDispenserProvider.error_illegal_access"), e)); //$NON-NLS-1$
34
			} catch (ClassCastException ex) {
35
				Plugin.log(Plugin.createError(Messages.getString("VisualIdentifierDispenserProvider.error_instantiation"), ex)); //$NON-NLS-1$
36
			}
37
		}
38
		return new NaiveIdentifierDispenser();
39
	}
40
41
	public VisualIdentifierDispenser get() {
42
		assert dispenser != null;
43
		return dispenser;
44
	}
45
46
	public void acquire() {
47
		assert dispenser == null;
48
		dispenser = initialize();
49
		if (dispenser instanceof StatefulVisualIdentifierDispencer) {
50
			StatefulVisualIdentifierDispencer statefulDispencer = (StatefulVisualIdentifierDispencer) dispenser;
51
			statefulDispencer.loadState(myStateBaseURI);
52
		}
53
	}
54
55
	public void release() {
56
		if (dispenser instanceof StatefulVisualIdentifierDispencer) {
57
			((StatefulVisualIdentifierDispencer) dispenser).saveState();
58
		}
59
		dispenser = null;
60
	}
61
}
(-)src/org/eclipse/gmf/internal/bridge/transform/messages.properties (+38 lines)
Added Link Here
1
StaleGenModelDetector.warning_stale=Resource {0} is newer ({1,date}) than genmodel ({2,date})
2
GenModelDetector.error_cannot_find=Can't find genmodel
3
GenModelDetector.error_cannot_save=Can't save created genmodel
4
GenModelDetector.error_no_genmodelaccess=Need to apply GenModelAccess first
5
GenModelConfigurationPage.btn_new_model=New EMF Model ...
6
GenModelConfigurationPage.btn_default_model=Create Default ...
7
GenModelConfigurationPage.check_detect_stale=Detect stale Genmodel
8
GenModelConfigurationPage.btn_refresh=Refresh ...
9
VisualIdentifierDispenserProvider.error_not_found=MergingIdentifierDispenser was not found in org.eclipse.gmf.bridge.trace bundle
10
ViewmapProducerWizardPage.btn_use_runtime_figures=&Utilize enhanced features of GMF runtime
11
VisualIdentifierDispenserProvider.error_instantiation=MergingIdentifierDispenser was not instantiated
12
VisualIdentifierDispenserProvider.error_illegal_access=IllegalAccessException while instantiating MergingIdentifierDispenser
13
ValidationHelper.task_validating=Validating...
14
ValidationHelper.error_marker_creation=Marker creation failure
15
TransformToGenModelOperation.cancel_mapping_model_load=Mapping model loading was interrupted
16
TransformToGenModelOperation.task_loading=Loading ...
17
TransformToGenModelWizard.title_map_model=Select Mapping Model
18
TransformToGenModelWizard.descr_map_model=Load Mapping Model
19
TransformToGenModelWizard.title_gen_model=Select GenModel
20
TransformToGenModelWizard.descr_gen_model=Load GenModel or create new one
21
TransformToGenModelWizard.error_transform=Errors while creating generator model
22
TransformToGenModelWizard.cancel_transform=Operation cancelled
23
TransformToGenModelOperation.task_validating=Validating ...
24
TransformToGenModelOperation.error_invalid_mapping_model=Invalid Mapping Model
25
TransformToGenModelOperation.error_load_genmodel=Failed to load GenModel
26
TransformToGenModelOperation.task_generating=Generating ...
27
TransformToGenModelOperation.task_reconciling=Reconciling ...
28
TransformToGenModelOperation.task_saving=Saving ...
29
TransformToGenModelWizard.title_options=Specify transformation options
30
TransformToGenModelWizard.descr_options=Specify transformation options
31
TransformToGenModelWizard.title_wizard=Create generator model
32
ViewmapProducerWizardPage.btn_use_map_mode=Use &IMapMode
33
ViewmapProducerWizardPage.btn_create_rcp=Generate RCP Application
34
ViewmapProducerWizardPage.info_map_mode_for_lite=It is not recommended to use IMapMode for pure-GEF diagram editors
35
MapModelConfigurationPage.lbl_severity=Select the severity level for load problems to ignore:
36
MapModelConfigurationPage.lbl_info=Info
37
MapModelConfigurationPage.lbl_warning=Warning
38
MapModelConfigurationPage.lbl_error=Error
(-)src/org/eclipse/gmf/internal/bridge/transform/Messages.java (+33 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2007 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Alexander Fedorov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import java.util.MissingResourceException;
15
import java.util.ResourceBundle;
16
17
public class Messages {
18
19
	private static final String BUNDLE_NAME = "org.eclipse.gmf.internal.bridge.transform.messages"; //$NON-NLS-1$
20
21
	private static final ResourceBundle RESOURCE_BUNDLE = ResourceBundle.getBundle(BUNDLE_NAME);
22
23
	private Messages() {
24
	}
25
26
	public static String getString(String key) {
27
		try {
28
			return RESOURCE_BUNDLE.getString(key);
29
		} catch (MissingResourceException e) {
30
			return '!' + key + '!';
31
		}
32
	}
33
}
(-)src/org/eclipse/gmf/internal/bridge/transform/StaleGenModelDetector.java (+102 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Artem Tikhomirov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import java.text.MessageFormat;
15
import java.util.Date;
16
import java.util.HashSet;
17
import java.util.Iterator;
18
19
import org.eclipse.core.resources.IFile;
20
import org.eclipse.core.resources.ResourcesPlugin;
21
import org.eclipse.core.runtime.IPath;
22
import org.eclipse.core.runtime.IStatus;
23
import org.eclipse.core.runtime.Path;
24
import org.eclipse.core.runtime.Status;
25
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
26
import org.eclipse.emf.codegen.ecore.genmodel.GenPackage;
27
import org.eclipse.emf.common.util.URI;
28
import org.eclipse.gmf.internal.bridge.ui.Plugin;
29
30
/**
31
 * @author artem
32
 */
33
public class StaleGenModelDetector {
34
35
	private final GenModel myGenModel;
36
37
	public StaleGenModelDetector(GenModel genModel) {
38
		assert genModel != null;
39
		myGenModel = genModel;
40
	}
41
42
	/**
43
	 * Uses local time stamp to detect staleness, though would be better to use IResource#modificationStamp 
44
	 * to tell whether resource has changed or not  
45
	 * @return warning status if staleness detected, ok otherwise.
46
	 */
47
	public IStatus detect() {
48
		if (myGenModel.eResource() == null) {
49
			return Status.OK_STATUS;
50
		}
51
		URI genModelURI = myGenModel.eResource().getURI();
52
		if (!isFileURI(genModelURI)) {
53
			return Status.OK_STATUS;
54
		}
55
		HashSet<URI> ecoreURIs = new HashSet<URI>(); 
56
		for (Iterator it = myGenModel.getAllGenAndUsedGenPackagesWithClassifiers().iterator(); it.hasNext();) {
57
			GenPackage next = (GenPackage) it.next();
58
			if (next.getEcorePackage().eResource() != null) {
59
				final URI uri = next.getEcorePackage().eResource().getURI();
60
				if (isFileURI(uri)) {
61
					// check only file uris
62
					// though we don't check non-file uris, it's not bad to make sure at least  
63
					// files are up to date
64
					ecoreURIs.add(uri);
65
				}
66
			}
67
		}
68
		Date genModelTimeStamp = timestamp(genModelURI);
69
		for (URI uri : ecoreURIs) {
70
			Date ts = timestamp(uri);
71
			/* HACK
72
			 * @see ModelImporter#saveGenModelAndEPackages
73
			 * saves both ecore and genmodel files regardless of the fact .ecore was not modified,
74
			 * hence, we adjust the timestamp to avoid false stale detection
75
			 */
76
			if (new Date(genModelTimeStamp.getTime() + 3000).before(ts)) {
77
				String format = Messages.getString("StaleGenModelDetector.warning_stale"); //$NON-NLS-1$
78
				String msg = MessageFormat.format(format, uri, ts, genModelTimeStamp);
79
				return Plugin.createWarning(msg);
80
			}
81
		}
82
		return Status.OK_STATUS;
83
	}
84
85
	private static boolean isFileURI(URI uri) {
86
		return "platform".equals(uri.scheme()) && "resource".equals(uri.segment(0)); //$NON-NLS-1$ //$NON-NLS-2$
87
	}
88
89
	private static Date timestamp(URI uri) {
90
		IFile f = getFile(uri);
91
		if (!f.exists()) {
92
			return new Date(0);
93
		}
94
		return new Date(f.getLocalTimeStamp());
95
	}
96
97
	private static IFile getFile(URI platformFileUri) {
98
		IPath p = new Path(platformFileUri.path()).removeFirstSegments(1);
99
		return ResourcesPlugin.getWorkspace().getRoot().getFile(p);
100
	}
101
	
102
}
(-)src/org/eclipse/gmf/internal/bridge/transform/ViewmapProducerWizardPage.java (+133 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Alexander Fedorov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import org.eclipse.core.runtime.IStatus;
15
import org.eclipse.core.runtime.Status;
16
import org.eclipse.gmf.internal.bridge.ui.Plugin;
17
import org.eclipse.jface.dialogs.Dialog;
18
import org.eclipse.jface.dialogs.IMessageProvider;
19
import org.eclipse.jface.wizard.WizardPage;
20
import org.eclipse.swt.SWT;
21
import org.eclipse.swt.events.SelectionEvent;
22
import org.eclipse.swt.events.SelectionListener;
23
import org.eclipse.swt.layout.GridData;
24
import org.eclipse.swt.layout.GridLayout;
25
import org.eclipse.swt.widgets.Button;
26
import org.eclipse.swt.widgets.Composite;
27
import org.eclipse.swt.widgets.Widget;
28
29
/*
30
 * XXX: duplicates functionality of 
31
 * org.eclipse.gmf.internal.codegen.popup.actions.TransformToGenModelOptionsDialog 
32
 * and
33
 * org.eclipse.gmf.internal.graphdef.codegen.ui.FigureGeneratorOptionsDialog
34
 */
35
class ViewmapProducerWizardPage extends WizardPage {
36
	
37
    private Button generateRCPButton;
38
    private Button useMapModeButton;
39
    private Button useRuntimeFiguresButton;
40
41
	protected ViewmapProducerWizardPage(String pageName) {
42
		super(pageName);
43
	}
44
	
45
	public void createControl(Composite parent) {
46
		initializeDialogUnits(parent);
47
48
		Composite composite = new Composite(parent, SWT.NONE);
49
		composite.setLayout(new GridLayout());
50
		createControls(composite);
51
		initControls();
52
		validatePage();
53
54
		setControl(composite);
55
		Dialog.applyDialogFont(composite);
56
	}
57
58
	private void createControls(Composite result) {
59
        useMapModeButton = new Button(result, SWT.CHECK);
60
        useMapModeButton.setText(Messages.getString("ViewmapProducerWizardPage.btn_use_map_mode")); //$NON-NLS-1$
61
        useMapModeButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER));
62
        useRuntimeFiguresButton = new Button(result, SWT.CHECK);
63
        useRuntimeFiguresButton.setText(Messages.getString("ViewmapProducerWizardPage.btn_use_runtime_figures")); //$NON-NLS-1$
64
        useRuntimeFiguresButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER));
65
        generateRCPButton = new Button(result, SWT.CHECK);
66
        generateRCPButton.setText(Messages.getString("ViewmapProducerWizardPage.btn_create_rcp")); //$NON-NLS-1$
67
        generateRCPButton.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER));
68
        SelectionListener selectionListener = new SelectionListener() {
69
        	public void widgetDefaultSelected(SelectionEvent e) {
70
        		handleSelection(e.widget);
71
        	}
72
        	public void widgetSelected(SelectionEvent e) {
73
        		handleSelection(e.widget);
74
        	}
75
		};
76
        useMapModeButton.addSelectionListener(selectionListener);
77
        useRuntimeFiguresButton.addSelectionListener(selectionListener);
78
        generateRCPButton.addSelectionListener(selectionListener);
79
	}
80
81
	void handleSelection(Widget w) {
82
		if (generateRCPButton.equals(w)){
83
			getOperation().getOptions().setGenerateRCP(generateRCPButton.getSelection());
84
		} else if (useMapModeButton.equals(w)) {
85
			getOperation().getOptions().setUseMapMode(useMapModeButton.getSelection());
86
		} else if (useRuntimeFiguresButton.equals(w)) {
87
			getOperation().getOptions().setUseRuntimeFigures(useRuntimeFiguresButton.getSelection());
88
		}
89
		validatePage();
90
	}
91
	
92
	private void validatePage() {
93
		IStatus checkOptions = checkOptions();
94
		if (checkOptions.isOK()) {
95
			setMessage(null);
96
			setPageComplete(true);
97
		} else {
98
    		setMessage(checkOptions.getMessage(), IMessageProvider.INFORMATION);
99
			setPageComplete(checkOptions.getSeverity() < IStatus.WARNING);
100
		}
101
	}
102
	
103
	private IStatus checkOptions() {
104
		boolean hasLite = TransformOptions.checkLiteOptionPresent();
105
		if (hasLite) {
106
			if (!useRuntimeFiguresButton.getSelection() && useMapModeButton.getSelection()) {
107
				return Plugin.createInfo(Messages.getString("ViewmapProducerWizardPage.info_map_mode_for_lite")); //$NON-NLS-1$
108
			}
109
		}
110
		return Status.OK_STATUS;
111
	}
112
113
	private void initControls() {
114
		TransformOptions options = getOperation().getOptions();
115
		generateRCPButton.setSelection(options.getGenerateRCP());
116
		boolean hasLite = TransformOptions.checkLiteOptionPresent();
117
		boolean useRuntimeFigures = options.getUseRuntimeFigures();
118
		if (hasLite) {
119
			useRuntimeFiguresButton.setEnabled(true);
120
			useRuntimeFiguresButton.setSelection(useRuntimeFigures);
121
		} else {
122
			useRuntimeFiguresButton.setEnabled(false);
123
			useRuntimeFiguresButton.setSelection(true);
124
			options.setUseRuntimeFigures(true);
125
		}
126
		useMapModeButton.setSelection(options.getUseMapMode());
127
	}
128
129
	private TransformToGenModelOperation getOperation() {
130
		TransformToGenModelWizard wizard = (TransformToGenModelWizard) getWizard();
131
		return wizard.getTransformOperation();
132
	}
133
}
(-)src/org/eclipse/gmf/internal/bridge/transform/ValidationHelper.java (+397 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2006 Eclipse.org
3
 * 
4
 * All rights reserved. This program and the accompanying materials are made
5
 * available under the terms of the Eclipse Public License v1.0 which
6
 * accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 * 
9
 * Contributors: dvorak - initial API and implementation
10
 */
11
package org.eclipse.gmf.internal.bridge.transform;
12
13
import java.util.ArrayList;
14
import java.util.Collections;
15
import java.util.Iterator;
16
import java.util.LinkedHashMap;
17
import java.util.List;
18
import java.util.Map;
19
20
import org.eclipse.core.resources.IFile;
21
import org.eclipse.core.resources.IMarker;
22
import org.eclipse.core.resources.IResource;
23
import org.eclipse.core.runtime.CoreException;
24
import org.eclipse.core.runtime.IProgressMonitor;
25
import org.eclipse.core.runtime.IStatus;
26
import org.eclipse.core.runtime.NullProgressMonitor;
27
import org.eclipse.core.runtime.SubProgressMonitor;
28
import org.eclipse.emf.common.ui.MarkerHelper;
29
import org.eclipse.emf.common.util.BasicDiagnostic;
30
import org.eclipse.emf.common.util.Diagnostic;
31
import org.eclipse.emf.common.util.DiagnosticChain;
32
import org.eclipse.emf.common.util.URI;
33
import org.eclipse.emf.ecore.EClass;
34
import org.eclipse.emf.ecore.EObject;
35
import org.eclipse.emf.ecore.EValidator;
36
import org.eclipse.emf.ecore.resource.Resource;
37
import org.eclipse.emf.ecore.util.Diagnostician;
38
import org.eclipse.emf.ecore.util.EcoreUtil;
39
import org.eclipse.emf.edit.provider.ComposedAdapterFactory;
40
import org.eclipse.emf.edit.provider.IItemLabelProvider;
41
import org.eclipse.emf.edit.ui.util.EditUIMarkerHelper;
42
import org.eclipse.gmf.internal.bridge.ui.Plugin;
43
44
/**
45
 * Provides various functinality useful for model validation, for instances
46
 * progress monitoring, resource markers creation.
47
 */
48
public class ValidationHelper {
49
50
	/**
51
	 * Enhanced diagnostician class supporting progress monitoring and object
52
	 * labels.
53
	 */
54
	private static class SmartDiagnostician extends Diagnostician {
55
56
		private static ComposedAdapterFactory adapterFactory = new ComposedAdapterFactory(ComposedAdapterFactory.Descriptor.Registry.INSTANCE);
57
58
		private IProgressMonitor monitor;
59
60
		/**
61
		 * Constructs diagnostician with progress monitor.
62
		 * 
63
		 * @param progressMonitor
64
		 *            non-null progress monitor to track validation progress
65
		 */
66
		SmartDiagnostician(IProgressMonitor progressMonitor) {
67
			this.monitor = progressMonitor;
68
		}
69
70
		/*
71
		 * Utilizes the adapter factory registry to provide labels.
72
		 */
73
		@Override
74
		public String getObjectLabel(EObject eObject) {
75
			if (eObject != null) {
76
				IItemLabelProvider itemLabelProvider = (IItemLabelProvider) adapterFactory.adapt(eObject, IItemLabelProvider.class);
77
				if (itemLabelProvider != null) {
78
					return itemLabelProvider.getText(eObject);
79
				}
80
			} else {
81
				return ""; //$NON-NLS-1$
82
			}
83
			return super.getObjectLabel(eObject);
84
		}
85
86
		/*
87
		 * Notifies the monitor about the unit of work done.
88
		 */
89
		@Override
90
		public boolean validate(EClass eClass, EObject eObject, DiagnosticChain diagnostics, Map context) {
91
			if(monitor.isCanceled()) {
92
				return true;
93
			}
94
95
			monitor.worked(1);
96
			return super.validate(eClass, eObject, diagnostics, context);
97
		}
98
	}	
99
		
100
	/**
101
	 * Helper class for binding validation diagnostics to corresponding problem
102
	 * markers.
103
	 * <p>
104
	 * This class ensures that markers are managed for both {@link Diagnostic}}
105
	 * and {@link Resource.Diagnostic} diagnostic types.
106
	 */
107
	private static class GMFMarkerHelper extends EditUIMarkerHelper {
108
		
109
		private LinkedHashMap<Diagnostic, IMarker> diagnostic2Marker;
110
		private String markerID;
111
		
112
		/**
113
		 * Constructs marker helper with default markerID taken from its super-type.
114
		 */
115
		GMFMarkerHelper() {
116
			super();
117
		}
118
		
119
		/**
120
		 * Constructs marker helper with given marker ID.
121
		 * 
122
		 * @param markerID
123
		 *            string ID used as IMarker.TYPE.
124
		 *            <p>
125
		 *            If <code>null</code>, the default is
126
		 *            <code>resource-problem-marker</code> taken from
127
		 *            {@link MarkerHelper#getMarkerID()}
128
		 */
129
		GMFMarkerHelper(String markerID) {
130
			this.markerID = markerID;
131
		}
132
		
133
		public IFile getFileFromDiagnostic(Diagnostic diagnostic) {
134
			return getFile(diagnostic);
135
		}
136
		
137
		@Override
138
		protected void adjustMarker(IMarker marker, Diagnostic diagnostic, Diagnostic parentDiagnostic) throws CoreException {
139
			getDiagnostic2MarkerMap().put(diagnostic, marker);
140
141
			// adjust marker to support IGotoMarker for standard EMF generated editors 
142
			List data = diagnostic.getData();
143
			if (data != null && !data.isEmpty()) {
144
				Object target = data.get(0);
145
				if (target instanceof EObject) {
146
					marker.setAttribute(EValidator.URI_ATTRIBUTE, EcoreUtil.getURI((EObject) target).toString());
147
				}
148
			}
149
150
			super.adjustMarker(marker, diagnostic, parentDiagnostic);
151
		}
152
				
153
		@Override
154
		protected IFile getFile(Object datum) {
155
			if (datum instanceof EObject) {
156
				EObject eObject = (EObject) datum;
157
				if(eObject.eResource() != null) {
158
					URI uri = eObject.eResource().getURI();
159
					IFile file = getFile(uri);
160
					if(file != null) {
161
						return file;
162
					}
163
				}
164
			}
165
			return super.getFile(datum);
166
		}
167
		
168
		
169
		
170
		@Override
171
		protected String getMarkerID() {
172
			return markerID != null ? markerID : super.getMarkerID();
173
		}
174
175
		LinkedHashMap<Diagnostic, IMarker> getDiagnostic2MarkerMap() {
176
			if(diagnostic2Marker == null) {
177
				diagnostic2Marker = new LinkedHashMap<Diagnostic, IMarker>();
178
			}
179
			return diagnostic2Marker;
180
		}		
181
	}	
182
		
183
	/**
184
	 * Diagnostic to marker map data holder class.
185
	 * <p>
186
	 * Note: The map iterators respect the order of marker creation.
187
	 */
188
	public static class DiagnosticMarkerMap {
189
		private Map<Diagnostic, IMarker> map;
190
		
191
		/**
192
		 * Constraint diagnostic marker from the given map data.
193
		 * @param markerMap map data to be encapsulated by the resulting object.
194
		 */
195
		DiagnosticMarkerMap(LinkedHashMap<Diagnostic, IMarker> markerMap) {
196
			this.map = Collections.unmodifiableMap(markerMap);
197
		}
198
						
199
		/**
200
		 * Gets the map data for this diagnostic marker map.
201
		 * @return read-only map object
202
		 */
203
		public Map<Diagnostic, IMarker> getMap() {
204
			return map;
205
		}
206
	}	
207
	
208
	/**
209
	 * No instances, just an utility class.
210
	 */
211
	private ValidationHelper() {
212
		super();
213
	}
214
	
215
	
216
	/**
217
	 * Indicates whether the severiti of the given diagnostic matches the given 
218
	 * bitmask.<p>
219
	 * Note that a diagnostic with severity <code>OK</code> will never match; 
220
	 * use <code>isOK</code> instead to detect a diagnostic with a severity of <code>OK</code>.
221
	 *  
222
	 * @param diagnostic a diagnostic to test for severity match
223
	 * @param severityBitMask a mask formed by bitwise or'ing severity mask constants
224
	 * 	(<code>ERROR</code>, <code>WARNING</code>, <code>INFO</code>, <code>CANCEL</code>)
225
	 * 
226
	 * @return <code>true</code> if there is at least one match, <code>false</code> otherwise
227
	 * 
228
	 * @see Diagnostic#ERROR
229
	 * @see Diagnostic#WARNING
230
	 * @see Diagnostic#INFO
231
	 * @see Diagnostic#CANCEL   
232
	 */
233
    public static boolean matches(Diagnostic diagnostic, int severityBitMask) {
234
    	return (diagnostic.getSeverity() & severityBitMask) != 0;
235
    }
236
    
237
	/**
238
	 * Returns whether this diagnostic indicates everything is OK. (neither
239
	 * info, warning, nor error).
240
	 * 
241
	 * @return <code>true</code> if this diagnostic has severity
242
	 *         <code>OK</code>, and <code>false</code> otherwise
243
	 */    
244
    public static boolean isOK(Diagnostic diagnostic) {
245
    	return diagnostic.getSeverity() == Diagnostic.OK;
246
    }
247
248
    /**
249
	 * Validates the given <code>EObject</code> and its all contents.
250
	 * <p>
251
	 * If the EMF basic validation results in <code>Diagnostic.CANCEL</code>
252
	 * severity, no problem markers are created at all.
253
	 * 
254
	 * The problem markers created by this operation are added as extra-data to
255
	 * the returned diagnostic and are accessible via
256
	 * {@link #getDiagnosticMarkerMap(Diagnostic)}.
257
	 * 
258
	 * @param createMarkers
259
	 *            if <code>true</code> this operation produces validation
260
	 *            problems markers provided that eObject.eResource() represents
261
	 *            a file existing in the workspace. If <code>true</code> no
262
	 *            attempt to create markers is performed.
263
	 * 
264
	 * @param progressMonitor
265
	 *            the progress monitor to track validation progress, or
266
	 *            <code>null</code> if no progress monitoring is required.
267
	 *            The implementation creates {@link SubProgressMonitor} as
268
	 *            a sub-task of the given parent <code>progressMonitor</code> 
269
	 *            allocating 1 tick from the parent. #beginTask and #done operation 
270
	 *            on the subprogress monitor is called.
271
	 * 
272
	 * @return the validation result diagnostic
273
	 */
274
	public static Diagnostic validate(EObject eObject, boolean createMarkers, IProgressMonitor progressMonitor) {		
275
		IProgressMonitor monitor = null;
276
		try {			
277
			int count = IProgressMonitor.UNKNOWN;
278
			if(progressMonitor != null) {
279
				for (Iterator i = eObject.eAllContents(); i.hasNext(); i.next()) {
280
					++count;
281
				}
282
			}
283
284
			monitor = (progressMonitor != null) ? new SubProgressMonitor(progressMonitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK) : new NullProgressMonitor(); 
285
		    monitor.beginTask("", count); //$NON-NLS-1$
286
		    monitor.subTask(Messages.getString("ValidationHelper.task_validating")); //$NON-NLS-1$
287
			
288
		    Diagnostic validationStatus = new SmartDiagnostician(monitor).validate(eObject);
289
			if(validationStatus.getSeverity() == Diagnostic.CANCEL) {
290
				return validationStatus;
291
			}
292
				
293
			if(createMarkers) {
294
				return createMarkers(validationStatus, EValidator.MARKER);
295
			}
296
			
297
			return validationStatus;
298
			
299
		} finally {
300
			monitor.done();
301
		} 
302
	}
303
	
304
    /**
305
	 * Validates the given <code>EObject</code> and its all contents.
306
	 * <p>
307
	 * This method is progress monitoring ignorant shorthand of {@link #validate(EObject, boolean, IProgressMonitor)}
308
	 * 
309
	 * @param createMarkers
310
	 *            if <code>true</code> this operation produces validation
311
	 *            problems markers provided that eObject.eResource() represents
312
	 *            a file existing in the workspace. If <code>true</code> no
313
	 *            attempt to create markers is performed.
314
	 * 
315
	 * @return the validation result diagnostic
316
	 * 
317
	 * @see #validate(EObject, boolean, IProgressMonitor)
318
	 */	
319
	public static Diagnostic validate(EObject eObject, boolean createMarkers) {
320
		return validate(eObject, createMarkers, null);
321
	}
322
	
323
	/**
324
	 * Gets the diagnostic marker map associated with the given validation
325
	 * diagnostic.
326
	 * 
327
	 * @param diagnostic
328
	 *            a non-null validation diagnostic which resulted from calling
329
	 *            {@link #validate(EObject, boolean, IProgressMonitor)}}
330
	 * 
331
	 * @see #validate(EObject, boolean, IProgressMonitor)
332
	 */
333
	public static DiagnosticMarkerMap getDiagnosticMarkerMap(Diagnostic diagnostic) {
334
		List data = (diagnostic.getData() != null) ? diagnostic.getData() : Collections.EMPTY_LIST;
335
		for (Iterator it = data.iterator(); it.hasNext();) {
336
			Object dataItem = it.next();
337
			if (dataItem instanceof DiagnosticMarkerMap) {
338
				return (DiagnosticMarkerMap) dataItem;
339
			}			
340
		}
341
		return null;
342
	}
343
344
	/**
345
	 * Extracts the file of the validated model instance referenced by the given
346
	 * diagnostic.
347
	 * 
348
	 * @param diagnostic
349
	 *            a non-null validation diagnostic
350
	 * @return the file object or <code>null</code> in case the resource
351
	 *         associated with the validated object does not represents a file
352
	 *         existing in the workspace.
353
	 */
354
	public static IFile getFileFromDiagnostic(Diagnostic diagnostic) {
355
		return new GMFMarkerHelper(EValidator.MARKER).getFileFromDiagnostic(diagnostic);
356
	}
357
	
358
	/**
359
	 * Creates resource problem markers {@link Resource.Diagnostic} encapsualted
360
	 * in the given diagnostic object.
361
	 * 
362
	 * @param diagnostic
363
	 *            non-null diagnostic eventually containing a hiearchy of
364
	 *            diagnostics for which markers are to be created.
365
	 * 
366
	 * @see #getDiagnosticMarkerMap(Diagnostic)
367
	 * @see Resource.Diagnostic
368
	 */
369
	public static Diagnostic createResourceProblemMarkers(Diagnostic diagnostic) {
370
		return createMarkers(diagnostic, null /* resource problem markers*/);
371
	}	
372
	
373
	private static Diagnostic createMarkers(Diagnostic diagnostic, String markerID) {
374
		GMFMarkerHelper markerHelper = new GMFMarkerHelper(markerID);
375
		try {
376
			markerHelper.deleteMarkers(diagnostic, false, IResource.DEPTH_ZERO);
377
			if(!diagnostic.getChildren().isEmpty() && !isOK(diagnostic)) {
378
				markerHelper.createMarkers(diagnostic);
379
			}
380
		} catch (CoreException e) {
381
			IStatus status = Plugin.createError(Messages.getString("ValidationHelper.error_marker_creation"), e); //$NON-NLS-1$
382
			Plugin.log(status);
383
		}
384
		DiagnosticMarkerMap markerMap = new DiagnosticMarkerMap(markerHelper.getDiagnostic2MarkerMap());
385
		
386
		List<Object> data = diagnostic.getData() != null ? (List<Object>)diagnostic.getData() : Collections.emptyList();			
387
		data = new ArrayList<Object>(data);
388
		data.add(markerMap);
389
		
390
		BasicDiagnostic result = new BasicDiagnostic(
391
				diagnostic.getSource(), diagnostic.getCode(),
392
				diagnostic.getMessage(), data.toArray());
393
394
		result.addAll(diagnostic);
395
		return result;
396
	}	
397
}
(-)src/org/eclipse/gmf/internal/bridge/transform/GenModelConfigurationPage.java (+243 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Alexander Fedorov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import org.eclipse.core.resources.IContainer;
15
import org.eclipse.core.resources.IFile;
16
import org.eclipse.core.resources.ResourcesPlugin;
17
import org.eclipse.core.runtime.CoreException;
18
import org.eclipse.core.runtime.IPath;
19
import org.eclipse.core.runtime.IProgressMonitor;
20
import org.eclipse.core.runtime.Path;
21
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
22
import org.eclipse.emf.common.util.URI;
23
import org.eclipse.emf.ecore.resource.Resource;
24
import org.eclipse.emf.ecore.resource.ResourceSet;
25
import org.eclipse.emf.importer.ui.EMFModelWizard;
26
import org.eclipse.emf.importer.ui.GenModelReloadActionDelegate;
27
import org.eclipse.gmf.internal.common.URIUtil;
28
import org.eclipse.gmf.internal.common.ui.ResourceLocationProvider;
29
import org.eclipse.jface.action.Action;
30
import org.eclipse.jface.action.IAction;
31
import org.eclipse.jface.viewers.StructuredSelection;
32
import org.eclipse.jface.window.Window;
33
import org.eclipse.jface.wizard.WizardDialog;
34
import org.eclipse.swt.SWT;
35
import org.eclipse.swt.events.SelectionAdapter;
36
import org.eclipse.swt.events.SelectionEvent;
37
import org.eclipse.swt.layout.GridData;
38
import org.eclipse.swt.layout.GridLayout;
39
import org.eclipse.swt.widgets.Button;
40
import org.eclipse.swt.widgets.Composite;
41
import org.eclipse.swt.widgets.Shell;
42
import org.eclipse.swt.widgets.Widget;
43
import org.eclipse.ui.PlatformUI;
44
45
46
class GenModelConfigurationPage extends ModelConfigurationPage {
47
	
48
	private static final String FILE_EXT_ECORE = "ecore"; //$NON-NLS-1$
49
	private static final String FILE_EXT_GENMODEL = "genmodel"; //$NON-NLS-1$
50
51
	private Button createWizardBtn;
52
	private Button createDefaultBtn;
53
	private Button detectStaleBtn;
54
	private Button refreshStaleBtn;
55
	
56
	GenModelConfigurationPage(String pageId, ResourceLocationProvider rlp, ResourceSet resourceSet) {
57
		super(pageId, rlp, resourceSet);
58
	}
59
	
60
	protected String getModelFileExtension() {
61
		return FILE_EXT_GENMODEL;
62
	}
63
	
64
	@Override
65
	protected void createAdditionalControls(Composite parent) {
66
		Composite createComposite = new Composite(parent, SWT.NONE);
67
		createComposite.setLayout(new GridLayout(2, true));
68
		createComposite.setLayoutData(createGridData());
69
70
		createWizardBtn = new Button(createComposite, SWT.PUSH);
71
		createWizardBtn.setText(Messages.getString("GenModelConfigurationPage.btn_new_model")); //$NON-NLS-1$
72
		createWizardBtn.setLayoutData(new GridData());
73
74
		createDefaultBtn = new Button(createComposite, SWT.PUSH);
75
		createDefaultBtn.setText(Messages.getString("GenModelConfigurationPage.btn_default_model")); //$NON-NLS-1$
76
		createDefaultBtn.setLayoutData(new GridData());
77
78
		Composite staleComposite = new Composite(parent, SWT.NONE);
79
		staleComposite.setLayout(new GridLayout());
80
		staleComposite.setLayoutData(createGridData());
81
82
		detectStaleBtn = new Button(staleComposite, SWT.CHECK);
83
		detectStaleBtn.setText(Messages.getString("GenModelConfigurationPage.check_detect_stale")); //$NON-NLS-1$
84
		detectStaleBtn.setLayoutData(new GridData());
85
86
		refreshStaleBtn = new Button(staleComposite, SWT.PUSH);
87
		refreshStaleBtn.setText(Messages.getString("GenModelConfigurationPage.btn_refresh")); //$NON-NLS-1$
88
		refreshStaleBtn.setLayoutData(new GridData());
89
90
		SelectionAdapter selectionAdapter = new SelectionAdapter() {
91
			@Override
92
			public void widgetSelected(SelectionEvent e) {
93
				handleSelection(e.widget);
94
			}
95
		};
96
		createWizardBtn.addSelectionListener(selectionAdapter);
97
		createDefaultBtn.addSelectionListener(selectionAdapter);
98
		detectStaleBtn.addSelectionListener(selectionAdapter);
99
		refreshStaleBtn.addSelectionListener(selectionAdapter);
100
	}
101
102
	private GridData createGridData() {
103
		GridData gd = new GridData();
104
		gd.horizontalAlignment = GridData.FILL;
105
		gd.grabExcessHorizontalSpace = true;
106
		return gd;
107
	}
108
	
109
	void handleSelection(Widget w) {
110
		if (createDefaultBtn.equals(w)){
111
			createDefault();
112
		} else if (createWizardBtn.equals(w)) {
113
			launchWizard();
114
		} else if (detectStaleBtn.equals(w)) {
115
			handleDetect(detectStaleBtn.getSelection());
116
		} else if (refreshStaleBtn.equals(w)) {
117
			refreshGenmodel();
118
		}
119
	}
120
121
	@Override
122
	protected void initControls() {
123
		super.initControls();
124
		if (getURI() == null) {
125
			findGenmodel();
126
		} else {
127
			updateControls();
128
		}
129
	}
130
	
131
	void findGenmodel() {
132
		try {
133
			GenModel genModel = getOperation().findGenmodel(getResourceSet());
134
			Resource r = genModel.eResource();
135
			URI genURI = r.getURI();
136
			setURI(genURI);
137
			updateURI();
138
		} catch (CoreException e) {
139
			setErrorMessage(e.getMessage());
140
			updateControls();
141
		}
142
	}
143
144
	/* (non-Javadoc)
145
	 * @see org.eclipse.gmf.internal.common.ui.ModelSelectionPage#resourceChanged()
146
	 */
147
	@Override
148
	protected void resourceChanged() {
149
		super.resourceChanged();
150
		updateControls();
151
	}
152
153
	private void updateControls() {
154
		GenModelDetector gmd = getOperation().getGenModelDetector();
155
		if (gmd!= null) {
156
			createDefaultBtn.setEnabled(gmd.canCreateDefault());
157
		}
158
		boolean detectStale = getOperation().getOptions().getDetectStaleGenmodel();
159
		detectStaleBtn.setSelection(detectStale);
160
		detectStaleBtn.setEnabled(getURI() != null);
161
		refreshStaleBtn.setEnabled(detectStaleBtn.isEnabled() && detectStale);
162
	}
163
164
	@Override
165
	protected Resource doLoadResource(IProgressMonitor monitor) throws CoreException {
166
		GenModel genModel = getOperation().loadGenModel(getResourceSet(), getURI(), monitor);
167
		return genModel.eResource();
168
	}
169
170
	private void createDefault() {
171
		try {
172
			TransformToGenModelOperation to = getOperation();
173
			GenModelDetector gmd = to.getGenModelDetector();
174
			URI mapURI = to.getMapURI();
175
			IFile mapFile = URIUtil.getFile(mapURI);
176
			String pluginID = mapFile.getProject().getName();
177
			IFile genmodel = gmd.createDefault(pluginID, mapFile);
178
			URI genURI = URI.createPlatformResourceURI(genmodel.getFullPath().toString(), true);
179
			setURI(genURI);
180
			updateURI();
181
		} catch (CoreException e) {
182
			setErrorMessage(e.getMessage());
183
		}
184
	}
185
	
186
	private void launchWizard() {
187
		URI mapURI = getOperation().getMapURI();
188
		IFile mapFile = URIUtil.getFile(mapURI);
189
		IFile genmodel = createWithWizard(getShell(), mapFile);
190
		if (genmodel != null) {
191
			setURI(URI.createPlatformResourceURI(genmodel.getFullPath().toString(), true));
192
			updateURI();
193
		}
194
	}
195
	
196
	private static IFile createWithWizard(Shell shell, IFile patternResource) {
197
		final IFile[] result = new IFile[1];
198
		EMFModelWizard wizard = new EMFModelWizard() {
199
			@Override
200
			public boolean performFinish() {
201
				result[0] = ResourcesPlugin.getWorkspace().getRoot().getFile(genModelContainerPath.append(genModelFileName));
202
				return super.performFinish();
203
			}
204
		};
205
		wizard.init(PlatformUI.getWorkbench(), createSelectionForEMFWizard(patternResource));
206
		if (Window.OK == new WizardDialog(shell, wizard).open()) {
207
			assert result[0] != null;
208
			return result[0];
209
		}
210
		return null;
211
	}
212
	private static StructuredSelection createSelectionForEMFWizard(IFile patternResource) {
213
		final IContainer parent = patternResource.getParent();
214
		IFile neighbour = parent.getFile(new Path(patternResource.getName()).removeFileExtension().addFileExtension(FILE_EXT_ECORE));
215
		if (neighbour.exists()) {
216
			return new StructuredSelection(neighbour);
217
		} else {
218
			return new StructuredSelection(patternResource);
219
		}
220
	}
221
222
	private void handleDetect(boolean selection) {
223
		getOperation().getOptions().setDetectStaleGenmodel(selection);
224
		updateControls();
225
	}
226
227
	private void refreshGenmodel() {
228
		IPath p = new Path(getURI().path()).removeFirstSegments(1);
229
		IFile genModelFile = ResourcesPlugin.getWorkspace().getRoot().getFile(p);
230
		GenModelReloadActionDelegate action = new GenModelReloadActionDelegate();
231
		IAction uiAction = new Action() {
232
			//empty
233
		};
234
		action.selectionChanged(uiAction, new StructuredSelection(genModelFile));
235
		action.run(uiAction);
236
		updateURI();
237
	}
238
239
	private TransformToGenModelOperation getOperation() {
240
		TransformToGenModelWizard wizard = (TransformToGenModelWizard) getWizard();
241
		return wizard.getTransformOperation();
242
	}
243
}
(-).settings/org.eclipse.core.resources.prefs (+3 lines)
Added Link Here
1
#Thu Jan 11 19:33:31 MSK 2007
2
eclipse.preferences.version=1
3
encoding//src/org/eclipse/gmf/internal/bridge/transform/messages.properties=8859_1
(-)src/org/eclipse/gmf/internal/bridge/transform/GenModelDetector.java (+154 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Artem Tikhomirov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import java.io.IOException;
15
import java.util.Collection;
16
import java.util.HashSet;
17
import java.util.Iterator;
18
19
import org.eclipse.core.resources.IFile;
20
import org.eclipse.core.resources.ResourcesPlugin;
21
import org.eclipse.core.runtime.CoreException;
22
import org.eclipse.core.runtime.IPath;
23
import org.eclipse.core.runtime.IStatus;
24
import org.eclipse.core.runtime.Status;
25
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
26
import org.eclipse.emf.common.util.URI;
27
import org.eclipse.emf.ecore.EClass;
28
import org.eclipse.emf.ecore.EPackage;
29
import org.eclipse.emf.ecore.resource.Resource;
30
import org.eclipse.emf.ecore.resource.ResourceSet;
31
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
32
import org.eclipse.emf.ecore.util.EcoreUtil;
33
import org.eclipse.gmf.internal.bridge.genmodel.BasicGenModelAccess;
34
import org.eclipse.gmf.internal.bridge.genmodel.DummyGenModel;
35
import org.eclipse.gmf.internal.bridge.genmodel.FileGenModelAccess;
36
import org.eclipse.gmf.internal.bridge.genmodel.GenModelAccess;
37
import org.eclipse.gmf.internal.bridge.ui.Plugin;
38
import org.eclipse.gmf.mappings.Mapping;
39
40
/**
41
 * Interact with user to retrieve genmodel for the domain model. XXX detect
42
 * stale genmodels and reconcile them based on user's decision
43
 * 
44
 * @author artem
45
 */
46
public class GenModelDetector {
47
	private final Mapping myMapping;
48
	private GenModelAccess myGMAccess;
49
	private Collection<EPackage> myPackages;
50
51
	public GenModelDetector(Mapping mapping) {
52
		assert mapping != null;
53
		myMapping = mapping;
54
	}
55
	
56
	public IStatus detect() {
57
		myPackages = findEPackages(myMapping);
58
		if (myPackages.isEmpty()) {
59
			myGMAccess = new GenModelAccess.Adapter(null);
60
			return Status.OK_STATUS;
61
		} else if (myPackages.size() == 1) {
62
			final EPackage solePack = myPackages.iterator().next();
63
			BasicGenModelAccess gma = new BasicGenModelAccess(solePack);
64
			gma.initDefault();
65
			return apply(gma);
66
		} else {
67
			return Plugin.createError(Messages.getString("GenModelDetector.error_cannot_find"), null); //$NON-NLS-1$
68
		}
69
	}
70
71
	public IStatus advise(URI genModelURI) {
72
		assert genModelURI != null;
73
		GenModelAccess gma = new FileGenModelAccess(genModelURI);
74
		return apply(gma);
75
	}
76
77
	public IStatus advise(IFile workspaceFile) {
78
		assert workspaceFile != null;
79
		GenModelAccess gma = new FileGenModelAccess(workspaceFile);
80
		return apply(gma);
81
	}
82
	
83
	private Collection<EPackage> findEPackages(Mapping mapping) {
84
		Collection<EPackage> packages = new HashSet<EPackage>();
85
		for (Iterator it = EcoreUtil.ExternalCrossReferencer.find(mapping).keySet().iterator(); it.hasNext();) {
86
			Object next = it.next();
87
			if (next instanceof EClass) {
88
				packages.add(((EClass) next).getEPackage());
89
			}
90
		}
91
		for (Iterator it = packages.iterator(); it.hasNext();) {
92
			EPackage next = (EPackage) it.next();
93
			if (next.getESuperPackage() != null && EcoreUtil.isAncestor(packages, next.getESuperPackage())) {
94
				it.remove();
95
			}
96
		}
97
		return packages;
98
	}
99
100
	private IStatus apply(GenModelAccess gma) {
101
		IStatus load = gma.load(new ResourceSetImpl());
102
		if (load.isOK()) {
103
			gma.unload();
104
			myGMAccess = gma;
105
			return Status.OK_STATUS;
106
		} else {
107
			return load;
108
		}
109
	}
110
	
111
	private EPackage getPrimaryPackage() {
112
		if (myPackages == null || myPackages.size() == 0) {
113
			return null;
114
		}
115
		return myPackages.iterator().next();
116
	}
117
	
118
	public boolean canCreateDefault() {
119
		return myPackages != null && myPackages.size() == 1;
120
	}
121
	
122
	public IFile createDefault(String pluginID, IFile patternResource) throws CoreException {
123
		DummyGenModel gma = new DummyGenModel(getPrimaryPackage(), null);
124
		gma.setPluginID(pluginID);
125
		GenModel model = gma.create();
126
		IPath path = patternResource.getFullPath().removeFileExtension().addFileExtension("genmodel"); //$NON-NLS-1$
127
		Resource res = new ResourceSetImpl().createResource(URI.createPlatformResourceURI(path.toString(), true));
128
		res.getContents().add(model);
129
		try {
130
			res.save(null);
131
			IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(path);
132
			return file;
133
		} catch (IOException ex) {
134
			IStatus error = Plugin.createError(Messages.getString("GenModelDetector.error_cannot_save"), ex); //$NON-NLS-1$
135
			throw new CoreException(error);
136
		}
137
	}
138
139
	public GenModel get(ResourceSet resSet) {
140
		if (myGMAccess == null) {
141
			throw new IllegalStateException(Messages.getString("GenModelDetector.error_no_genmodelaccess")); //$NON-NLS-1$
142
		}
143
		IStatus s = myGMAccess.load(resSet);
144
		if (!s.isOK()) {
145
			throw new IllegalStateException(s.getMessage());
146
		}
147
		return myGMAccess.model();
148
	}
149
	
150
	public boolean checkState() {
151
		return myGMAccess != null;
152
	}
153
154
}
(-)src/org/eclipse/gmf/internal/bridge/transform/MapModelConfigurationPage.java (+99 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Alexander Fedorov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import org.eclipse.core.resources.IFile;
15
import org.eclipse.core.runtime.CoreException;
16
import org.eclipse.core.runtime.IProgressMonitor;
17
import org.eclipse.emf.common.util.URI;
18
import org.eclipse.emf.ecore.resource.Resource;
19
import org.eclipse.emf.ecore.resource.ResourceSet;
20
import org.eclipse.gmf.internal.common.ui.ResourceLocationProvider;
21
import org.eclipse.gmf.mappings.Mapping;
22
import org.eclipse.jface.resource.JFaceResources;
23
import org.eclipse.swt.SWT;
24
import org.eclipse.swt.events.SelectionAdapter;
25
import org.eclipse.swt.events.SelectionEvent;
26
import org.eclipse.swt.events.SelectionListener;
27
import org.eclipse.swt.layout.GridData;
28
import org.eclipse.swt.layout.GridLayout;
29
import org.eclipse.swt.widgets.Combo;
30
import org.eclipse.swt.widgets.Composite;
31
import org.eclipse.swt.widgets.Label;
32
import org.eclipse.swt.widgets.Widget;
33
34
35
class MapModelConfigurationPage extends ModelConfigurationPage {
36
	
37
	private static final String FILE_EXT_GMFMAP = "gmfmap"; //$NON-NLS-1$
38
39
	private Combo loadProblemsLevel;
40
	
41
	MapModelConfigurationPage(String pageId, ResourceLocationProvider rlp, ResourceSet resourceSet) {
42
		super(pageId, rlp, resourceSet);
43
	}
44
45
	protected String getModelFileExtension() {
46
		return FILE_EXT_GMFMAP;
47
	}
48
	
49
	@Override
50
	protected void createAdditionalControls(Composite parent) {
51
		super.createAdditionalControls(parent);
52
		Composite group = new Composite(parent, SWT.NONE);
53
		group.setLayout(new GridLayout(2, false));
54
		group.setLayoutData(new GridData(GridData.HORIZONTAL_ALIGN_BEGINNING | GridData.VERTICAL_ALIGN_CENTER));
55
		Label labelControl= new Label(group, SWT.LEFT);
56
		labelControl.setFont(JFaceResources.getDialogFont());
57
		labelControl.setText(Messages.getString("MapModelConfigurationPage.lbl_severity")); //$NON-NLS-1$
58
		loadProblemsLevel = new Combo(group, SWT.READ_ONLY);
59
		String[] items = new String[]{Messages.getString("MapModelConfigurationPage.lbl_info"), Messages.getString("MapModelConfigurationPage.lbl_warning"), Messages.getString("MapModelConfigurationPage.lbl_error")}; //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
60
		loadProblemsLevel.setItems(items);
61
		loadProblemsLevel.setFont(JFaceResources.getDialogFont());
62
63
		SelectionListener selectionListener = new SelectionAdapter() {
64
        	public void widgetSelected(SelectionEvent e) {
65
        		handleSelection(e.widget);
66
        	}
67
		};
68
		loadProblemsLevel.addSelectionListener(selectionListener);
69
	}
70
	
71
	void handleSelection(Widget w) {
72
		if (loadProblemsLevel.equals(w)){
73
			getOperation().getOptions().setMapdefLoadLevel(loadProblemsLevel.getSelectionIndex());
74
		} 
75
	}
76
	
77
	@Override
78
	protected void initControls() {
79
		super.initControls();
80
		TransformToGenModelWizard wizard = (TransformToGenModelWizard) getWizard();
81
		IFile target = wizard.getTargetFile();
82
		getOperation().setGenURI(URI.createPlatformResourceURI(target.getFullPath().toString(), true));
83
		TransformOptions o = getOperation().getOptions();
84
		loadProblemsLevel.select(o.getMapdefLoadLevel());
85
	}
86
	
87
	@Override
88
	protected Resource doLoadResource(IProgressMonitor monitor) throws CoreException {
89
		TransformToGenModelOperation o = getOperation();
90
		o.reset(getURI());
91
		Mapping mapping = o.loadMappingModel(getResourceSet(), getURI(), monitor);
92
		return mapping.eResource();
93
	}
94
95
	TransformToGenModelOperation getOperation() {
96
		TransformToGenModelWizard wizard = (TransformToGenModelWizard) getWizard();
97
		return wizard.getTransformOperation();
98
	}
99
}
(-)src/org/eclipse/gmf/internal/bridge/transform/GMFGenConfig.java (+152 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Michael Golubev (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import org.eclipse.emf.ecore.EAttribute;
15
import org.eclipse.emf.ecore.EClass;
16
import org.eclipse.emf.ecore.EObject;
17
import org.eclipse.gmf.codegen.gmfgen.GMFGenPackage;
18
import org.eclipse.gmf.codegen.gmfgen.GenChildContainer;
19
import org.eclipse.gmf.codegen.gmfgen.GenNode;
20
import org.eclipse.gmf.internal.common.reconcile.Copier;
21
import org.eclipse.gmf.internal.common.reconcile.DefaultDecisionMaker;
22
import org.eclipse.gmf.internal.common.reconcile.Matcher;
23
import org.eclipse.gmf.internal.common.reconcile.ReconcilerConfigBase;
24
import org.eclipse.gmf.internal.common.reconcile.ReflectiveMatcher;
25
import org.eclipse.gmf.internal.common.reconcile.StringPatternDecisionMaker;
26
27
/**
28
 * XXX Perhaps, org.eclipse.gmf.codegen/oeg.internal.util would be better place for this class. 
29
 */
30
public class GMFGenConfig extends ReconcilerConfigBase {
31
	private final GMFGenPackage GMFGEN = GMFGenPackage.eINSTANCE;
32
	
33
	public GMFGenConfig(){
34
		setMatcher(GMFGEN.getGenEditorGenerator(), ALWAYS_MATCH);
35
		preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_CopyrightText());
36
		preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_PackageNamePrefix());
37
		preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_DomainFileExtension());
38
		preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_DiagramFileExtension());
39
		preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_SameFileForDiagramAndModel());
40
		preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_ModelID());
41
		preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_DynamicTemplates());
42
		preserveIfSet(GMFGEN.getGenEditorGenerator(), GMFGEN.getGenEditorGenerator_TemplateDirectory());
43
		
44
		setMatcher(GMFGEN.getGenPlugin(), ALWAYS_MATCH); //exactly one feature for ALWAYS_MATCH GenEditorGenerator
45
		preserveIfSet(GMFGEN.getGenPlugin(), GMFGEN.getGenPlugin_ID());
46
		preserveIfSet(GMFGEN.getGenPlugin(), GMFGEN.getGenPlugin_Name());
47
		preserveIfSet(GMFGEN.getGenPlugin(), GMFGEN.getGenPlugin_Provider());
48
		preserveIfSet(GMFGEN.getGenPlugin(), GMFGEN.getGenPlugin_Version());
49
		preserveIfSet(GMFGEN.getGenPlugin(), GMFGEN.getGenPlugin_ActivatorClassName());
50
		preserveIfSet(GMFGEN.getGenPlugin(), GMFGEN.getGenPlugin_PrintingEnabled());
51
		
52
		setMatcher(GMFGEN.getGenEditorView(), ALWAYS_MATCH); //exactly one 
53
		preserveIfSet(GMFGEN.getGenEditorView(), GMFGEN.getGenEditorView_IconPath());
54
		preserveIfSet(GMFGEN.getGenEditorView(), GMFGEN.getGenEditorView_ClassName());
55
		preserveIfSet(GMFGEN.getGenEditorView(), GMFGEN.getGenEditorView_ID());
56
		
57
		setMatcher(GMFGEN.getGenDiagram(), ALWAYS_MATCH);  
58
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getShortcuts_ContainsShortcutsTo());
59
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getShortcuts_ShortcutsProvidedFor());
60
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getEditorCandies_CreationWizardIconPath());
61
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getEditorCandies_CreationWizardCategoryID());
62
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getGenDiagram_Synchronized());
63
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationEnabled());
64
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_LiveValidationUIFeedback());		
65
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationDecorators());
66
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationDecoratorProviderClassName());		
67
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationDecoratorProviderPriority());		
68
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationProviderClassName());		
69
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_ValidationProviderPriority());
70
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_MetricProviderPriority());		
71
		preserveIfSet(GMFGEN.getGenDiagram(), GMFGEN.getBatchValidation_MetricProviderClassName());		
72
		
73
		setMatcher(GMFGEN.getGenTopLevelNode(), getGenNodeMatcher());
74
		preserveIfNotByPattern(GMFGEN.getGenTopLevelNode(), GMFGEN.getGenContainerBase_CanonicalEditPolicyClassName(), ".*" + GenChildContainer.CANONICAL_EDIT_POLICY_SUFFIX); //$NON-NLS-1$
75
		preserveIfNotByPattern(GMFGEN.getGenTopLevelNode(), GMFGEN.getGenNode_GraphicalNodeEditPolicyClassName(), ".*" + GenNode.GRAPHICAL_NODE_EDIT_POLICY_SUFFIX); //$NON-NLS-1$
76
		//[155332]preserveIfNotByPattern(GMFGEN.getGenTopLevelNode(), GMFGEN.getGenCommonBase_EditPartClassName(), ".*" + GenCommonBase.EDIT_PART_SUFFIX);
77
		preserveIfSet(GMFGEN.getGenTopLevelNode(), GMFGEN.getGenNode_PrimaryDragEditPolicyQualifiedClassName());
78
		
79
		setMatcher(GMFGEN.getGenChildNode(), getGenNodeMatcher());
80
		preserveIfNotByPattern(GMFGEN.getGenChildNode(), GMFGEN.getGenContainerBase_CanonicalEditPolicyClassName(), ".*" + GenChildContainer.CANONICAL_EDIT_POLICY_SUFFIX); //$NON-NLS-1$
81
		preserveIfNotByPattern(GMFGEN.getGenChildNode(), GMFGEN.getGenNode_GraphicalNodeEditPolicyClassName(), ".*" + GenNode.GRAPHICAL_NODE_EDIT_POLICY_SUFFIX); //$NON-NLS-1$
82
		//[155332]preserveIfNotByPattern(GMFGEN.getGenChildNode(), GMFGEN.getGenCommonBase_EditPartClassName(), ".*" + GenCommonBase.EDIT_PART_SUFFIX);
83
		preserveIfSet(GMFGEN.getGenChildNode(), GMFGEN.getGenNode_PrimaryDragEditPolicyQualifiedClassName());
84
		 
85
		setMatcher(GMFGEN.getGenChildLabelNode(), getGenNodeMatcher());
86
		preserveIfSet(GMFGEN.getGenChildLabelNode(), GMFGEN.getGenNode_PrimaryDragEditPolicyQualifiedClassName());
87
		
88
		setMatcher(GMFGEN.getGenChildSideAffixedNode(), getGenNodeMatcher());
89
		preserveIfSet(GMFGEN.getGenChildSideAffixedNode(), GMFGEN.getGenNode_PrimaryDragEditPolicyQualifiedClassName());
90
		
91
		setMatcher(GMFGEN.getGenCompartment(), new ReflectiveMatcher(GMFGEN.getGenCompartment_Title()));
92
		preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_ListLayout());
93
		preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_CanCollapse());
94
		preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_HideIfEmpty());
95
		preserveIfSet(GMFGEN.getGenCompartment(), GMFGEN.getGenCompartment_NeedsTitle());
96
		//[155332]preserveIfNotByPattern(GMFGEN.getGenCompartment(), GMFGEN.getGenCommonBase_EditPartClassName(), ".*" + GenCommonBase.EDIT_PART_SUFFIX);
97
		
98
		//if parent node is matched, then viemap is matched automatically because it is [1] feature.
99
		//there are nothing to reconcile for viewmaps, all their properties are derived
100
		//we need this only to dig into viewmap attributes
101
		setMatcherForAllSubclasses(GMFGEN.getViewmap(), ALWAYS_MATCH);
102
		
103
		setMatcher(GMFGEN.getDefaultSizeAttributes(), ALWAYS_MATCH);
104
		setCopier(GMFGEN.getDefaultSizeAttributes(), Copier.COMPLETE_COPY);
105
		preserveIfSet(GMFGEN.getDefaultSizeAttributes(), GMFGEN.getDefaultSizeAttributes_Height());
106
		preserveIfSet(GMFGEN.getDefaultSizeAttributes(), GMFGEN.getDefaultSizeAttributes_Width());
107
108
		// provided GenCommonBase matched, custom behaviour should be kept as is
109
		setMatcher(GMFGEN.getCustomBehaviour(), ALWAYS_MATCH);
110
		setCopier(GMFGEN.getCustomBehaviour(), Copier.COMPLETE_COPY);
111
		
112
		setMatcher(GMFGEN.getMetamodelType(), ALWAYS_MATCH);
113
		preserveIfSet(GMFGEN.getMetamodelType(), GMFGEN.getElementType_DisplayName());
114
		preserveIfSet(GMFGEN.getMetamodelType(), GMFGEN.getElementType_DefinedExternally());
115
116
		setMatcher(GMFGEN.getSpecializationType(), ALWAYS_MATCH);
117
		preserveIfSet(GMFGEN.getSpecializationType(), GMFGEN.getElementType_DisplayName());
118
		preserveIfSet(GMFGEN.getSpecializationType(), GMFGEN.getElementType_DefinedExternally());
119
120
		setMatcher(GMFGEN.getGenPropertySheet(), ALWAYS_MATCH);
121
		preserveIfSet(GMFGEN.getGenPropertySheet(), GMFGEN.getGenPropertySheet_ReadOnly());
122
		preserveIfSet(GMFGEN.getGenPropertySheet(), GMFGEN.getGenPropertySheet_NeedsCaption());
123
		preserveIfSet(GMFGEN.getGenPropertySheet(), GMFGEN.getGenPropertySheet_PackageName());
124
		preserveIfSet(GMFGEN.getGenPropertySheet(), GMFGEN.getGenPropertySheet_LabelProviderClassName());
125
126
		setMatcherForAllSubclasses(GMFGEN.getGenPropertyTab(), new ReflectiveMatcher(GMFGEN.getGenPropertyTab_ID()));
127
		preserveIfSet(GMFGEN.getGenStandardPropertyTab(),GMFGEN.getGenPropertyTab_Label());
128
129
		preserveIfSet(GMFGEN.getGenCustomPropertyTab(),GMFGEN.getGenPropertyTab_Label());
130
		preserveIfSet(GMFGEN.getGenCustomPropertyTab(),GMFGEN.getGenCustomPropertyTab_ClassName());
131
	}
132
133
	private Matcher getGenNodeMatcher(){
134
		//FIXME: use new AttributeMatcher("domainMetaClass")
135
		return new ReflectiveMatcher(GMFGenPackage.eINSTANCE.getGenNode(), new ReflectiveMatcher.Reflector(){
136
			public Object reflect(EObject target) {
137
				GenNode genNode = (GenNode)target;
138
				return genNode.getDomainMetaClass();
139
			}
140
		});
141
	}
142
	
143
	private void preserveIfSet(EClass eClass, EAttribute feature){
144
		//FIXME: only attributes for now, allow references
145
		addDecisionMaker(eClass, new DefaultDecisionMaker(feature));
146
	}
147
	
148
	private void preserveIfNotByPattern(EClass eClass, EAttribute feature, String pattern){
149
		addDecisionMaker(eClass, new StringPatternDecisionMaker(pattern, feature));
150
	}
151
	
152
}
(-)src/org/eclipse/gmf/internal/bridge/transform/TransformToGenModelOperation.java (+328 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Alexander Fedorov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import java.io.IOException;
15
import java.util.HashMap;
16
import java.util.List;
17
import java.util.Map;
18
19
import org.eclipse.core.runtime.CoreException;
20
import org.eclipse.core.runtime.IProgressMonitor;
21
import org.eclipse.core.runtime.IStatus;
22
import org.eclipse.core.runtime.NullProgressMonitor;
23
import org.eclipse.core.runtime.Status;
24
import org.eclipse.core.runtime.SubProgressMonitor;
25
import org.eclipse.emf.codegen.ecore.genmodel.GenModel;
26
import org.eclipse.emf.common.util.BasicDiagnostic;
27
import org.eclipse.emf.common.util.Diagnostic;
28
import org.eclipse.emf.common.util.URI;
29
import org.eclipse.emf.ecore.resource.Resource;
30
import org.eclipse.emf.ecore.resource.ResourceSet;
31
import org.eclipse.emf.ecore.xmi.XMLResource;
32
import org.eclipse.gmf.codegen.gmfgen.GenEditorGenerator;
33
import org.eclipse.gmf.gmfgraph.util.FigureQualifiedNameSwitch;
34
import org.eclipse.gmf.gmfgraph.util.RuntimeFQNSwitch;
35
import org.eclipse.gmf.gmfgraph.util.RuntimeLiteFQNSwitch;
36
import org.eclipse.gmf.graphdef.codegen.MapModeCodeGenStrategy;
37
import org.eclipse.gmf.internal.bridge.VisualIdentifierDispenser;
38
import org.eclipse.gmf.internal.bridge.genmodel.BasicDiagramRunTimeModelHelper;
39
import org.eclipse.gmf.internal.bridge.genmodel.DiagramGenModelTransformer;
40
import org.eclipse.gmf.internal.bridge.genmodel.DiagramRunTimeModelHelper;
41
import org.eclipse.gmf.internal.bridge.genmodel.GenModelProducer;
42
import org.eclipse.gmf.internal.bridge.genmodel.InnerClassViewmapProducer;
43
import org.eclipse.gmf.internal.bridge.genmodel.ViewmapProducer;
44
import org.eclipse.gmf.internal.bridge.naming.gen.GenModelNamingMediatorImpl;
45
import org.eclipse.gmf.internal.bridge.ui.Plugin;
46
import org.eclipse.gmf.internal.common.migrate.ModelLoadHelper;
47
import org.eclipse.gmf.internal.common.reconcile.Reconciler;
48
import org.eclipse.gmf.mappings.Mapping;
49
50
51
public class TransformToGenModelOperation {
52
	
53
	private URI myMapModelURI;
54
	private URI myGMFGenModelURI;
55
	private TransformOptions myOptions;
56
	private Mapping myMapping;
57
	private GenModelDetector myGMDetector;
58
	private GenModel myGenModel;
59
	
60
	public TransformToGenModelOperation(URI mapURI) {
61
		assert mapURI != null;
62
		this.myMapModelURI = mapURI;
63
		this.myOptions = new TransformOptions();
64
	}
65
	
66
	public TransformOptions getOptions() {
67
		return myOptions;
68
	}
69
	
70
	public URI getMapURI() {
71
		return this.myMapModelURI;
72
	}
73
	
74
	public URI getGenURI() {
75
		return this.myGMFGenModelURI;
76
	}
77
78
	void setGenURI(URI gmfGen) {
79
		this.myGMFGenModelURI = gmfGen;
80
	}
81
82
	private GenModel getGenModel() {
83
		return this.myGenModel;
84
	}
85
86
	Mapping getMapping() {
87
		return this.myMapping;
88
	}
89
	
90
	private void setMapping(Mapping m) {
91
		this.myMapping = m;
92
		myGMDetector = null;
93
		myGenModel = null;
94
	}
95
	
96
	GenModelDetector getGenModelDetector() {
97
		if (myGMDetector == null) {
98
			myGMDetector = new GenModelDetector(getMapping());
99
		}
100
		return myGMDetector;
101
	}
102
	
103
	Mapping loadMappingModel(ResourceSet rs, URI uri, IProgressMonitor pm) throws CoreException {
104
		IProgressMonitor monitor = null;
105
		try {
106
			monitor = (pm != null) ? new SubProgressMonitor(pm, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK) : new NullProgressMonitor(); 
107
			IStatus cancel = Plugin.createCancel(Messages.getString("TransformToGenModelOperation.cancel_mapping_model_load")); //$NON-NLS-1$
108
			CoreException cancelled = new CoreException(cancel);
109
110
			monitor.beginTask("", 100); //$NON-NLS-1$
111
			if (monitor.isCanceled()) {
112
				throw cancelled;
113
			}
114
			monitor.subTask(Messages.getString("TransformToGenModelOperation.task_loading")); //$NON-NLS-1$
115
			ModelLoadHelper loadHelper = new ModelLoadHelper(rs, uri);
116
			IStatus loadStatus = loadHelper.getStatus();
117
			if (!loadStatus.isOK()) {
118
				throw new CoreException(loadStatus);
119
			}
120
			monitor.worked(20);
121
122
			if (monitor.isCanceled()) {
123
				throw cancelled;
124
			}
125
			monitor.subTask(Messages.getString("TransformToGenModelOperation.task_validating")); //$NON-NLS-1$
126
			final Mapping content = (Mapping) loadHelper.getContentsRoot();
127
			Diagnostic mapIsValid = ValidationHelper.validate(content, true, monitor);
128
			int severity = mapIsValid.getSeverity();
129
			monitor.worked(60);
130
			if (!getOptions().checkMapdefLoadLevel(mapIsValid)) {
131
				if (Diagnostic.CANCEL == severity) {
132
					throw cancelled;
133
				} else {
134
					throw new CoreException(getFirst(mapIsValid));
135
				}
136
			}
137
			setMapping(content);
138
			return content;
139
		} finally {
140
			monitor.done();
141
		}
142
	}
143
	
144
	GenModel findGenmodel(ResourceSet rs) throws CoreException {
145
		try {
146
			GenModelDetector gmd = getGenModelDetector();
147
			IStatus detect = gmd.detect();
148
			if (detect.isOK()) {
149
				GenModel genModel = gmd.get(rs);
150
				this.myGenModel = genModel;
151
				return genModel;
152
			}
153
			throw new CoreException(detect);
154
			
155
		} catch (CoreException e) {
156
			throw e;
157
		} catch (Exception e) {
158
			IStatus error = Plugin.createError(Messages.getString("TransformToGenModelOperation.error_invalid_mapping_model"), e); //$NON-NLS-1$
159
			throw new CoreException(error);
160
		}
161
	}
162
163
	GenModel loadGenModel(ResourceSet rs, URI uri, IProgressMonitor pm) throws CoreException {
164
		try {
165
			GenModelDetector gmd = getGenModelDetector();
166
			IStatus status = Status.OK_STATUS;
167
			if (uri == null) {
168
				status = gmd.detect();
169
			} else {
170
				status = gmd.advise(uri); 
171
			}
172
			if (!status.isOK()) {
173
				throw new CoreException(status);
174
			}
175
			GenModel genModel = gmd.get(rs);
176
			if (getOptions().getDetectStaleGenmodel()) {
177
				StaleGenModelDetector staleDetector = new StaleGenModelDetector(genModel);
178
				IStatus stale = staleDetector.detect();
179
				if (!stale.isOK()) {
180
					throw new CoreException(stale);
181
				}
182
			}
183
			this.myGenModel = genModel;
184
			return genModel;
185
186
		} catch (CoreException e) {
187
			throw e;
188
		} catch (Exception e) {
189
			IStatus error = Plugin.createError(Messages.getString("TransformToGenModelOperation.error_load_genmodel"), e); //$NON-NLS-1$
190
			throw new CoreException(error);
191
		}
192
	}
193
	
194
	IStatus executeTransformation(ResourceSet rs, IProgressMonitor pm) {
195
		IProgressMonitor monitor = null;
196
		try {
197
			monitor = (pm != null) ? new SubProgressMonitor(pm, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK) : new NullProgressMonitor(); 
198
			monitor.beginTask("", 100); //$NON-NLS-1$
199
			if (monitor.isCanceled()) {
200
				return Status.CANCEL_STATUS;
201
			}
202
			final DiagramRunTimeModelHelper drtModelHelper = detectRunTimeModel();
203
			final ViewmapProducer viewmapProducer = detectTransformationOptions();
204
			final VisualIdentifierDispenserProvider idDispenser = getVisualIdDispenser();
205
			idDispenser.acquire();
206
207
			GenModelProducer t = createGenModelProducer(getGenModel(), drtModelHelper, viewmapProducer, idDispenser.get());
208
209
			monitor.subTask(Messages.getString("TransformToGenModelOperation.task_generating")); //$NON-NLS-1$
210
			GenEditorGenerator genEditor = t.process(getMapping(), new SubProgressMonitor(monitor, 20));
211
			if (monitor.isCanceled()) {
212
				return Status.CANCEL_STATUS;
213
			}
214
			monitor.subTask(Messages.getString("TransformToGenModelOperation.task_reconciling")); //$NON-NLS-1$
215
			if (Plugin.needsReconcile()) {
216
				reconcile(rs, genEditor);
217
			}
218
			monitor.worked(20);
219
			if (monitor.isCanceled()) {
220
				return Status.CANCEL_STATUS;
221
			}
222
			monitor.subTask(Messages.getString("TransformToGenModelOperation.task_saving")); //$NON-NLS-1$
223
			save(rs, genEditor);
224
			monitor.worked(20);
225
			if (monitor.isCanceled()) {
226
				return Status.CANCEL_STATUS;
227
			}
228
			monitor.subTask(Messages.getString("TransformToGenModelOperation.task_validating")); //$NON-NLS-1$
229
			return validate(genEditor, monitor);
230
			
231
		} catch (Exception ex) {
232
			return Plugin.createError(ex.getMessage(), ex);
233
		} finally {
234
			if (monitor != null) {
235
				monitor.done();
236
			}
237
		}
238
	}
239
240
	public void reset(URI uri) {
241
		assert uri != null;
242
		myMapModelURI = uri;
243
		setMapping(null);
244
	}
245
	
246
	private IStatus getFirst(Diagnostic d) {
247
		if (d == null) {
248
			return Status.OK_STATUS;
249
		}
250
		List<Diagnostic> children = d.getChildren();
251
		if (children.isEmpty()) {
252
			return BasicDiagnostic.toIStatus(d);
253
		} else {
254
			return BasicDiagnostic.toIStatus(children.get(0));
255
		}
256
	}
257
	
258
	private DiagramRunTimeModelHelper detectRunTimeModel() {
259
		return new BasicDiagramRunTimeModelHelper();
260
	}
261
262
	private ViewmapProducer detectTransformationOptions() {
263
		FigureQualifiedNameSwitch fSwitch = getOptions().getUseRuntimeFigures() ? new RuntimeFQNSwitch() : new RuntimeLiteFQNSwitch();
264
		MapModeCodeGenStrategy mmStrategy = getOptions().getUseMapMode() ? MapModeCodeGenStrategy.DYNAMIC : MapModeCodeGenStrategy.STATIC;
265
		return new InnerClassViewmapProducer(fSwitch, mmStrategy);
266
	}
267
268
	private VisualIdentifierDispenserProvider getVisualIdDispenser() {
269
		return new VisualIdentifierDispenserProvider(getGenURI());
270
	}
271
272
	private GenModelProducer createGenModelProducer(GenModel domainGenModel, final DiagramRunTimeModelHelper drtModelHelper, final ViewmapProducer viewmapProducer, final VisualIdentifierDispenser idDespenser) {
273
		final DiagramGenModelTransformer t = new DiagramGenModelTransformer(drtModelHelper, new GenModelNamingMediatorImpl(), viewmapProducer, idDespenser, getOptions().getGenerateRCP());
274
		if (domainGenModel != null) {
275
			t.setEMFGenModel(domainGenModel);
276
		}
277
		return new GenModelProducer() {
278
279
			public GenEditorGenerator process(Mapping mapping, IProgressMonitor progress) {
280
				progress.beginTask(null, 1);
281
				try {
282
					t.transform(mapping);
283
					return t.getResult();
284
				} finally {
285
					progress.done();
286
				}
287
			}
288
		};
289
	}
290
291
	private void reconcile(ResourceSet rs, GenEditorGenerator genBurdern) {
292
		GenEditorGenerator old = null;
293
		Resource resource = null;
294
		try {
295
			resource = rs.getResource(getGenURI(), true);
296
			List contents = resource.getContents();
297
			if (!contents.isEmpty() && contents.get(0) instanceof GenEditorGenerator) {
298
				old = (GenEditorGenerator) contents.get(0);
299
			}
300
			if (old != null) {
301
				new Reconciler(new GMFGenConfig()).reconcileTree(genBurdern, old);
302
			}
303
		} catch (RuntimeException e) {
304
			old = null;
305
		} finally {
306
			if (resource != null) {
307
				resource.unload();
308
			}
309
		}
310
	}
311
312
	private void save(ResourceSet rs, GenEditorGenerator genBurdern) throws IOException {
313
		Resource dgmmRes = rs.createResource(getGenURI());
314
		dgmmRes.getContents().add(genBurdern);
315
		dgmmRes.save(getSaveOptions());
316
	}
317
318
	private Map getSaveOptions() {
319
		HashMap<String, Object> saveOptions = new HashMap<String, Object>();
320
		saveOptions.put(XMLResource.OPTION_ENCODING, "UTF-8"); //$NON-NLS-1$
321
		return saveOptions;
322
	}
323
324
	private IStatus validate(GenEditorGenerator genBurdern, IProgressMonitor monitor) {
325
		Diagnostic d = ValidationHelper.validate(genBurdern, true, monitor);
326
		return getFirst(d);
327
	}
328
}
(-)src/org/eclipse/gmf/internal/bridge/transform/TransformToGenModelWizard.java (+160 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Alexander Fedorov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import java.lang.reflect.InvocationTargetException;
15
16
import org.eclipse.core.resources.IFile;
17
import org.eclipse.core.runtime.IProgressMonitor;
18
import org.eclipse.core.runtime.IStatus;
19
import org.eclipse.emf.common.util.URI;
20
import org.eclipse.emf.ecore.resource.ResourceSet;
21
import org.eclipse.emf.ecore.resource.impl.ResourceSetImpl;
22
import org.eclipse.gmf.codegen.gmfgen.presentation.EditorPlugin;
23
import org.eclipse.gmf.codegen.gmfgen.presentation.GMFGenModelWizard;
24
import org.eclipse.gmf.internal.bridge.wizards.WizardUtil;
25
import org.eclipse.gmf.internal.common.ui.ResourceLocationProvider;
26
import org.eclipse.jface.operation.IRunnableWithProgress;
27
import org.eclipse.jface.viewers.IStructuredSelection;
28
import org.eclipse.jface.wizard.WizardDialog;
29
import org.eclipse.jface.wizard.WizardPage;
30
import org.eclipse.ui.IWorkbench;
31
32
33
public class TransformToGenModelWizard extends GMFGenModelWizard {
34
	
35
	private static final String PAGE_ID_GENMODEL = "genmodel"; //$NON-NLS-1$
36
	private static final String PAGE_ID_GMFMAP = "gmfmap"; //$NON-NLS-1$
37
	private static final String PAGE_ID_TRANSFORM = "transform"; //$NON-NLS-1$
38
	
39
	protected MapModelConfigurationPage mapModelPage;
40
	protected GenModelConfigurationPage genModelPage;
41
	protected ViewmapProducerWizardPage transformOptionPage;
42
	
43
	private TransformToGenModelOperation myOperation;
44
	ResourceSet resourceSet;
45
	
46
	@Override
47
	public void addPages() {
48
		super.addPages();
49
		
50
		final String defaultName = EditorPlugin.INSTANCE.getString("_UI_GMFGenEditorFilenameDefaultBase"); //$NON-NLS-1$
51
		final String extension = EditorPlugin.INSTANCE.getString("_UI_GMFGenEditorFilenameExtension"); //$NON-NLS-1$
52
		newFileCreationPage.setFileName(WizardUtil.getDefaultFileName(selection, defaultName, extension));
53
		
54
		resourceSet = new ResourceSetImpl();
55
		ResourceLocationProvider rlp = new ResourceLocationProvider(selection);
56
		mapModelPage = new MapModelConfigurationPage(PAGE_ID_GMFMAP, rlp, resourceSet);
57
		mapModelPage.setTitle(Messages.getString("TransformToGenModelWizard.title_map_model")); //$NON-NLS-1$
58
		mapModelPage.setDescription(Messages.getString("TransformToGenModelWizard.descr_map_model")); //$NON-NLS-1$
59
		mapModelPage.setPageComplete(false);
60
		mapModelPage.setModelRequired(true);
61
		addPage(mapModelPage);
62
63
		genModelPage = new GenModelConfigurationPage(PAGE_ID_GENMODEL, rlp, resourceSet);
64
		genModelPage.setTitle(Messages.getString("TransformToGenModelWizard.title_gen_model")); //$NON-NLS-1$
65
		genModelPage.setDescription(Messages.getString("TransformToGenModelWizard.descr_gen_model")); //$NON-NLS-1$
66
		genModelPage.setPageComplete(false);
67
		genModelPage.setModelRequired(true);
68
		addPage(genModelPage);
69
70
		transformOptionPage = new ViewmapProducerWizardPage(PAGE_ID_TRANSFORM);
71
		transformOptionPage.setTitle(Messages.getString("TransformToGenModelWizard.title_options")); //$NON-NLS-1$
72
		transformOptionPage.setDescription(Messages.getString("TransformToGenModelWizard.descr_options")); //$NON-NLS-1$
73
		transformOptionPage.setPageComplete(false);
74
		addPage(transformOptionPage);
75
		
76
	}
77
	
78
	/* (non-Javadoc)
79
	 * @see org.eclipse.gmf.codegen.gmfgen.presentation.GMFGenModelWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
80
	 */
81
	@Override
82
	public void init(IWorkbench w, IStructuredSelection ss) {
83
		super.init(w, ss);
84
		setWindowTitle(Messages.getString("TransformToGenModelWizard.title_wizard")); //$NON-NLS-1$
85
		setNeedsProgressMonitor(true);
86
		IFile mapFile = (IFile) ss.getFirstElement();
87
		URI mapURI = URI.createPlatformResourceURI(mapFile.getFullPath().toString(), true);
88
		initOperation(mapURI);
89
	}
90
	
91
	void initOperation(URI mapURI) {
92
		myOperation = new TransformToGenModelOperation(mapURI);
93
	}
94
	
95
	@Override
96
	public boolean performFinish() {
97
		try {
98
			final IStatus[] s = new IStatus[1];
99
			IRunnableWithProgress iwr = new IRunnableWithProgress() {
100
				public void run(IProgressMonitor monitor) {
101
					s[0] = getTransformOperation().executeTransformation(resourceSet, monitor);
102
				}
103
			};
104
			getContainer().run(false, false, iwr);
105
			if (s[0].isOK()) {
106
				setErrorMessage(null);
107
				saveTransformOptions();
108
				return true;
109
			}
110
			setErrorMessage(s[0].getMessage());
111
			return false;
112
		} catch (InvocationTargetException ex) {
113
			Throwable targetException = ex.getTargetException();
114
			if (targetException != null && targetException.getMessage() != null) {
115
				String message = targetException.getMessage();
116
				if (message == null) {
117
					message = Messages.getString("TransformToGenModelWizard.error_transform"); //$NON-NLS-1$
118
				}
119
			}
120
			return false;
121
		} catch (InterruptedException ex){
122
			setErrorMessage(Messages.getString("TransformToGenModelWizard.cancel_transform")); //$NON-NLS-1$
123
			return false;
124
		}
125
	}
126
	
127
	private void saveTransformOptions() {
128
		if (getTransformOperation() != null) {
129
			getTransformOperation().getOptions().flush();
130
		}
131
	}
132
	
133
	/* (non-Javadoc)
134
	 * @see org.eclipse.jface.wizard.Wizard#performCancel()
135
	 */
136
	@Override
137
	public boolean performCancel() {
138
		if (getTransformOperation() != null) {
139
			getTransformOperation().getOptions().reset();
140
		}
141
		return super.performCancel();
142
	}
143
144
	TransformToGenModelOperation getTransformOperation() {
145
		return myOperation;
146
	}
147
	
148
	IFile getTargetFile() {
149
		return newFileCreationPage.getModelFile();
150
	}
151
	
152
	private void setErrorMessage(String message) {
153
		WizardDialog wd = (WizardDialog) getContainer();
154
		WizardPage wp = (WizardPage) wd.getCurrentPage();
155
		if (wp != null) {
156
			wp.setErrorMessage(message);
157
		}
158
	}
159
160
}
(-)src/org/eclipse/gmf/internal/bridge/transform/TransformOptions.java (+142 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Alexander Fedorov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import org.eclipse.core.runtime.Platform;
15
import org.eclipse.core.runtime.Preferences;
16
import org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer;
17
import org.eclipse.core.runtime.preferences.DefaultScope;
18
import org.eclipse.core.runtime.preferences.IEclipsePreferences;
19
import org.eclipse.emf.common.util.Diagnostic;
20
import org.eclipse.gmf.internal.bridge.ui.Plugin;
21
22
23
public class TransformOptions extends AbstractPreferenceInitializer {
24
	
25
	public static final String PREF_MAPDEF_LOAD_LEVEL = "mapdef_load_level"; //$NON-NLS-1$
26
	public static final String PREF_GENMODEL_DETECT_STALE = "genmodel_detect_stale"; //$NON-NLS-1$
27
	public static final String PREF_GENERATE_RCP = "generate_rcp"; //$NON-NLS-1$
28
	public static final String PREF_USE_MAP_MODE = "use_map_mode"; //$NON-NLS-1$
29
	public static final String PREF_USE_RUNTIME_FIGURES = "use_runtime_figures"; //$NON-NLS-1$
30
	
31
	private static int VAL_MAPDEF_LOAD_LEVEL_INFO = 0;	
32
	private static int VAL_MAPDEF_LOAD_LEVEL_WARNING = 1;	
33
	private static int VAL_MAPDEF_LOAD_LEVEL_ERROR = 2;	
34
35
	private Preferences myPreferences;
36
	
37
	public TransformOptions() {
38
		myPreferences = new Preferences();
39
		reset();
40
	}
41
	
42
	private Preferences getPreferences() {
43
		return myPreferences;
44
	}
45
	
46
	public void reset() {
47
		Preferences pluginPrefs = Plugin.getDefault().getPluginPreferences();
48
		copyPreferences(pluginPrefs, myPreferences);
49
	}
50
	
51
	public void flush() {
52
		Preferences pluginPrefs = Plugin.getDefault().getPluginPreferences();
53
		copyPreferences(myPreferences, pluginPrefs);
54
		Plugin.getDefault().savePluginPreferences();
55
	}
56
	
57
	private void copyPreferences(Preferences source, Preferences target) {
58
		String[] propNames = source.propertyNames();
59
		for (int i = 0; i < propNames.length; i++) {
60
			String name = propNames[i];
61
			String value = source.getString(name);
62
			target.setValue(name, value);
63
		}
64
	}
65
	
66
	public boolean checkMapdefLoadLevel(Diagnostic diagnostic) {
67
		if (diagnostic == null) {
68
			return false;
69
		}
70
		int severity = diagnostic.getSeverity();
71
		int level = getMapdefLoadLevel();
72
		if (VAL_MAPDEF_LOAD_LEVEL_INFO == level) {
73
			return Diagnostic.INFO >= severity;
74
		} else if (VAL_MAPDEF_LOAD_LEVEL_WARNING == level) {
75
			return Diagnostic.WARNING >= severity;
76
		} else if (VAL_MAPDEF_LOAD_LEVEL_ERROR == level) {
77
			return Diagnostic.ERROR >= severity;
78
		}
79
		return Diagnostic.CANCEL == severity;
80
	}
81
	
82
	public int getMapdefLoadLevel() {
83
		return getPreferences().getInt(PREF_MAPDEF_LOAD_LEVEL);
84
	}
85
	
86
	public boolean getDetectStaleGenmodel() {
87
		return getPreferences().getBoolean(PREF_GENMODEL_DETECT_STALE);
88
	}
89
90
	public boolean getGenerateRCP() {
91
		return getPreferences().getBoolean(PREF_GENERATE_RCP);
92
	}
93
94
	public boolean getUseMapMode() {
95
		return getPreferences().getBoolean(PREF_USE_MAP_MODE);
96
	}
97
98
	public boolean getUseRuntimeFigures() {
99
		return getPreferences().getBoolean(PREF_USE_RUNTIME_FIGURES);
100
	}
101
102
	public void setMapdefLoadLevel(int value) {
103
		getPreferences().setValue(PREF_MAPDEF_LOAD_LEVEL, value);
104
	}
105
106
	public void setDetectStaleGenmodel(boolean value) {
107
		getPreferences().setValue(PREF_GENMODEL_DETECT_STALE, value);
108
	}
109
110
	public void setGenerateRCP(boolean value) {
111
		getPreferences().setValue(PREF_GENERATE_RCP, value);
112
	}
113
114
	public void setUseMapMode(boolean value) {
115
		getPreferences().setValue(PREF_USE_MAP_MODE, value);
116
	}
117
118
	public void setUseRuntimeFigures(boolean value) {
119
		getPreferences().setValue(PREF_USE_RUNTIME_FIGURES, value);
120
	}
121
122
	/* (non-Javadoc)
123
	 * @see org.eclipse.core.runtime.preferences.AbstractPreferenceInitializer#initializeDefaultPreferences()
124
	 */
125
	@Override
126
	public void initializeDefaultPreferences() {
127
		DefaultScope scope = new DefaultScope();
128
		IEclipsePreferences node = scope.getNode(Plugin.getPluginID());
129
		node.putInt(PREF_MAPDEF_LOAD_LEVEL, VAL_MAPDEF_LOAD_LEVEL_INFO);
130
		node.put(PREF_GENMODEL_DETECT_STALE, Boolean.TRUE.toString());
131
132
		node.put(PREF_GENERATE_RCP, Boolean.FALSE.toString());
133
		boolean liteOptionPresent = checkLiteOptionPresent();
134
		node.putBoolean(PREF_USE_MAP_MODE, !liteOptionPresent);
135
		node.putBoolean(PREF_USE_RUNTIME_FIGURES, !liteOptionPresent);
136
137
	}
138
	
139
	static boolean checkLiteOptionPresent() {
140
		return Platform.getBundle("org.eclipse.gmf.codegen.lite") != null; //$NON-NLS-1$
141
	}
142
}
(-)src/org/eclipse/gmf/internal/bridge/transform/TransformToGenModelAction.java (+62 lines)
Added Link Here
1
/*
2
 * Copyright (c) 2005,2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Artem Tikhomirov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import org.eclipse.jface.action.IAction;
15
import org.eclipse.jface.viewers.ISelection;
16
import org.eclipse.jface.viewers.IStructuredSelection;
17
import org.eclipse.jface.window.Window;
18
import org.eclipse.jface.wizard.WizardDialog;
19
import org.eclipse.swt.widgets.Shell;
20
import org.eclipse.ui.IObjectActionDelegate;
21
import org.eclipse.ui.IWorkbenchPart;
22
import org.eclipse.ui.PlatformUI;
23
24
/**
25
 * .gmfmap to .gmfgen
26
 * 
27
 * @author artem
28
 */
29
public class TransformToGenModelAction implements IObjectActionDelegate {
30
31
	private static final int WIZARD_WIDTH = 500;
32
	private static final int WIZARD_HEIGHT = 600;
33
34
	private IWorkbenchPart myPart;
35
36
	private IStructuredSelection sselection;
37
38
	public void setActivePart(IAction action, IWorkbenchPart targetPart) {
39
		myPart = targetPart;
40
	}
41
42
	public void selectionChanged(IAction action, ISelection selection) {
43
		final IStructuredSelection structuredSelection = ((IStructuredSelection) selection);
44
		sselection = structuredSelection;
45
	}
46
47
	public void run(IAction action) {
48
		final TransformToGenModelWizard wiz = new TransformToGenModelWizard();
49
		wiz.setWindowTitle(action.getText());
50
		wiz.init(PlatformUI.getWorkbench(), sselection);
51
		WizardDialog wd = new WizardDialog(getShell(), wiz);
52
		wd.create();
53
		wd.getShell().setSize(WIZARD_WIDTH, WIZARD_HEIGHT);
54
		if (wd.open() != Window.OK) {
55
			return;
56
		}
57
	}
58
59
	private Shell getShell() {
60
		return myPart.getSite().getShell();
61
	}
62
}
(-)src/org/eclipse/gmf/internal/bridge/transform/ModelConfigurationPage.java (+90 lines)
Added Link Here
1
/**
2
 * Copyright (c) 2006 Borland Software Corporation
3
 * 
4
 * All rights reserved. This program and the accompanying materials
5
 * are made available under the terms of the Eclipse Public License v1.0
6
 * which accompanies this distribution, and is available at
7
 * http://www.eclipse.org/legal/epl-v10.html
8
 *
9
 * Contributors:
10
 *    Alexander Fedorov (Borland) - initial API and implementation
11
 */
12
package org.eclipse.gmf.internal.bridge.transform;
13
14
import java.lang.reflect.InvocationTargetException;
15
16
import org.eclipse.core.runtime.CoreException;
17
import org.eclipse.core.runtime.IProgressMonitor;
18
import org.eclipse.core.runtime.NullProgressMonitor;
19
import org.eclipse.core.runtime.SubProgressMonitor;
20
import org.eclipse.emf.ecore.resource.Resource;
21
import org.eclipse.emf.ecore.resource.ResourceSet;
22
import org.eclipse.gmf.internal.bridge.ui.Plugin;
23
import org.eclipse.gmf.internal.common.ui.ModelSelectionPage;
24
import org.eclipse.gmf.internal.common.ui.ResourceLocationProvider;
25
import org.eclipse.ui.actions.WorkspaceModifyOperation;
26
27
28
public class ModelConfigurationPage extends ModelSelectionPage {
29
30
	public ModelConfigurationPage(String pageId, ResourceLocationProvider rlp, ResourceSet resourceSet) {
31
		super(pageId, rlp, resourceSet);
32
	}
33
34
	@Override
35
	protected Resource loadResource() {
36
		Resource current = getResource();
37
		if (current != null) {
38
			current.getResourceSet().getResources().remove(current);
39
		}
40
		
41
		final Resource[] result = new Resource[1];
42
	    WorkspaceModifyOperation initializeOperation = new WorkspaceModifyOperation()
43
	      {
44
45
			protected void execute(IProgressMonitor progressMonitor) throws CoreException {
46
				IProgressMonitor monitor = null;
47
				try {
48
					monitor = (progressMonitor != null) ? new SubProgressMonitor(progressMonitor, 1, SubProgressMonitor.PREPEND_MAIN_LABEL_TO_SUBTASK) : new NullProgressMonitor(); 
49
					setErrorMessage(null);
50
					setMessage(null);
51
					result[0] = doLoadResource(monitor);
52
				} catch (CoreException exception) {
53
					throw exception;
54
				} catch (Exception exception) {
55
					throw new CoreException(Plugin.createError(exception.getMessage(), exception));
56
				} finally {
57
					if (monitor != null) {
58
						monitor.done();
59
					}
60
				}
61
			}
62
		};
63
64
		try {
65
			getContainer().run(false, false, initializeOperation);
66
			setMessage(null);
67
			setErrorMessage(null);
68
		} catch (InvocationTargetException e) {
69
			Throwable target = e.getTargetException();
70
			setErrorMessage(target.getMessage());
71
		} catch (InterruptedException e) {
72
			//TODO
73
		}
74
		return result[0];
75
	}
76
77
	protected Resource doLoadResource(IProgressMonitor monitor) throws CoreException {
78
		try {
79
			Resource r = super.loadResource();
80
			return r;
81
		} catch (Exception e) {
82
			throw new CoreException(Plugin.createError(e.getMessage(), e));
83
		} finally {
84
			if (monitor != null) {
85
				monitor.done();
86
			}
87
		}
88
	}
89
90
}

Return to bug 148836