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

import static org.eclipse.papyrus.infra.ui.resources.Activator.log;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
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.OperationCanceledException;
import org.eclipse.core.runtime.Path;
import org.eclipse.core.runtime.SubProgressMonitor;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature;
import org.eclipse.emf.ecore.EStructuralFeature.Setting;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.URIConverter;
import org.eclipse.emf.ecore.util.ECrossReferenceAdapter;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.ltk.core.refactoring.Change;
import org.eclipse.ltk.core.refactoring.RefactoringStatus;
import org.eclipse.ltk.core.refactoring.resource.RenameResourceChange;
import org.eclipse.osgi.util.NLS;
import org.eclipse.papyrus.infra.core.modelsetquery.IModelSetQueryAdapter;
import org.eclipse.papyrus.infra.core.modelsetquery.ModelSetQuery;
import org.eclipse.papyrus.infra.core.resource.ModelSet;
import org.eclipse.papyrus.infra.core.resource.ModelsReader;
import org.eclipse.papyrus.infra.core.resource.ReadOnlyAxis;
import org.eclipse.papyrus.infra.core.resource.sasheditor.DiModelUtils;
import org.eclipse.papyrus.infra.core.resource.sasheditor.SashModel;
import org.eclipse.papyrus.infra.core.resource.sasheditor.SashModelUtils;
import org.eclipse.papyrus.infra.core.services.ServiceException;
import org.eclipse.papyrus.infra.emf.readonly.ReadOnlyManager;
import org.eclipse.papyrus.infra.emf.utils.EMFHelper;
import org.eclipse.papyrus.infra.emf.utils.ResourceUtils;
import org.eclipse.papyrus.infra.services.controlmode.mm.history.ControledResource;
import org.eclipse.papyrus.infra.services.controlmode.mm.history.historyPackage;
import org.eclipse.papyrus.infra.ui.editor.IMultiDiagramEditor;
import org.eclipse.papyrus.infra.ui.resources.Activator;
import org.eclipse.papyrus.infra.ui.util.EditorUtils;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.part.FileEditorInput;

/**
 * Rename the model.<BR>
 * <b>Note</b>: That change should be called inside a rename operation as it assumes that a {@link RenameResourceChange} occured.
 *
 * @author tszadel
 *
 */
public class RenameModelChange extends Change {

	private final Map<URI, URI> uriMap = new HashMap<URI, URI>();

	private final IFile oldFile;

	private final IFile newFile;

	private final Set<IResource> relatedFiles;

	private final Collection<? extends IResource> impacted;

	private TransactionalEditingDomain domain;

	private ModelSet resourceSet;

	private List<IMultiDiagramEditor> openedEditors;

	private boolean isUndoOperation;

	/**
	 * Constructor.
	 *
	 * @param resourceSet
	 *            The resource set being changed.
	 * @param oldFile
	 *            The old file.
	 * @param newFile
	 *            The new file.
	 * @param impacted
	 */
	public RenameModelChange(IFile oldFile, IFile newFile, Collection<? extends IResource> impacted) {
		this.oldFile = oldFile;
		this.newFile = newFile;
		this.impacted = impacted;

		IPath newPathWithoutExt = newFile.getFullPath().removeFileExtension();

		// Create the map of URI that are being modified in the resource set
		relatedFiles = ModelParticipantHelpers.getRelatedFiles(oldFile);
		relatedFiles.add(oldFile);

		for (IResource iResource : relatedFiles) {
			IPath path = iResource.getFullPath();
			URI oldURI = getPlatformURI(path);
			URI newURI = getPlatformURI(newPathWithoutExt.addFileExtension(path.getFileExtension()));
			uriMap.put(oldURI, newURI);
		}
	}

	/**
	 * Overrides getModifiedElement.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ltk.core.refactoring.Change#getModifiedElement()
	 */
	@Override
	public Object getModifiedElement() {
		return oldFile;
	}

	/**
	 * Overrides getName.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ltk.core.refactoring.Change#getName()
	 */
	@Override
	public String getName() {
		return NLS.bind(Messages.RenameModelChange_Name, oldFile.getName());
	}

