Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 00a37e230bf237533a533197abed74c7028cf70a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
/*******************************************************************************
 * Copyright (c) 2004 INRIA.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Freddy Allilaire (INRIA) - initial API and implementation
 *******************************************************************************/
package org.eclipse.m2m.atl.core.ui.launch;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Platform;
import org.eclipse.debug.core.DebugException;
import org.eclipse.debug.core.ILaunch;
import org.eclipse.debug.core.ILaunchConfiguration;
import org.eclipse.debug.core.ILaunchManager;
import org.eclipse.debug.core.model.LaunchConfigurationDelegate;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.m2m.atl.common.ATLExecutionException;
import org.eclipse.m2m.atl.common.ATLLaunchConstants;
import org.eclipse.m2m.atl.common.ATLLogger;
import org.eclipse.m2m.atl.core.ATLCoreException;
import org.eclipse.m2m.atl.core.launch.ILauncher;
import org.eclipse.m2m.atl.core.service.CoreService;
import org.eclipse.m2m.atl.core.service.LauncherService;
import org.eclipse.m2m.atl.core.ui.ATLCoreUIPlugin;
import org.eclipse.m2m.atl.core.ui.Messages;
import org.eclipse.m2m.atl.debug.core.AtlDebugTarget;
import org.eclipse.m2m.atl.debug.core.AtlRunTarget;
import org.eclipse.m2m.atl.debug.core.AtlSourceLocator;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;

/**
 * The method "launch" is launched when you click on the button "Run" or "Debug".
 * 
 * @author <a href="mailto:william.piers@obeo.fr">William Piers</a>
 * @author <a href="mailto:freddy.allilaire@obeo.fr">Freddy Allilaire</a>
 * @author <a href="mailto:thierry.fortin@obeo.fr">Thierry Fortin</a>
 */
public class AtlLaunchConfigurationDelegate extends LaunchConfigurationDelegate {

	private static Map<String, IFile> moduleFilesByModuleName;

	private static final String[] PROFILER_VM_IDS = new String[] {
			"EMF-specific VM Profiler", "Regular VM Profiler",}; //$NON-NLS-1$ //$NON-NLS-2$

