Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 4944ada079309f0d87364d18224031e2e3a8e794 (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
/*****************************************************************************
 * Copyright (c) 2011, 2014 Atos Origin, CEA, and others.
 *
 *
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *  Vincent Hemery (Atos) vincent.hemery@atos.net - Initial API and implementation
 *  Christian W. Damus (CEA) - bug 415639
 *
 *****************************************************************************/
package org.eclipse.papyrus.infra.services.resourceloading.util;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.gef.EditPart;
import org.eclipse.gef.GraphicalEditPart;
import org.eclipse.gef.util.EditPartUtilities;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramGraphicalViewer;
import org.eclipse.gmf.runtime.notation.Diagram;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.papyrus.infra.core.resource.ModelSet;
import org.eclipse.papyrus.infra.core.resource.sasheditor.DiModel;
import org.eclipse.papyrus.infra.core.sashwindows.di.service.IPageManager;
import org.eclipse.papyrus.infra.core.services.ServiceException;
import org.eclipse.papyrus.infra.gmfdiag.common.model.NotationModel;
import org.eclipse.papyrus.infra.services.resourceloading.Activator;
import org.eclipse.papyrus.infra.services.resourceloading.Messages;
import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
import org.eclipse.papyrus.infra.ui.util.TransactionUIHelper;
import org.eclipse.papyrus.infra.widgets.toolbox.notification.Type;
import org.eclipse.papyrus.infra.widgets.toolbox.notification.builders.NotificationBuilder;
import org.eclipse.papyrus.uml.tools.model.UmlModel;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IWorkbenchSiteProgressService;
import org.eclipse.ui.statushandlers.StatusManager;

/**
 * This class provides utility methods for model loading
 *
 * @author vhemery
 */
public class LoadingUtils {

	/**
	 * Load corresponding resources in model set for all its existing models.
	 *
	 * @param modelSet
	 *            the model set
	 * @param uriWithoutFileExtension
	 *            path of resources to load without file extension
	 */
	public static void loadResourcesInModelSet(final ModelSet modelSet, final URI uriWithoutFileExtension) {
		final IEditorPart editor = getEditor();
		if (editor instanceof IMultiDiagramEditor) {
			// This must be created on the UI thread
			final NotificationBuilder error = NotificationBuilder.createAsyncPopup(Messages.LoadingUtils_ErrorTitle, String.format(Messages.LoadingUtils_ErrorMessage, uriWithoutFileExtension.toString())).setType(Type.ERROR).setDelay(2000);

			runInEditingDomain(modelSet.getTransactionalEditingDomain(), editor, new IRunnableWithProgress() {

				public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {
					try {
						IMultiDiagramEditor core = (IMultiDiagramEditor) editor;
						try {
							IPageManager pageMngr = core.getServicesRegistry().getService(IPageManager.class);
							List<Object> allPages = pageMngr.allPages();
							// mark progress
							monitor.beginTask(Messages.LoadingUtils_RefreshPagesTask, allPages.size());
							// the uri is added after getting all the pages. If it is done before, the eobjects are resolved
							for (Object o : allPages) {
								// refresh pages to display proxy diagrams
								if (o instanceof EObject) {
									EObject eobject = (EObject) o;
									if (eobject.eIsProxy()) {
										InternalEObject internal = (InternalEObject) eobject;
										URI uriProxy = internal.eProxyURI();
										URI trimFragment = uriProxy.trimFragment();
										if (uriWithoutFileExtension.equals(trimFragment.trimFileExtension())) {
											try {
												Resource r = modelSet.getResource(trimFragment, true);
												if (r != null) {
													EObject newEObject = r.getEObject(uriProxy.fragment());
													if (pageMngr.isOpen(newEObject)) {
														pageMngr.selectPage(newEObject);
													}
												} else {
													error.run();
												}
											} catch (Exception e) {
												error.run();
												Activator.logError(e);
											}
										}
									}
								}
								// mark progress
								monitor.worked(1);
							}
							Set<String> extensions = getExtensions(modelSet);
							// mark progress
							monitor.beginTask(Messages.LoadingUtils_LoadModelsTask, extensions.size());
							for (String s : extensions) {
								try {
									URI uriToLoad = uriWithoutFileExtension.appendFileExtension(s);
									Resource r = modelSet.getResource(uriToLoad, true);
									if (r == null) {
										error.run();
									}
								} catch (Exception re) {
									error.run();
									Activator.logError(re);
								}
								// mark progress
								monitor.worked(1);
							}
						} catch (ServiceException e) {
							Activator.logError(e);
						}
					} finally {
						// mark progress
						monitor.done();
					}
				}
			});
		}
	}

	/**
	 * Unload corresponding resources from model set for all its existing models.
	 *
	 * @param modelSet
	 *            the model set
	 * @param uriWithoutFileExtension
	 *            path of resources to unload without file extension
	 */
	public static void unloadResourcesFromModelSet(ModelSet modelSet, URI uriWithoutFileExtension) {
		unloadResourcesFromModelSet(modelSet, uriWithoutFileExtension, false);
	}

	/**
	 * Unload corresponding resources from model set for all its existing models.
	 *
	 * @param modelSet
	 *            the model set
	 * @param uriWithoutFileExtension
	 *            path of resources to unload without file extension
	 * @param refreshDiagramsWithProxies
	 *            true if we must refresh necessary diagrams, false to skip it.
	 */
	public static void unloadResourcesFromModelSet(final ModelSet modelSet, final URI uriWithoutFileExtension, final boolean refreshDiagramsWithProxies) {
		final IEditorPart editor = getEditor();
		if (editor instanceof IMultiDiagramEditor) {
			runInEditingDomain(modelSet.getTransactionalEditingDomain(), editor, new IRunnableWithProgress() {

				public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException {

					try {
						IMultiDiagramEditor core = (IMultiDiagramEditor) editor;
						try {
							IPageManager pageMngr = core.getServicesRegistry().getService(IPageManager.class);
							List<Object> allPages = pageMngr.allPages();
							List<URI> pagesURIToOpen = new ArrayList<URI>(allPages.size());
							List<URI> pagesURIToRefresh = new ArrayList<URI>(allPages.size());
							if (refreshDiagramsWithProxies) {
								// mark progress
								monitor.beginTask(Messages.LoadingUtils_RefreshPagesTask, allPages.size());
								for (Object o : allPages) {
									// refresh pages to cancel display of proxified elements
									if (o instanceof EObject) {
										EObject eobject = (EObject) o;
										if (!eobject.eIsProxy()) {
											URI trimFragment = eobject.eResource().getURI();
											String frag = eobject.eResource().getURIFragment(eobject);
											if (uriWithoutFileExtension.equals(trimFragment.trimFileExtension())) {
												// diagram was in unloaded resource. Refresh it.
												if (pageMngr.isOpen(eobject)) {
													pageMngr.closePage(eobject);
													pagesURIToOpen.add(trimFragment.appendFragment(frag));
												}
											} else if (pageMngr.isOpen(eobject)) {
												// diagram is still loaded but may display proxified elements
												pagesURIToRefresh.add(trimFragment.appendFragment(frag));
											}
										}
									}
									// mark progress
									monitor.worked(1);
								}
							}
							// mark progress
							monitor.beginTask(Messages.LoadingUtils_UnloadModelsTask, modelSet.getResources().size());

							// Use the platform string of a normalized URI for comparison below, see bug 372326
							// (registered libraries in the model set have different URIs - e.g. due to a pathmap -
							// although they point to the same location).
							// TODO: Use a single detection mechanism in ResourceUpdateService and here
							String unloadPlatformString;
							if (uriWithoutFileExtension.isPlatform()) {
								unloadPlatformString = uriWithoutFileExtension.toPlatformString(true);
							} else {
								unloadPlatformString = URI.decode(uriWithoutFileExtension.toString());
							}
							// URIConverter uriConverter = modelSet.getURIConverter();
							// unload resource
							for (Resource res : new ArrayList<Resource>(modelSet.getResources())) {
								URI normalizedURI = res.getURI();
								String platformString;
								if (normalizedURI.isPlatform()) {
									platformString = normalizedURI.trimFileExtension().toPlatformString(true);
								} else {
									platformString = URI.decode(normalizedURI.trimFileExtension().toString());
								}

								if ((platformString != null) && platformString.equals(unloadPlatformString)) {
									// unload this resource
									res.unload();
									// there is no need to remove it from the resource set (which inevitably
									// causes ConcurrentModificationExceptions!), especially as we may be
									// loading it again (the editor is still open)
								}
								// mark progress
								monitor.worked(1);
							}
							// // mark progress
							// monitor.beginTask("Resolve", 1);
							// EcoreUtil.resolveAll(modelSet);
							// monitor.worked(1);

							if (refreshDiagramsWithProxies) {
								// mark progress
								monitor.beginTask(Messages.LoadingUtils_RefreshPagesTask, allPages.size());
								// reopen pages from proxies and refresh necessary pages
								for (Object page : allPages) {
									if (page instanceof EObject) {
										EObject eobject = (EObject) page;
										if (eobject.eIsProxy()) {
											// reopen page from proxy if needed
											InternalEObject internal = (InternalEObject) eobject;
											URI uriProxy = internal.eProxyURI();
											if (pagesURIToOpen.contains(uriProxy)) {
												pageMngr.openPage(eobject);
											}
										} else if (eobject instanceof Diagram) {
											// refresh page's diagram if needed
											Diagram diag = ((Diagram) eobject);
											if (pageMngr.isOpen(diag)) {

												IDiagramGraphicalViewer graphicalViewer = core.getAdapter(IDiagramGraphicalViewer.class);
												if (graphicalViewer == null) {
													continue;
												}

												Object part = graphicalViewer.getEditPartRegistry().get(diag);
												if (part instanceof GraphicalEditPart) {
													// refresh nodes
													for (Object child : EditPartUtilities.getAllChildren((GraphicalEditPart) part)) {
														if (child instanceof EditPart) {
															((EditPart) child).refresh();
														}
													}
													// refresh edges
													for (Object child : EditPartUtilities.getAllNestedConnectionEditParts((GraphicalEditPart) part)) {
														if (child instanceof EditPart) {
															((EditPart) child).refresh();
														}
													}
												}
											}
										}
									}
									// mark progress
									monitor.worked(1);
								}
							}
						} catch (ServiceException e) {
							Activator.logError(e);
						}
					} finally {
						// mark progress
						monitor.done();
					}
				}
			});
		}
	}

	static void runInEditingDomain(TransactionalEditingDomain domain, IEditorPart editorContext, IRunnableWithProgress operation) {
		final IWorkbenchSiteProgressService progress = editorContext.getSite().getService(IWorkbenchSiteProgressService.class);

		try {
			progress.incrementBusy();
			progress.busyCursorWhile(TransactionUIHelper.createPrivilegedRunnableWithProgress(domain, operation));
		} catch (InterruptedException e) {
			Activator.log.error(e);
		} catch (InvocationTargetException e) {
			StatusManager.getManager().handle(new Status(IStatus.ERROR, Activator.PLUGIN_ID, "Failed to manage controlled resources.", e.getTargetException()), StatusManager.SHOW);
		} finally {
			progress.decrementBusy();
		}
	}

	/**
	 * Common extensions
	 * TODO get rid of listing all model's extensions and find a way to deduce them from model set. Then, delete this attribute.
	 *
	 * @see #getExtensions(ModelSet)
	 */
	private static final Set<String> COMMON_EXTENSIONS = new HashSet<String>();

	static {
		COMMON_EXTENSIONS.add(UmlModel.UML_FILE_EXTENSION);
		COMMON_EXTENSIONS.add(NotationModel.NOTATION_FILE_EXTENSION);
		COMMON_EXTENSIONS.add(DiModel.DI_FILE_EXTENSION);
	}

	/**
	 * Get list of file extensions existing for this model set
	 *
	 * @param modelSet
	 *            model set to find common extensions for
	 * @return extensions list to explore
	 */
	private static Set<String> getExtensions(ModelSet modelSet) {
		return COMMON_EXTENSIONS;
	}

	/**
	 * Get currently opened editor
	 *
	 * @return editor
	 */
	public static IEditorPart getEditor() {
		IEditorPart editor = null;
		IWorkbench workbench = PlatformUI.getWorkbench();
		if (workbench != null) {
			IWorkbenchWindow activeWorkbenchWindow = workbench.getActiveWorkbenchWindow();
			if (activeWorkbenchWindow != null) {
				IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
				if (activePage != null) {
					editor = activePage.getActiveEditor();
				}
			}
		}
		return editor;
	}

	/**
	 * Get File from a URI
	 *
	 * @param uri
	 *            the URI to transform
	 * @return the corresponding file
	 */
	public static IFile getFile(URI uri) {
		IPath path = getPath(uri);
		if (path != null) {
			return ResourcesPlugin.getWorkspace().getRoot().getFile(path);
		}
		return null;
	}

	/**
	 * Get Path from a URI
	 *
	 * @param uri
	 *            the URI to transform
	 * @return the corresponding path
	 */
	public static IPath getPath(URI uri) {
		String scheme = uri.scheme();
		IPath path = null;
		if ("platform".equals(scheme)) { //$NON-NLS-1$
			path = Path.fromPortableString(uri.toPlatformString(true));
		} else if ("file".equals(scheme)) { //$NON-NLS-1$
			path = Path.fromPortableString(uri.toFileString());
		}
		return path;
	}
}

Back to the top