	/**
	 * Overrides initializeValidationData.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ltk.core.refactoring.Change#initializeValidationData(org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public void initializeValidationData(IProgressMonitor pm) {
		// Nothing
	}

	/**
	 * Overrides isValid.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ltk.core.refactoring.Change#isValid(org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public RefactoringStatus isValid(IProgressMonitor pm) throws CoreException, OperationCanceledException {
		// That change assumes that the model resource has already been renamed
		// So, the first thing to do is to get the new file, to restore it in order
		// to change all the resources.
		pm.subTask(Messages.RenameModelChange_LoadingEMF);

		pm.subTask(Messages.RenameModelChange_DaveDirtyEditor);
		// We need to get the current workbench... so we have to use the UI-Thread!
		openedEditors = new ArrayList<IMultiDiagramEditor>();
		Display.getDefault().syncExec(new Runnable() {

			public void run() {
				IMultiDiagramEditor[] multiEditors = EditorUtils.getRelatedEditors(oldFile);
				if (multiEditors != null && multiEditors.length > 0) {
					for (IMultiDiagramEditor editor : multiEditors) {
						if (editor.isDirty()) {
							editor.doSave(new NullProgressMonitor());
						}
						openedEditors.add(editor);
					}
				}
			}
		});
		pm.worked(10);

		/*
		 * Load ModelSet
		 */
		resourceSet = new ModelSet();
		try {
			ModelsReader reader = new ModelsReader();
			reader.readModel(resourceSet);
			resourceSet.loadModels(oldFile);
			for (IResource r : impacted) {
				if (r instanceof IFile) {
					IFile file = (IFile) r;
					try {
						resourceSet.getResource(URI.createPlatformResourceURI(file.getFullPath().toString(), true), true);
					} catch (Exception e) {
						// to avoid load errors
					}
				}
			}
		} catch (Exception e) {
			Activator.log.error(e);
		}

		// Force EMF resolve and load all the resources
		try {
			EcoreUtil.resolveAll(resourceSet);
		} catch (Exception ex) {
			// the resolve all does not have to break the operation
		}

		pm.worked(4);
		domain = resourceSet.getTransactionalEditingDomain();