	/**
	 * {@inheritDoc}
	 * 
	 * @see org.eclipse.debug.core.model.ILaunchConfigurationDelegate#launch(org.eclipse.debug.core.ILaunchConfiguration,
	 *      java.lang.String, org.eclipse.debug.core.ILaunch, org.eclipse.core.runtime.IProgressMonitor)
	 */
	public void launch(ILaunchConfiguration configuration, String mode, ILaunch launch,
			IProgressMonitor monitor) throws CoreException {

		moduleFilesByModuleName = new HashMap<String, IFile>();
		if (monitor == null) {
			monitor = new NullProgressMonitor();
		}

		String launcherName = configuration.getAttribute(ATLLaunchConstants.ATL_VM, ""); //$NON-NLS-1$		
		String atlCompiler = configuration.getAttribute(ATLLaunchConstants.ATL_COMPILER, ""); //$NON-NLS-1$
		boolean isRefining = configuration.getAttribute(ATLLaunchConstants.IS_REFINING, false);

		Map<String, Object> options = new HashMap<String, Object>();
		boolean isRefiningTraceMode = ("atl2006".equals(atlCompiler) || "atl2010".equals(atlCompiler)) && isRefining; //$NON-NLS-1$
		options.put("isRefiningTraceMode", isRefiningTraceMode); //$NON-NLS-1$
		options.put("launch", launch); //$NON-NLS-1$
		options.put("monitor", monitor); //$NON-NLS-1$

		// Launch configuration analysis
		String fileName = configuration.getAttribute(ATLLaunchConstants.ATL_FILE_NAME,
				ATLLaunchConstants.NULL_PARAMETER);
		Map<String, String> unsortedSourceModels = configuration.getAttribute(ATLLaunchConstants.INPUT,
				Collections.<String, String> emptyMap());
		Map<String, String> unsortedTargetModels = configuration.getAttribute(ATLLaunchConstants.OUTPUT,
				Collections.<String, String> emptyMap());
		Map<String, String> launchConfigModelPaths = configuration.getAttribute(ATLLaunchConstants.PATH,
				Collections.<String, String> emptyMap());
		Map<String, String> modelPaths = convertPaths(launchConfigModelPaths);

		Map<String, String> libs = configuration.getAttribute(ATLLaunchConstants.LIBS, Collections.<String, String> emptyMap());
		List<String> superimps = configuration.getAttribute(ATLLaunchConstants.SUPERIMPOSE,
				Collections.<String> emptyList());
		options.putAll(configuration.getAttribute(ATLLaunchConstants.OPTIONS, Collections.<String, String> emptyMap()));
		Map<String, String> modelHandlers = configuration.getAttribute(ATLLaunchConstants.MODEL_HANDLER,
				Collections.<String, String> emptyMap());
		options.put(ATLLaunchConstants.OPTION_MODEL_HANDLER, modelHandlers);

		if (LauncherService.getBooleanOption(options.get(AdvancedTab.OPTION_CLEAR), false)) {
			ATLCoreUIPlugin.clearConsole();
		}

		ILauncher launcher = null;
		try {
			showViewsForProfiler(launcherName);
			// API extensions management
			launcher = CoreService.getLauncher(launcherName);
		} catch (ATLCoreException e) {
			ATLLogger.log(Level.SEVERE, e.getMessage(), e);
		}

		if (launcher == null) {
			String[] registeredLaunchers = CoreService.getLaunchersNames();
			ATLLogger
					.severe(Messages
							.getString(
									"AtlLaunchConfigurationDelegate.LAUNCHER_NOT_FOUND", launcherName, Arrays.asList(registeredLaunchers))); //$NON-NLS-1$
			return;
		}

		// ATL modules
		IFile currentAtlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(getBytecodePath(fileName, launcher));
		String currentExtension = currentAtlFile.getFileExtension().toLowerCase();
		if (currentExtension.equals("atl")) { //$NON-NLS-1$
			options.put(ATLLaunchConstants.OPTION_ATL_FILE_PATH, fileName);
			String currentAsmPath = currentAtlFile.getFullPath().toString().substring(0,
					currentAtlFile.getFullPath().toString().length() - currentExtension.length())
					+ "asm"; //$NON-NLS-1$
			currentAtlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(currentAsmPath));
		}

		if (!addLaunchedModule(currentAtlFile)) {
			return;
		}

		InputStream asmInputStream = currentAtlFile.getContents();
		InputStream[] modules = new InputStream[superimps.size() + 1];
		modules[0] = asmInputStream;
		for (int i = 1; i < modules.length; i++) {
			String moduleFileName = superimps.get(i - 1);
			IFile moduleFile = ResourcesPlugin.getWorkspace().getRoot().getFile(
					getBytecodePath(moduleFileName, launcher));
			if (!addLaunchedModule(moduleFile)) {
				return;
			}
			modules[i] = moduleFile.getContents();
		}

		// Libraries
		Map<String, InputStream> libraries = new HashMap<String, InputStream>();
		for (Iterator<String> i = libs.keySet().iterator(); i.hasNext();) {
			String libName = i.next();
			IFile libFile = ResourcesPlugin.getWorkspace().getRoot().getFile(
					Path.fromOSString(libs.get(libName)));
			if (!addLaunchedModule(libFile)) {
				return;
			}
			libraries.put(libName, libFile.getContents());
		}

		// check for cancellation
		if (monitor.isCanceled()) {
			return;
		}

		Map<String, String> sourceModels = unsortedSourceModels;
		List<String> orderedInput = configuration.getAttribute(ATLLaunchConstants.ORDERED_INPUT,
				Collections.<String> emptyList());
		if (!orderedInput.isEmpty()) {
			sourceModels = sort(unsortedSourceModels, orderedInput);
		}

