Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: c9c9010edb183c6eaf600274d6bde08286006df1 (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
/*******************************************************************************
 * Copyright (c) 2016 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:
 * 		Juergen Haug
 * 
 *******************************************************************************/

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

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

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.emf.common.util.Diagnostic;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.transaction.RunnableWithResult;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.etrice.ui.common.base.UIBaseActivator;
import org.eclipse.graphiti.mm.pictograms.Diagram;
import org.eclipse.graphiti.ui.editor.DefaultPersistencyBehavior;
import org.eclipse.graphiti.ui.editor.DiagramBehavior;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.xtext.diagnostics.Severity;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.serializer.ISerializer;
import org.eclipse.xtext.util.CancelIndicator;
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;

public class CustomPersistencyBehavior extends DefaultPersistencyBehavior {

	private SaveOnFocusLostListener saveOnFocusListener;
	
	public CustomPersistencyBehavior(DiagramBehavior diagramBehavior) {
		super(diagramBehavior);
	}
	
	@Override
	public Diagram loadDiagram(URI uri) {
		saveOnFocusListener = new SaveOnFocusLostListener((IEditorPart)diagramBehavior.getDiagramContainer().getWorkbenchPart());
		return super.loadDiagram(uri);
	}
	
	@Override
	public void saveDiagram(IProgressMonitor monitor) {
		boolean valid = validateResourcesBeforeSave(monitor);

		if (valid)
			super.saveDiagram(monitor);

		// deactivate saveOnFocus for better usability
		// avoid retrigger loop from message box
		saveOnFocusListener.setActive(valid);
	}
	
	protected boolean validateResourcesBeforeSave(final IProgressMonitor monitor){
		final RunnableWithResult<Boolean> runnable = new RunnableWithResult.Impl<Boolean>() {

			@Override
			public void run() {
				setResult(false);
				
				boolean result = true;
				// copy list to avoid ConcurrentModification during serialize and validation
				final List<Resource> resources = Lists.newArrayList(diagramBehavior.getEditingDomain().getResourceSet().getResources());
				for(Resource res : resources){
					result &= !shouldSave(res) || validateResource(res, monitor);
				}
				
				setResult(result);
			}
			
		};
		
		try {
			return TransactionUtil.runExclusive(diagramBehavior.getEditingDomain(), 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) {
		IStatus resultStatus = null;		
		if(res instanceof XtextResource)
			resultStatus = validateSyntax((XtextResource) res);
		else
			resultStatus = Status.OK_STATUS;
		
		if (!resultStatus.isOK()) {
			final int filterMask = IStatus.OK | IStatus.INFO | IStatus.WARNING | IStatus.ERROR;
			ErrorDialog dialog = new ErrorDialog(diagramBehavior.getDiagramContainer().getSite().getShell(),
					"Save", "Cannot save diagram.", resultStatus, filterMask) {
				@Override
				public void create() {
					super.create();
					showDetailsArea();
				};
			};
			dialog.open();
		}
		
		return resultStatus.isOK();
	}

	protected IStatus validateSyntax(XtextResource resource) {		
		MultiStatus status = new MultiStatus(UIBaseActivator.PLUGIN_ID, 0, "Could not create textual representation of " + resource.getURI().lastSegment() + ".", null);
		for (Diagnostic diag : resource.validateConcreteSyntax())
			status.add(new Status(IStatus.ERROR, UIBaseActivator.PLUGIN_ID, diag.toString()));

		try {
			if(status.isOK())
				resource.getSerializer().serialize(resource.getContents().get(0));
		} catch(RuntimeException e){
			status.add(new Status(IStatus.ERROR, UIBaseActivator.PLUGIN_ID, e.getMessage()));
		}
		
		return status;
	}
	
	//
	// Old syntax + semantic validation backup
	//
	
	@Deprecated
	@Inject
	private IResourceValidator resourceValidator;
	
	@Deprecated
	@SuppressWarnings("unused")
	private boolean validateResourceFully(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() {
							if(monitor == null)
								return false;
							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) {
							StringBuilder messges = new StringBuilder();
							for(IStatus status : ms.getChildren())
								messges.append(status.getMessage()+"\n");
							MessageDialog.openError(Display.getDefault().getActiveShell(), "ERROR", "Internal error: model is invalid, can't save:\n\n"+messges);
							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;
	}

}

Back to the top