		// TODO improve when impact analysis will be effective
		return manageResourceSet(pm, resourceSet);
	}

	/**
	 * Get a platform resource URI of the given path
	 *
	 * @param path
	 *            the path
	 * @return the uri
	 */
	private URI getPlatformURI(IPath path) {
		return URI.createPlatformResourceURI(path.toString(), true);
	}

	/**
	 * Overrides perform.
	 *
	 * {@inheritDoc}
	 *
	 * @see org.eclipse.ltk.core.refactoring.Change#perform(org.eclipse.core.runtime.IProgressMonitor)
	 */
	@Override
	public Change perform(IProgressMonitor pm) throws CoreException {

		String lMsg = NLS.bind(Messages.RenameModelChange_Change, oldFile.getName(), newFile.getName());
		isUndoOperation = oldFile.exists() && !newFile.exists();

		if (!isUndoOperation) {
			// The file has already been renamed. Undo the rename change, then do the full refactoring in the resource set
			newFile.move(oldFile.getFullPath(), true, new SubProgressMonitor(pm, 1));
		}

		Set<IResource> revertImpactedFiles = getRevertImpactedResources();

		pm.beginTask(lMsg, 30);
		try {
			doRun(pm, resourceSet, domain);
			// Now, save all the resources
			pm.subTask(Messages.RenameModelChange_savingResource);
			for (Resource res : resourceSet.getResources()) {
				if (res.getURI().isPlatformResource()) {
					try {
						if (res.isModified()) {
							res.save(ResourceUtils.getSaveOptions());
						}
					} catch (Exception e) {
						log.error(NLS.bind(Messages.RenameModelChange_ErrorLoading, res.getURI()), e);
					}
				}
			}
			pm.worked(5);


			try {
				SashModel oldSash = SashModelUtils.getSashModel(resourceSet);
				URI oldSashURI = oldSash.getResourceURI();
				Resource resource = oldSash.getResource();
				resourceSet.loadModels(newFile);
				SashModel sashModel = SashModelUtils.getSashModel(resourceSet);
				URI stashNewFile = sashModel.getResourceURI();
				resource.setURI(stashNewFile);
				resource.save(ResourceUtils.getSaveOptions());
				if(oldSash != null) { // delete old stash
					try {
						resourceSet.getURIConverter().delete(oldSashURI, null);
					} catch (IOException e) {
						log.error(Messages.bind(Messages.RenameModelChange_ErrorLoading, oldSashURI), e);
					}
				}
			} catch (Exception e) {
				log.error(e);
			}

			// Do not forget to unload all the resources to avoid memory leak
			pm.subTask(Messages.RenameModelChange_Unloading);
			resourceSet.unload();
			pm.worked(1);

			// Now, notify the editor of the change
			if (!openedEditors.isEmpty()) {
				Display.getDefault().syncExec(new Runnable() {

					public void run() {
						// Get the DI file as the rename could occur on any model's file.
						IFile newDiFile = DiModelUtils.getRelatedDiFile(newFile);
						for (IMultiDiagramEditor editor : openedEditors) {
							try {
								ModelSet diRes = editor.getServicesRegistry().getService(ModelSet.class);
								if (diRes != null) {
									diRes.saveAs(newFile.getFullPath());
								}
								editor.setEditorInput(new FileEditorInput(newDiFile));

							} catch (ServiceException e) {
								log.error(e);
							} catch (IOException e) {
								log.error(e);
							}
						}
					}
				});
			}

			// Then, remove the old model files
			pm.subTask(Messages.RenameModelChange_RemoveOldFile);
			for (IResource iResource : relatedFiles) {
				if (iResource.exists()) {
					IPath path = iResource.getFullPath();
					URI oldURI = getPlatformURI(path);
					URI newURI = uriMap.get(oldURI);
					URIConverter uriConverter = resourceSet.getURIConverter();
					if (uriConverter.exists(newURI, Collections.EMPTY_MAP)) {
						iResource.delete(true, new NullProgressMonitor());
					}
				}
			}
			pm.worked(4);

			RenameModelChange undoChange = new RenameModelChange(newFile, oldFile, revertImpactedFiles);

			if (isUndoOperation) {
				// Restore the expected state for the basic rename change
				newFile.move(oldFile.getFullPath(), true, new SubProgressMonitor(pm, 1));
			}

			// Invert the change
			return undoChange;
		} finally {
			pm.done();
		}
	}

	private Set<IResource> getRevertImpactedResources() {
		Set<IResource> result = new HashSet<IResource>();

		Set<IResource> relatedFiles = ModelParticipantHelpers.getRelatedFiles(oldFile);
		relatedFiles.add(oldFile);

		for (IResource initialResource : impacted) {
			if (relatedFiles.contains(initialResource)) {
				IResource invertedResource = invertFileName(initialResource);
				result.add(invertedResource); // Participant model (the file is renamed)
			} else {
				result.add(initialResource); // Client model (only links are modified)
			}
		}

		return result;
	}

	private IResource invertFileName(IResource initialResource) {
		String newName;

		IPath pathWithoutExtension = newFile.getFullPath().removeFileExtension();
		IPath pathWithExtension = pathWithoutExtension.addFileExtension(initialResource.getFileExtension());
		newName = pathWithExtension.lastSegment();

		IFile newFile = oldFile.getParent().getFile(new Path(newName));

		return newFile;
	}

	private RefactoringStatus manageResourceSet(final IProgressMonitor pm, final ModelSet resourceSet) {

		final Collection<Resource> readOnlies = new HashSet<Resource>();
		// for each object of the resources renamed, the refactor will search if a resource is read only or not
		domain.getCommandStack().execute(new RecordingCommand(domain) {

			@Override
			protected void doExecute() {

				// got though resources, to find if a resources that reference one of uri map is read only
				for (URI uri : uriMap.keySet()) {
					Resource r = resourceSet.getResource(uri, false);
					ECrossReferenceAdapter adapter = ECrossReferenceAdapter.getCrossReferenceAdapter(resourceSet);
					if (adapter == null) {
						adapter = new ECrossReferenceAdapter();
						adapter.setTarget(resourceSet);
					}
					if (r != null) {
						for (Iterator<EObject> i = EcoreUtil.getAllProperContents(r, false); i.hasNext();) {
							EObject e = i.next();

							// look for all references where e is playing
							Collection<Setting> references = adapter.getInverseReferences(e);
							for (Setting s : references) {
								// get the EObject that play with e
								EObject eObject = s.getEObject();

								// this is the same resource --> not interesting
								if ((eObject.eResource() != null) && !(eObject.eResource().equals(e.eResource()))) {
									// this is a external resource that references uri map
									// if not not interesting
									EStructuralFeature eFeature = s.getEStructuralFeature();

									if ((!eFeature.isDerived()) && (eObject.eClass().getEAllStructuralFeatures().contains(eFeature))) {
										if (eObject.eResource() != null && EMFHelper.isReadOnly(eObject.eResource(), domain)) {
											boolean isWritable = EMFHelper.canMakeWritable(eObject.eResource(), domain);
											if (isWritable) {
												readOnlies.add(eObject.eResource());
											}
										}
									}
								}
							}
						}
					}
				}
			}

		});
		// if read only => error to the user
		if (!readOnlies.isEmpty()) {
			ReadOnlyManager readOnlyManager = new ReadOnlyManager(domain);
			Collection<URI> uris = new ArrayList<URI>();
			for (Iterator<Resource> iterator = readOnlies.iterator(); iterator.hasNext();) {
				Resource r = iterator.next();
				uris.add(r.getURI());
			}

			readOnlyManager.makeWritable(ReadOnlyAxis.anyAxis(), uris.toArray(new URI[uris.size()]));
		}
		return new RefactoringStatus();

	}

	private void doRun(final IProgressMonitor pm, final ModelSet resourceSet, final TransactionalEditingDomain domain) {
		domain.getCommandStack().execute(new RecordingCommand(domain) {

			@Override
			protected void doExecute() {
				// Manage Controlled map to ensure consistent history
				// TODO change this code when history will be useless
				URI modifiedURI = URI.createPlatformResourceURI(oldFile.getFullPath().removeFileExtension().toString(), true);
				IModelSetQueryAdapter controledResourcesAdapter = ModelSetQuery.getExistingTypeCacheAdapter(resourceSet);
				if (controledResourcesAdapter != null) {
					EObject first = null;
					for (Iterator<Notifier> i = resourceSet.getAllContents(); i.hasNext();) {
						Notifier n = i.next();
						if (n instanceof EObject) {
							first = (EObject) n;
							break;
						}
					}
					if (first != null) {
						Collection<EObject> resources = null;
						try {
							resources = controledResourcesAdapter.getReachableObjectsOfType(first, historyPackage.Literals.CONTROLED_RESOURCE);
						} catch (RuntimeException e) {
							// in case of errors integrity must be valid
							// even performances are bad
							resources = new LinkedList<EObject>();
							for (int i = 0; i < resourceSet.getResources().size(); i++) {
								Resource r = resourceSet.getResources().get(i);
								for (Iterator<EObject> it = r.getAllContents(); it.hasNext();) {
									EObject tmp = it.next();
									if (tmp instanceof ControledResource) {
										ControledResource controled = (ControledResource) tmp;
										resources.add(controled);
									}
								}
							}
						}
						for (EObject e : resources) {
							if (e instanceof ControledResource) {
								ControledResource controled = (ControledResource) e;
								URI baseURI = URI.createURI(e.eResource().getURI().trimSegments(1).trimFragment().toString() + "/");
								URI resolvedURI = URI.createURI(controled.getResourceURL()).resolve(baseURI);
								if (resolvedURI.trimFileExtension().equals(modifiedURI.trimFileExtension())) {
									String ext = resolvedURI.fileExtension();
									URI newURL = URI.createURI(resolvedURI.trimSegments(1).toString() + "/" + newFile.getFullPath().removeFileExtension().lastSegment().toString() + "." + ext);
									controled.setResourceURL(newURL.deresolve(baseURI).toString());
								}
							}
						}
					}
				}
			}
		});
		// Change the uri of the files
		pm.subTask(Messages.RenameModelChange_ModifyURI);
		for (Resource res : resourceSet.getResources()) {
			if (res.getURI().isPlatformResource()) {
				URI newURI = uriMap.get(res.getURI());
				if (newURI != null) {
					if (log.isDebugEnabled()) {
						log.debug(NLS.bind(Messages.RenameModelChange_6, Arrays.asList(res.getURI(), newURI)));
					}
					res.setURI(newURI);
				}
			}

		}
		pm.worked(5);


	}
}

Back to the top