Debian Codegraph @

plugins/org.eclipse.emf.edit.ui/src/org/eclipse/emf/edit/ui/action/ValidateAction.java

raw
1 /**
2 * Copyright (c) 2004-2008 IBM Corporation and others.
3 * All rights reserved. This program and the accompanying materials
4 * are made available under the terms of the Eclipse Public License v2.0
5 * which accompanies this distribution, and is available at
6 * http://www.eclipse.org/legal/epl-v20.html
7 *
8 * Contributors:
9 * IBM - Initial API and implementation
10 */
11 package org.eclipse.emf.edit.ui.action;
12
13 import java.lang.reflect.InvocationTargetException;
14 import java.util.ArrayList;
15 import java.util.Iterator;
16 import java.util.LinkedHashMap;
17 import java.util.LinkedHashSet;
18 import java.util.List;
19 import java.util.Map;
20 import java.util.Set;
21
22 import org.eclipse.core.resources.IMarker;
23 import org.eclipse.core.runtime.CoreException;
24 import org.eclipse.core.runtime.IProgressMonitor;
25 import org.eclipse.core.runtime.OperationCanceledException;
26 import org.eclipse.jface.action.Action;
27 import org.eclipse.jface.dialogs.Dialog;
28 import org.eclipse.jface.dialogs.MessageDialog;
29 import org.eclipse.jface.dialogs.ProgressMonitorDialog;
30 import org.eclipse.jface.operation.IRunnableWithProgress;
31 import org.eclipse.jface.viewers.ISelectionChangedListener;
32 import org.eclipse.jface.viewers.ISelectionProvider;
33 import org.eclipse.jface.viewers.IStructuredSelection;
34 import org.eclipse.jface.viewers.SelectionChangedEvent;
35 import org.eclipse.jface.viewers.StructuredSelection;
36 import org.eclipse.jface.viewers.Viewer;
37 import org.eclipse.jface.window.Window;
38 import org.eclipse.swt.widgets.Shell;
39 import org.eclipse.ui.IWorkbenchPart;
40 import org.eclipse.ui.PlatformUI;
41 import org.eclipse.ui.actions.WorkspaceModifyDelegatingOperation;
42 import org.eclipse.ui.part.ISetSelectionTarget;
43
44 import org.eclipse.emf.common.EMFPlugin;
45 import org.eclipse.emf.common.notify.AdapterFactory;
46 import org.eclipse.emf.common.ui.dialogs.DiagnosticDialog;
47 import org.eclipse.emf.common.ui.viewer.IViewerProvider;
48 import org.eclipse.emf.common.util.BasicDiagnostic;
49 import org.eclipse.emf.common.util.Diagnostic;
50 import org.eclipse.emf.common.util.DiagnosticChain;
51 import org.eclipse.emf.common.util.URI;
52 import org.eclipse.emf.ecore.EClass;
53 import org.eclipse.emf.ecore.EObject;
54 import org.eclipse.emf.ecore.EValidator;
55 import org.eclipse.emf.ecore.resource.Resource;
56 import org.eclipse.emf.ecore.resource.ResourceSet;
57 import org.eclipse.emf.ecore.util.Diagnostician;
58 import org.eclipse.emf.ecore.util.EObjectValidator;
59 import org.eclipse.emf.ecore.util.EcoreUtil;
60 import org.eclipse.emf.edit.domain.AdapterFactoryEditingDomain;
61 import org.eclipse.emf.edit.domain.EditingDomain;
62 import org.eclipse.emf.edit.domain.IEditingDomainProvider;
63 import org.eclipse.emf.edit.provider.IItemLabelProvider;
64 import org.eclipse.emf.edit.ui.EMFEditUIPlugin;
65 import org.eclipse.emf.edit.ui.provider.DiagnosticDecorator;
66 import org.eclipse.emf.edit.ui.util.EditUIMarkerHelper;
67
68
69 public class ValidateAction extends Action implements ISelectionChangedListener
70 {
71 public static class EclipseResourcesUtil extends EditUIMarkerHelper
72 {
73 public IRunnableWithProgress getWorkspaceModifyOperation(IRunnableWithProgress runnableWithProgress)
74 {
75 try
76 {
77 return new WorkspaceModifyDelegatingOperation(runnableWithProgress);
78 }
79 catch (NoClassDefFoundError exception)
80 {
81 return runnableWithProgress;
82 }
83 }
84
85 @Override
86 protected String getMarkerID()
87 {
88 return EValidator.MARKER;
89 }
90
91 public void createMarkers(Resource resource, Diagnostic diagnostic)
92 {
93 try
94 {
95 createMarkers(getFile(resource), diagnostic, null);
96 }
97 catch (CoreException e)
98 {
99 EMFEditUIPlugin.INSTANCE.log(e);
100 }
101 }
102
103 @Override
104 protected String composeMessage(Diagnostic diagnostic, Diagnostic parentDiagnostic)
105 {
106 String message = diagnostic.getMessage();
107 if (parentDiagnostic != null)
108 {
109 String parentMessage = parentDiagnostic.getMessage();
110 if (parentMessage != null)
111 {
112 message = message != null ? parentMessage + ". " + message : parentMessage;
113 }
114 }
115 return message;
116 }
117
118 @Override
119 protected void adjustMarker(IMarker marker, Diagnostic diagnostic, Diagnostic parentDiagnostic) throws CoreException
120 {
121 List<?> data = diagnostic.getData();
122 StringBuilder relatedURIs = new StringBuilder();
123 boolean first = true;
124 for (Object object : data)
125 {
126 if (object instanceof EObject)
127 {
128 EObject eObject = (EObject)object;
129 if (first)
130 {
131 first = false;
132 marker.setAttribute(EValidator.URI_ATTRIBUTE, EcoreUtil.getURI(eObject).toString());
133 }
134 else
135 {
136 if (relatedURIs.length() != 0)
137 {
138 relatedURIs.append(' ');
139 }
140 relatedURIs.append(URI.encodeFragment(EcoreUtil.getURI(eObject).toString(), false));
141 }
142 }
143 }
144
145 if (relatedURIs.length() > 0)
146 {
147 marker.setAttribute(EValidator.RELATED_URIS_ATTRIBUTE, relatedURIs.toString());
148 }
149
150 super.adjustMarker(marker, diagnostic, parentDiagnostic);
151 }
152 }
153
154 protected ISelectionProvider selectionProvider;
155 protected List<EObject> selectedObjects;
156 protected EditingDomain domain;
157 protected EclipseResourcesUtil eclipseResourcesUtil =
158 EMFPlugin.IS_RESOURCES_BUNDLE_AVAILABLE ?
159 new EclipseResourcesUtil() :
160 null;
161
162 public ValidateAction()
163 {
164 super(EMFEditUIPlugin.INSTANCE.getString("_UI_Validate_menu_item"));
165 setDescription(EMFEditUIPlugin.INSTANCE.getString("_UI_Validate_simple_description"));
166 setEnabled(false);
167 }
168
169 @Override
170 public void run()
171 {
172 final Diagnostic[] diagnostic = new Diagnostic[1];
173 IRunnableWithProgress validationRunnable =
174 new IRunnableWithProgress()
175 {
176 public void run(final IProgressMonitor progressMonitor) throws InvocationTargetException, InterruptedException
177 {
178 try
179 {
180 diagnostic[0] = validate(progressMonitor);
181 }
182 catch (OperationCanceledException exception)
183 {
184 diagnostic[0] = Diagnostic.CANCEL_INSTANCE;
185 }
186 finally
187 {
188 progressMonitor.done();
189 }
190 }
191 };
192 final Shell shell = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell();
193 try
194 {
195 new ProgressMonitorDialog(shell).run(true, true, validationRunnable);
196 handleDiagnostic(diagnostic[0]);
197 }
198 catch (Exception exception)
199 {
200 EMFEditUIPlugin.INSTANCE.log(exception);
201 MessageDialog.openError(shell, EMFEditUIPlugin.INSTANCE.getString("_UI_ValidationProblems_title"), EMFEditUIPlugin.INSTANCE.getString("_UI_ValidationFailed_message"));
202 try
203 {
204 PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().showView("org.eclipse.pde.runtime.LogView");
205 }
206 catch (Exception ex)
207 {
208 // Ignored.
209 }
210 }
211 }
212
213 protected Diagnostic validate(IProgressMonitor progressMonitor)
214 {
215 int selectionSize = selectedObjects.size();
216 int count = selectionSize;
217 synchronized (domain.getResourceSet())
218 {
219 for (EObject eObject : selectedObjects)
220 {
221 for (Iterator<?> i = eObject.eAllContents(); i.hasNext(); i.next())
222 {
223 ++count;
224 }
225 }
226 }
227
228 progressMonitor.beginTask("", count);
229
230 AdapterFactory adapterFactory =
231 domain instanceof AdapterFactoryEditingDomain ? ((AdapterFactoryEditingDomain)domain).getAdapterFactory() : null;
232 Diagnostician diagnostician = createDiagnostician(adapterFactory, progressMonitor);
233
234 BasicDiagnostic diagnostic;
235 if (selectionSize == 1)
236 {
237 diagnostic = diagnostician.createDefaultDiagnostic(selectedObjects.get(0));
238 }
239 else
240 {
241 diagnostic =
242 new BasicDiagnostic
243 (EObjectValidator.DIAGNOSTIC_SOURCE,
244 0,
245 EMFEditUIPlugin.INSTANCE.getString("_UI_DiagnosisOfNObjects_message", new String[] { Integer.toString(selectionSize) }),
246 selectedObjects.toArray());
247 }
248 Map<Object, Object> context = diagnostician.createDefaultContext();
249 for (EObject eObject : selectedObjects)
250 {
251 progressMonitor.setTaskName(EMFEditUIPlugin.INSTANCE.getString("_UI_Validating_message", new Object [] { diagnostician.getObjectLabel(eObject) }));
252 diagnostician.validate(eObject, diagnostic, context);
253 context.remove(EObjectValidator.ROOT_OBJECT);
254 }
255 return diagnostic;
256 }
257
258 protected Diagnostician createDiagnostician(final AdapterFactory adapterFactory, final IProgressMonitor progressMonitor)
259 {
260 final ResourceSet resourceSet = domain.getResourceSet();
261 return
262 new Diagnostician()
263 {
264 @Override
265 public String getObjectLabel(EObject eObject)
266 {
267 if (adapterFactory != null && !eObject.eIsProxy())
268 {
269 IItemLabelProvider itemLabelProvider = (IItemLabelProvider)adapterFactory.adapt(eObject, IItemLabelProvider.class);
270 if (itemLabelProvider != null)
271 {
272 return itemLabelProvider.getText(eObject);
273 }
274 }
275
276 return super.getObjectLabel(eObject);
277 }
278
279 @Override
280 protected boolean doValidate(EValidator eValidator, EClass eClass, EObject eObject, DiagnosticChain diagnostics, Map<Object, Object> context)
281 {
282 if (progressMonitor.isCanceled())
283 {
284 throw new OperationCanceledException();
285 }
286
287 progressMonitor.worked(1);
288 Resource resource = eObject.eResource();
289 if (resource == null)
290 {
291 synchronized (resourceSet)
292 {
293 return super.doValidate(eValidator, eClass, eObject, diagnostics, context);
294 }
295 }
296 else
297 {
298 synchronized (resource)
299 {
300 synchronized (resourceSet)
301 {
302 return super.doValidate(eValidator, eClass, eObject, diagnostics, context);
303 }
304 }
305 }
306 }
307 };
308 }
309
310 protected void handleDiagnostic(final Diagnostic diagnostic)
311 {
312 int severity = diagnostic.getSeverity();
313 String title = null;
314 String message = null;
315
316 if (severity == Diagnostic.ERROR || severity == Diagnostic.WARNING)
317 {
318 title = EMFEditUIPlugin.INSTANCE.getString("_UI_ValidationProblems_title");
319 message = EMFEditUIPlugin.INSTANCE.getString("_UI_ValidationProblems_message");
320 }
321 else
322 {
323 title = EMFEditUIPlugin.INSTANCE.getString("_UI_ValidationResults_title");
324 message = EMFEditUIPlugin.INSTANCE.getString(severity == Diagnostic.OK ? "_UI_ValidationOK_message" : "_UI_ValidationResults_message");
325 }
326
327 int result = 0;
328 if (diagnostic.getSeverity() == Diagnostic.OK)
329 {
330 MessageDialog.openInformation(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, message);
331 result = Window.CANCEL;
332 }
333 else
334 {
335 result = DiagnosticDialog.open
336 (PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell(), title, message, diagnostic);
337 }
338
339 ResourceSet resourceSet = domain.getResourceSet();
340 final Set<Resource> resources = new LinkedHashSet<Resource>();
341 if (eclipseResourcesUtil != null)
342 {
343 for (Object data : diagnostic.getData())
344 {
345 resources.add(data instanceof EObject ? ((EObject)data).eResource() : null);
346 }
347 resources.remove(null);
348 }
349 for (Resource resource : resources)
350 {
351 eclipseResourcesUtil.deleteMarkers(resource);
352 }
353
354 if (result == Window.OK)
355 {
356 if (!diagnostic.getChildren().isEmpty())
357 {
358 List<?> data = (diagnostic.getChildren().get(0)).getData();
359 if (!data.isEmpty() && data.get(0) instanceof EObject)
360 {
361 Object part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart();
362 if (part instanceof ISetSelectionTarget)
363 {
364 ((ISetSelectionTarget)part).selectReveal(new StructuredSelection(data.get(0)));
365 }
366 else if (part instanceof IViewerProvider)
367 {
368 Viewer viewer = ((IViewerProvider)part).getViewer();
369 if (viewer != null)
370 {
371 viewer.setSelection(new StructuredSelection(data.get(0)), true);
372 }
373 }
374 }
375 }
376
377 if (eclipseResourcesUtil != null)
378 {
379 IRunnableWithProgress runnable = new IRunnableWithProgress()
380 {
381 public void run(IProgressMonitor progressMonitor)
382 {
383 int count = 0;
384 int limit = getLimit();
385 for (Diagnostic childDiagnostic : diagnostic.getChildren())
386 {
387 if (progressMonitor.isCanceled() || ++count > limit)
388 {
389 return;
390 }
391 List<?> data = childDiagnostic.getData();
392 if (!data.isEmpty())
393 {
394 Object object = data.get(0);
395 Resource resource = object instanceof EObject ? ((EObject)object).eResource() : null;
396 if (resource != null)
397 {
398 eclipseResourcesUtil.createMarkers(resource, childDiagnostic);
399 }
400 }
401 }
402 }
403 };
404
405 runnable = eclipseResourcesUtil.getWorkspaceModifyOperation(runnable);
406
407 try
408 {
409 new ProgressMonitorDialog(PlatformUI.getWorkbench().getActiveWorkbenchWindow().getShell()).run(false, true, runnable);
410 }
411 catch (Exception exception)
412 {
413 EMFEditUIPlugin.INSTANCE.log(exception);
414 }
415 }
416 }
417 else
418 {
419 // Trigger direct updating of decorations, if there are adapters.
420 //
421 resources.clear();
422 }
423
424 if (resources.isEmpty())
425 {
426 // If no markers are produced the decorator won't be able to respond to marker resource deltas, so inform it directly.
427 //
428
429 // Create a diagnostic for the resource set as a whole.
430 //
431 BasicDiagnostic resourceSetDiagnostic = new BasicDiagnostic(EObjectValidator.DIAGNOSTIC_SOURCE, 0, null, new Object [] { resourceSet });
432
433 // Create a diagnostic for each resource.
434 //
435 Map<Resource, BasicDiagnostic> resourceDiagnostics = new LinkedHashMap<Resource, BasicDiagnostic>();
436 for (Resource r : resourceSet.getResources())
437 {
438 BasicDiagnostic resourceDiagnostic = new BasicDiagnostic(EObjectValidator.DIAGNOSTIC_SOURCE, 0, null, new Object [] { r });
439 resourceDiagnostics.put(r, resourceDiagnostic);
440 }
441
442 // Just clean up decorations if the dialog was cancelled.
443 //
444 if (result == Dialog.OK)
445 {
446 // Partition the children among the resource diagnostics.
447 //
448 for (Diagnostic child : diagnostic.getChildren())
449 {
450 List<?> data = child.getData();
451 if (!data.isEmpty())
452 {
453 Object object = data.get(0);
454 if (object instanceof EObject)
455 {
456 BasicDiagnostic resourceDiagnostic = resourceDiagnostics.get(((EObject)object).eResource());
457 if (resourceDiagnostic != null)
458 {
459 resourceDiagnostic.add(child);
460 }
461 }
462 }
463 }
464 }
465
466 // Add the resource diagnostics to the resource set diagnostic.
467 //
468 for (Diagnostic resourceDiagnostic : resourceDiagnostics.values())
469 {
470 resourceSetDiagnostic.add(resourceDiagnostic);
471 }
472
473 // Inform any decorators.
474 //
475 DiagnosticDecorator.DiagnosticAdapter.update(resourceSet, resourceSetDiagnostic);
476 }
477 }
478
479 public void selectionChanged(SelectionChangedEvent event)
480 {
481 selectionProvider = event.getSelectionProvider();
482 if (event.getSelection() instanceof IStructuredSelection)
483 {
484 setEnabled(updateSelection((IStructuredSelection)event.getSelection()));
485 }
486 else
487 {
488 setEnabled(false);
489 }
490 }
491
492 public boolean updateSelection(IStructuredSelection selection)
493 {
494 selectedObjects = new ArrayList<EObject>();
495 for (Iterator<?> objects = selection.iterator(); objects.hasNext(); )
496 {
497 Object object = AdapterFactoryEditingDomain.unwrap(objects.next());
498 if (object instanceof EObject)
499 {
500 selectedObjects.add((EObject)object);
501 }
502 else if (object instanceof Resource)
503 {
504 selectedObjects.addAll(((Resource)object).getContents());
505 }
506 else
507 {
508 return false;
509 }
510 }
511 selectedObjects = EcoreUtil.filterDescendants(selectedObjects);
512 return !selectedObjects.isEmpty();
513 }
514
515 /**
516 * @since 2.1.0
517 */
518 public void setActiveWorkbenchPart(IWorkbenchPart workbenchPart)
519 {
520 if (workbenchPart instanceof IEditingDomainProvider)
521 {
522 domain = ((IEditingDomainProvider)workbenchPart).getEditingDomain();
523 }
524 }
525
526 private int getLimit()
527 {
528 String property = System.getProperty("org.eclipse.emf.common.util.Diagnostic.limit");
529 if (property != null)
530 {
531 try
532 {
533 int result = Integer.parseInt(property);
534 if (result > 0)
535 {
536 return result;
537 }
538 }
539 catch (RuntimeException exception)
540 {
541 //$FALL-THROUGH$
542 }
543 }
544 return 10000;
545 }
546 }