Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: 364b388f94669f5cb1a732f0915451e4122835ee (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
/*******************************************************************************
 * Copyright (c) 2014 protos software gmbh (http://www.protos.de).
 * 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:
 * 		Henrik Rentz-Reichert (initial contribution)
 * 
 *******************************************************************************/

package org.eclipse.etrice.ui.common.base.editor;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.NullProgressMonitor;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EStructuralFeature.Setting;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.transaction.RunnableWithResult;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.etrice.core.fsm.fSM.ModelComponent;
import org.eclipse.etrice.core.fsm.ui.FSMUiModule;
import org.eclipse.etrice.ui.common.base.UIBaseActivator;
import org.eclipse.graphiti.mm.pictograms.Diagram;
import org.eclipse.graphiti.services.Graphiti;
import org.eclipse.graphiti.ui.editor.DiagramBehavior;
import org.eclipse.graphiti.ui.editor.DiagramEditor;
import org.eclipse.graphiti.ui.editor.EditorInputAdapter;
import org.eclipse.graphiti.ui.editor.IDiagramEditorInput;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.TrayDialog;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorSite;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.xtext.diagnostics.Severity;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.serializer.ISerializer;
import org.eclipse.xtext.ui.editor.XtextEditor;
import org.eclipse.xtext.util.CancelIndicator;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;
import org.eclipse.xtext.validation.CheckMode;
import org.eclipse.xtext.validation.IResourceValidator;
import org.eclipse.xtext.validation.Issue;

import com.google.common.collect.Lists;
import com.google.inject.Inject;
import com.google.inject.Injector;

/**
 * @author Henrik Rentz-Reichert
 *
 */
public abstract class DiagramEditorBase extends DiagramEditor implements IInputUriHolder {

	@Inject
	protected IResourceValidator resourceValidator;

	protected ModificationTrackingEnabler mte = new ModificationTrackingEnabler();
	protected URI inputUri;
	private Object textEditorClass;

	private SaveOnFocusLostListener saveOnFocusListener;

	private SuperClassListener superClassListener;

	public DiagramEditorBase(Object textEditorClass) {
		this.textEditorClass = textEditorClass;
		
		Injector injector = FSMUiModule.getInjector();
		injector.injectMembers(this);
		
		TrayDialog.setDialogHelpAvailable(false);
	}
	
	@Override
	protected DiagramBehavior createDiagramBehavior() {
		return new CustomDiagramBehavior(this);
	}

	@Override
	public void init(IEditorSite site, IEditorInput input) throws PartInitException {
		IEditorInput newInput = EditorInputAdapter.adaptToDiagramEditorInput(input);
		if (newInput instanceof IDiagramEditorInput)
			this.inputUri = ((IDiagramEditorInput) newInput).getUri();
		
		super.init(site, input);
	}

	@Override
	public void initializeGraphicalViewer() {
		super.initializeGraphicalViewer();
		
		ResourceSet resourceSet = getEditingDomain().getResourceSet();
		Map<EObject, Collection<Setting>> result = EcoreUtil.UnresolvedProxyCrossReferencer.find(resourceSet);
		if (!result.isEmpty())
			System.err.println("ERROR in diagram viewer: could not resolve all proxies!");
	
		mte.setTarget(getEditingDomain());
	}

	@Override
	public void doSave(final IProgressMonitor monitor) {
		boolean isValid = validateResourcesBeforeSave(monitor);
		if(isValid)
			super.doSave(monitor);
		// deactivate saveOnFocus for better usability
		// avoid retrigger loop from message box
		saveOnFocusListener.setActive(isValid);
	}
	
	protected boolean validateResourcesBeforeSave(final IProgressMonitor monitor){
		final TransactionalEditingDomain editingDomain = getEditingDomain();
		
		final RunnableWithResult<Boolean> runnable = new RunnableWithResult.Impl<Boolean>() {

			@Override
			public void run() {
				// copy list to avoid ConcurrentModification during serialize and validation
				final List<Resource> resources = Lists.newArrayList(editingDomain.getResourceSet().getResources());
				setResult(false);
				for(Resource res : resources){
					if(!validateResource(res, monitor))
						return;
				}
				
				setResult(true);
			}
			
		};
		
		try {
			return TransactionUtil.runExclusive(editingDomain, runnable);
		}
		catch (InterruptedException e) {
			MessageDialog.openError(Display.getDefault().getActiveShell(), "ERROR", "Internal error: could not save model:\n\n"+e.getMessage());
			UIBaseActivator.getDefault().getLog().log(new Status(Status.ERROR, UIBaseActivator.PLUGIN_ID, e.getMessage(), e));
	
			return false;
		}
	}
	
	protected boolean validateResource(Resource res, final IProgressMonitor monitor){
		if (res instanceof XtextResource) {
			if (!res.isLoaded()) {
				try {
					res.load(Collections.EMPTY_MAP);
				} catch (IOException e) {
					MessageDialog.openError(Display.getDefault().getActiveShell(), "ERROR", "Internal error: couldn't load referenced resource "+res.getURI());
					return false;
				}
			}
			if (res.isModified()) {

				XtextResource xres = (XtextResource) res;
				ISerializer serializer = xres.getSerializer();
				
				if (xres.getContents().isEmpty()) {
					MessageDialog.openError(Display.getDefault().getActiveShell(), "ERROR", "Internal error: part of textual model is empty, can't save");
					return false;
				}

				try {
					// HOWTO: call serializer to validate the concrete syntax
					// this throws an exception which is caught further up the stack
					// and a dialog will be displayed
					serializer.serialize(xres.getContents().get(0));
					
					List<Issue> result = resourceValidator.validate(res, CheckMode.NORMAL_AND_FAST, new CancelIndicator() {
						public boolean isCanceled() {
							return monitor.isCanceled();
						}
					});
					if (!result.isEmpty()) {
						boolean error = false;
						MultiStatus ms = new MultiStatus(UIBaseActivator.PLUGIN_ID, Status.ERROR, "validation errors during diagram save", null);
						for (Issue issue : result) {
							if (issue.isSyntaxError() || issue.getSeverity()==Severity.ERROR) {
								ms.add(new Status(Status.ERROR, UIBaseActivator.PLUGIN_ID, issue.getMessage()));
								error = true;
							}
						}
						if (error) {
							MessageDialog.openError(Display.getDefault().getActiveShell(), "ERROR", "Internal error: model is invalid, can't save");
							UIBaseActivator.getDefault().getLog().log(ms);
							return false;
						}
					}
				}
				catch (RuntimeException e) {
					MessageDialog.openError(Display.getDefault().getActiveShell(), "ERROR", "Internal error: model is invalid, can't save:\n\n"+e.getMessage());
					UIBaseActivator.getDefault().getLog().log(new Status(Status.ERROR, UIBaseActivator.PLUGIN_ID, e.getMessage(),e));
					return false;
				}
			}
		}
		
		return true;
	}
	
	/* (non-Javadoc)
	 * @see org.eclipse.graphiti.ui.editor.DiagramEditor#setFocus()
	 */
	@Override
	public void setFocus() {
		boolean dirtyAlready = isDirty();
		
		// inside this call auto refresh will happen if (and turn the editor dirty)
		super.setFocus();
		
		if (superClassListener.isChangeInSuperClass())
			superClassChanged();
		
		if (!dirtyAlready && isDirty())
			doSave(null);
		
		Diagram diagram = getDiagramTypeProvider().getDiagram();
		EObject diagramBo = diagram.getLink().getBusinessObjects().iterator().next();
		if(diagramBo == null || diagramBo.eIsProxy())
			handleMissingDiagramBo(diagram);
	}
	
	public ModelComponent getModelComponent() {
		Diagram diagram = getDiagramTypeProvider().getDiagram();
		EObject bo = Graphiti.getLinkService().getBusinessObjectForLinkedPictogramElement(diagram);
		if (bo instanceof ModelComponent)
			return (ModelComponent) bo;
		
		return null;
	}

	@Override
	public void dispose() {
		mte.unsetTarget(getEditingDomain());
	
		getSite().getPage().removePartListener(saveOnFocusListener);
		PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().removePartListener(superClassListener);
		superClassListener.dispose();
		
		super.dispose();
	}

	@Override
	public void createPartControl(Composite parent) {
			super.createPartControl(parent);
	
			saveOnFocusListener = new SaveOnFocusLostListener(this);
			getSite().getPage().addPartListener(saveOnFocusListener);
			
			superClassListener = new SuperClassListener(this, textEditorClass);
			PlatformUI.getWorkbench().getActiveWorkbenchWindow().getPartService().addPartListener(superClassListener);
			
			/* we have to save here whether changes have been done or not to get rid of the dirty state
			 * CAUTION: save in
			 * init(IEditorSite site, IEditorInput input)
			 * or
			 * setInput(IEditorInput input)
			 * did not work correctly
			 */
	//		if (AutoUpdateFeature.isLastDoneChanges())
				doSave(new NullProgressMonitor());
		}

	/**
	 * Check whether the given diagram editor manages a super class
	 * @param editor
	 * @return
	 */
	protected boolean registerSuperClassListener(DiagramEditorBase editor) {
		if (!(this.getClass().equals(editor.getClass()) && this.getModelComponent()!=null))
			return false;
		
		ModelComponent editorSc = editor.getModelComponent();
		if (editorSc!=null) {
			URI editorResURI = toCurrentPlatformURI(editorSc.eResource().getURI());
			
			ModelComponent base = getModelComponent();
			while((base = base.getBase()) != null){
				URI baseResURI = toCurrentPlatformURI(base.eResource().getURI());
				if(editorResURI.equals(baseResURI))
					if(editorSc.getComponentName().equals(base.getComponentName()))
						return true;
			}
		}
		
		return false;
	}

	/**
	 * Check whether the given room editor has a super class
	 * @param editor
	 * @return
	 */
	protected boolean registerSuperClassListener(XtextEditor editor) {
		if (!((Class<?>)textEditorClass).isInstance(editor))
			return false;
		if (this.getModelComponent()==null)
			return false;
		
		return editor.getDocument().readOnly(new IUnitOfWork<Boolean, XtextResource>(){
	
			@Override
			public Boolean exec(XtextResource resource) throws Exception {
				
				URI editorResURI = toCurrentPlatformURI(resource.getURI());
				URI thisScResURI = toCurrentPlatformURI(getModelComponent().eResource().getURI());
				
				// ignore if in same file (handled by graphiti)
				if(thisScResURI.equals(editorResURI))
					return false;
				
				ModelComponent base = getModelComponent();
				while((base = base.getBase()) != null){
					URI baseResURI = toCurrentPlatformURI(base.eResource().getURI());
					if(editorResURI.equals(baseResURI))
						return true;
				}
				
				return false;
			}
		});
	}

	private URI toCurrentPlatformURI(URI uri) {
		if(uri.isPlatform())
			return uri;
		else if(uri.isFile()){
			final IPath rootPath = ResourcesPlugin.getWorkspace().getRoot().getLocation();
			String rootString = rootPath.toFile().toString();
			String fileString = uri.toFileString();
			if(fileString.startsWith(rootString))
				return URI.createPlatformResourceURI(fileString.replace(rootString, ""), false);
		}
		return null;
	}

	protected abstract void handleMissingDiagramBo(Diagram diagram);
	protected abstract void superClassChanged();
	protected abstract EObject getModel();

	public URI getInputUri() {
		return inputUri;
	}

}

Back to the top