		Map<String, String> targetModels = unsortedTargetModels;
		List<String> orderedOutput = configuration.getAttribute(ATLLaunchConstants.ORDERED_OUTPUT,
				Collections.<String> emptyList());
		if (!orderedOutput.isEmpty()) {
			targetModels = sort(unsortedTargetModels, orderedOutput);
		}

		if (isRefiningTraceMode) {
			/*
			 * TODO: improve ATL header syntax to recognize inout models. Apply those changes to launch
			 * config. Current workaround: refined models list must match output models list to be saved, with
			 * respect to the declaration order.
			 */
			Iterator<String> sourceIterator = sourceModels.keySet().iterator();
			Iterator<String> targetIterator = targetModels.keySet().iterator();

			Map<String, String> newTargetModels = new HashMap<String, String>();
			newTargetModels.putAll(targetModels);
			List<String> targetToRemove = new ArrayList<String>();

			while (sourceIterator.hasNext()) {
				String sourceModelName = sourceIterator.next();
				String sourceMetamodelName = sourceModels.get(sourceModelName);

				// Lookup for a matching target model (same metamodel)
				while (targetIterator.hasNext()) {
					String targetModelName = targetIterator.next();
					String targetMetamodelName = targetModels.get(targetModelName);

					// Ignore previously used target models
					if (targetMetamodelName.equals(sourceMetamodelName)
							&& !targetToRemove.contains(targetModelName)) {
						String targetModelPath = modelPaths.get(targetModelName);

						// Compute the inout model path (for extraction)
						String refinedModelPathName = LauncherService.getRefinedModelName(sourceModelName);
						modelPaths.put(refinedModelPathName, targetModelPath);
						targetToRemove.add(targetModelName);
						break;
					}
				}
			}

			for (String key : targetToRemove) {
				newTargetModels.remove(key);
			}

			launchOrDebug(mode, monitor, launcher, Collections.<String, String> emptyMap(), sourceModels, newTargetModels,
					modelPaths, options, libraries, launch, modules);
		} else {
			launchOrDebug(mode, monitor, launcher, sourceModels, Collections.<String, String> emptyMap(), targetModels,
					modelPaths, options, libraries, launch, modules);
		}

		if (LauncherService.getBooleanOption(options.get(AdvancedTab.OPTION_DERIVED), false)) {
			// Set generated files as derived
			for (String targetModel : targetModels.keySet()) {
				String path = launchConfigModelPaths.get(targetModel);
				setDerived(path, monitor);
			}
		}

	}

	private IPath getBytecodePath(String fileName, final ILauncher launcher) {
		if (launcher != null && launcher.getClass().getSimpleName().startsWith("EMFTVM")) { //$NON-NLS-1$
			fileName = fileName.replaceAll("\\.(atl|asm)$", ".emftvm"); //$NON-NLS-1$ //$NON-NLS-2$
		}
		return Path.fromOSString(fileName);
	}

	private static Object launchOrDebug(final String mode, final IProgressMonitor monitor,
			final ILauncher launcher, final Map<String, String> sourceModels,
			final Map<String, String> sourceTargetModels, final Map<String, String> targetModels,
			final Map<String, String> modelPaths, final Map<String, Object> options,
			final Map<String, InputStream> libraries, ILaunch launchParam, final InputStream... modules) {
		final String realMode;
		if (!Arrays.asList(launcher.getModes()).contains(mode)) {
			ATLLogger.info(Messages.getString(
					"AtlLaunchConfigurationDelegate.UNSUPPORTED_MODE", mode, launcher.getName())); //$NON-NLS-1$
			realMode = ILauncher.RUN_MODE;
		} else {
			realMode = mode;
		}
		/*
		 * If the mode chosen was Debug, an ATLDebugTarget was created
		 */
		if (realMode.equals(ILaunchManager.DEBUG_MODE)) {
			launchParam.setSourceLocator(new AtlSourceLocator());
			final AtlDebugTarget mTarget = new AtlDebugTarget(launchParam);
			Thread th = new Thread() {
				@Override
				public void run() {
					try {
						LauncherService.launch(realMode, monitor, launcher, sourceModels, sourceTargetModels,
								targetModels, modelPaths, options, libraries, modules);
					} catch (ATLCoreException e) {
						ATLLogger.severe(e.getMessage());
						return;
					} catch (ATLExecutionException e) {
						ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
					} finally {
						monitor.done();
					}
				}
			};
			th.start();

			mTarget.setStopInMain(LauncherService.getBooleanOption(options
					.get(ATLLaunchConstants.STOP_IN_MAIN), false));
			mTarget.start();
			launchParam.addDebugTarget(mTarget);

		} else {

			// Run mode
			launchParam.setSourceLocator(new AtlSourceLocator());
			AtlRunTarget mTarget = new AtlRunTarget(launchParam);
			launchParam.addDebugTarget(mTarget);
			try {
				LauncherService.launch(realMode, monitor, launcher, sourceModels, sourceTargetModels,
						targetModels, modelPaths, options, libraries, modules);
				mTarget.terminate();
			} catch (ATLCoreException e) {
				ATLLogger.severe(e.getMessage());
				return null;
			} catch (DebugException e) {
				ATLLogger.severe(e.getMessage());
				return null;
			} catch (ATLExecutionException e) {
				ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
			} finally {
				monitor.done();
			}
		}
		return null;
	}

	private static Map<String, String> sort(Map<String, String> mapToSort, List<String> orderedKeys) {
		Map<String, String> res = new LinkedHashMap<String, String>();
		for (String key : orderedKeys) {
			res.put(key, mapToSort.get(key));
		}
		return res;
	}

	private static boolean addLaunchedModule(IFile file) {
		if (!file.exists()) {
			ATLLogger.severe(Messages.getString(
					"AtlLaunchConfigurationDelegate.FILE_NOT_EXIST", file.getFullPath())); //$NON-NLS-1$
			return false;
		}
		IFile atlFile = file;
		String ext = atlFile.getFileExtension().toLowerCase();
		if (ext.equals("asm")) { //$NON-NLS-1$
			String path = atlFile.getFullPath().toString().substring(0,
					atlFile.getFullPath().toString().length() - ext.length())
					+ "atl"; //$NON-NLS-1$
			atlFile = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(path));
		}
		if (atlFile.isAccessible()) {
			moduleFilesByModuleName.put(computeModuleName(file), atlFile);
		}
		return true;
	}

	/**
	 * Returns the file matching the given module name.
	 * 
	 * @param moduleName
	 *            the module name
	 * @return the file
	 */
	public static IFile getFileFromModuleName(String moduleName) {
		if (moduleFilesByModuleName != null) {
			return moduleFilesByModuleName.get(moduleName);
		}
		return null;
	}

	private static String computeModuleName(IFile file) {
		String res = file.getName();
		try {
			InputStreamReader streamReader = new InputStreamReader(file.getContents());
			BufferedReader buffer = new BufferedReader(streamReader);
			String line = ""; //$NON-NLS-1$
			while (null != (line = buffer.readLine())) {
				if (line.contains("<constant value=")) { //$NON-NLS-1$
					res = line.split("\\\"")[1]; //$NON-NLS-1$
					buffer.close();
					streamReader.close();
					return res;
				}
			}
			buffer.close();
			streamReader.close();
		} catch (Throwable e) {
			// DO NOTHING
		}
		return res;
	}

	/**
	 * Convert model map paths.
	 * 
	 * @param modelPaths
	 *            the model path map
	 * @return the converted map
	 */
	public static Map<String, String> convertPaths(Map<String, String> modelPaths) {
		Map<String, String> result = new HashMap<String, String>();
		for (Iterator<String> iterator = modelPaths.keySet().iterator(); iterator.hasNext();) {
			String modelName = iterator.next();
			String modelPath = modelPaths.get(modelName);
			result.put(modelName, convertPath(modelPath));
		}
		return result;
	}

	/**
	 * Convert "launch configuration style" paths to EMF uris:
	 * <ul>
	 * <li>ext:<i>path</i> => file:<i>path</i> (file system resource)</li>
	 * <li>uri:<i>uri</i> => <i>uri</i> (EMF uri)</li>
	 * <li><i>path</i> => platform:/resource/<i>path</i> (workspace resource)</li>
	 * </ul>
	 * Unchanged paths:
	 * <ul>
	 * <li>platform:/plugin/<i>path</i> (plugin resource)</li>
	 * <li>pathmap:<i>path</i> (pathmap resource, e.g. UML2 profile)</li>
	 * </ul>
	 * 
	 * @param path
	 *            the path as created by the launchConfiguration
	 * @return the converted path
	 */
	public static String convertPath(String path) {
		if (path.startsWith("ext:")) { //$NON-NLS-1$
			return path.replaceFirst("ext:", "file:/"); //$NON-NLS-1$ //$NON-NLS-2$
		} else if (path.startsWith("uri:")) { //$NON-NLS-1$
			return path.substring(4);
		} else if (path.startsWith("#") || path.startsWith("platform:") || path.startsWith("pathmap")) { //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			return path;
		}
		return "platform:/resource" + path; //$NON-NLS-1$
	}

	private void setDerived(String filePath, IProgressMonitor monitor) {
		if (Platform.isRunning()) {
			try {
				IFile file = ResourcesPlugin.getWorkspace().getRoot().getFile(new Path(filePath));
				if (file.exists()) {
					file.setDerived(true, monitor);
				}
			} catch (IllegalStateException e) {
				ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
			} catch (CoreException e) {
				ATLLogger.log(Level.SEVERE, e.getLocalizedMessage(), e);
			}
		}
	}

	/**
	 * Shows the profiler views for a profiler VM.
	 * 
	 * @param launcherName
	 *            the launcher name (the VM id)
	 */
	private void showViewsForProfiler(String launcherName) {
		boolean isProfilerVm = false;
		// The launcher name tells us if this is a profiler VM
		for (String profilerVMId : PROFILER_VM_IDS) {
			if (launcherName.equals(profilerVMId))
				isProfilerVm = true;
		}
		if (!isProfilerVm)
			return;
		// We show the profiler views
		PlatformUI.getWorkbench().getDisplay().syncExec(new Runnable() {
			public void run() {
				IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
				String rulesViewId = "org.eclipse.m2m.atl.profiler.ui.profilingdatatable.ProfilingDataTableView"; //$NON-NLS-1$
				String executionViewId = "org.eclipse.m2m.atl.profiler.ui.executionviewer.view.ExecutionView"; //$NON-NLS-1$
				if (window != null) {
					if (window.getActivePage().findView(rulesViewId) == null
							|| window.getActivePage().findView(executionViewId) == null) {
						MessageDialog dialog = new MessageDialog(
								null,
								Messages.getString("AtlLaunchConfigurationDelegate.PROFILER_WINDOW_TITLE"), null, Messages.getString("AtlLaunchConfigurationDelegate.PROFILER_WINDOW_MSG"), //$NON-NLS-1$ //$NON-NLS-2$
								MessageDialog.QUESTION,
								new String[] {
										Messages.getString("AtlLaunchConfigurationDelegate.PROFILER_WINDOW_YES"), Messages.getString("AtlLaunchConfigurationDelegate.PROFILER_WINDOW_NO"),}, 0); //$NON-NLS-1$ //$NON-NLS-2$
						// TODO keep user's answer in preferences (add "Always" and "Never" buttons)
						int result = dialog.open();
						if (result == 1)
							return;
					}
					try {
						if (window.getActivePage().findView(rulesViewId) == null)
							window.getActivePage().showView(rulesViewId);
					} catch (PartInitException e1) {
						// The view is not found
					}
					try {
						if (window.getActivePage().findView(executionViewId) == null)
							window.getActivePage().showView(executionViewId);
					} catch (PartInitException e1) {
						// The view is not found
					}
				}
			}
		});
		return;
	}

}

Back to the top