/**
   * This method should be called within a workspace modify operation since it creates resources.
   *
   * @generated
   */
  public static Resource createDiagram(
      URI diagramURI,
      URI modelURI,
      final String diagramName,
      final String diagramNameWithoutExtension,
      final EClass initialObject,
      final String encoding,
      IProgressMonitor progressMonitor) {
    TransactionalEditingDomain editingDomain =
        GMFEditingDomainFactory.INSTANCE.createEditingDomain();
    progressMonitor.beginTask(Messages.UMLDiagramEditorUtil_CreateDiagramProgressTask, 3);
    final Resource diagramResource = editingDomain.getResourceSet().createResource(diagramURI);
    final Resource modelResource = editingDomain.getResourceSet().createResource(modelURI);
    AbstractTransactionalCommand command =
        new AbstractTransactionalCommand(
            editingDomain,
            Messages.UMLDiagramEditorUtil_CreateDiagramCommandLabel,
            Collections.EMPTY_LIST) {

          protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
              throws ExecutionException {
            Package model = createInitialModel(initialObject, diagramNameWithoutExtension);
            attachModelToResource(model, modelResource);

            Diagram diagram =
                ViewService.createDiagram(
                    model,
                    PackageEditPart.MODEL_ID,
                    UMLDiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);
            if (diagram != null) {
              diagramResource.getContents().add(diagram);
              diagram.setName(diagramName);
              diagram.setElement(model);
            }

            try {
              modelResource.save(
                  org.eclipse.uml2.diagram.csd.part.UMLDiagramEditorUtil.getSaveOptions(encoding));
              diagramResource.save(
                  org.eclipse.uml2.diagram.csd.part.UMLDiagramEditorUtil.getSaveOptions(encoding));
            } catch (IOException e) {

              UMLDiagramEditorPlugin.getInstance()
                  .logError("Unable to store model and diagram resources", e); // $NON-NLS-1$
            }
            return CommandResult.newOKCommandResult();
          }
        };
    try {
      OperationHistoryFactory.getOperationHistory()
          .execute(command, new SubProgressMonitor(progressMonitor, 1), null);
    } catch (ExecutionException e) {
      UMLDiagramEditorPlugin.getInstance()
          .logError("Unable to create model and diagram", e); // $NON-NLS-1$
    }
    setCharset(WorkspaceSynchronizer.getFile(modelResource));
    setCharset(WorkspaceSynchronizer.getFile(diagramResource));
    return diagramResource;
  }
  /** @generated */
  protected void handleElementChanged(
      ResourceSetInfo info, Resource changedResource, IProgressMonitor monitor) {
    IFile file = WorkspaceSynchronizer.getFile(changedResource);
    if (file != null) {
      try {
        file.refreshLocal(IResource.DEPTH_INFINITE, monitor);
      } catch (CoreException ex) {
        CallGraphDiagramEditorPlugin.getInstance()
            .logError(Messages.CallGraphDocumentProvider_handleElementContentChanged, ex);
        // Error message to log was initially taken from
        // org.eclipse.gmf.runtime.diagram.ui.resources.editor.ide.internal.l10n.EditorMessages.FileDocumentProvider_handleElementContentChanged
      }
    }
    changedResource.unload();

    fireElementContentAboutToBeReplaced(info.getEditorInput());
    removeUnchangedElementListeners(info.getEditorInput(), info);
    info.fStatus = null;
    try {
      setDocumentContent(info.fDocument, info.getEditorInput());
    } catch (CoreException e) {
      info.fStatus = e.getStatus();
    }
    if (!info.fCanBeSaved) {
      info.setModificationStamp(computeModificationStamp(info));
    }
    addUnchangedElementListeners(info.getEditorInput(), info);
    fireElementContentReplaced(info.getEditorInput());
  }
 /** @generated */
 public void dispose() {
   myWorkspaceSynchronizer.dispose();
   myWorkspaceSynchronizer = null;
   myViewerRefreshRunnable = null;
   myViewer = null;
   unloadAllResources();
   ((TransactionalEditingDomain) myEditingDomain).dispose();
   myEditingDomain = null;
 }
 private String absolute(String path) {
   path = substitute(path);
   if (source.eResource().getURI().isPlatformResource()) {
     IFile f = WorkspaceSynchronizer.getFile(source.eResource());
     IFile resultFile = f.getProject().getFile(new Path(path));
     resultFile.getParent().getLocation().toFile().mkdirs();
     return resultFile.getLocation().toFile().getAbsolutePath();
   }
   return null;
 }
 /** @generated */
 public void dispose() {
   myWorkspaceSynchronizer.dispose();
   myWorkspaceSynchronizer = null;
   myViewerRefreshRunnable = null;
   for (Iterator it = myEditingDomain.getResourceSet().getResources().iterator(); it.hasNext(); ) {
     Resource resource = (Resource) it.next();
     resource.unload();
   }
   ((TransactionalEditingDomain) myEditingDomain).dispose();
   myEditingDomain = null;
 }
 /** @generated */
 public boolean isDeleted(Object element) {
   IDiagramDocument document = getDiagramDocument(element);
   if (document != null) {
     Resource diagramResource = document.getDiagram().eResource();
     if (diagramResource != null) {
       IFile file = WorkspaceSynchronizer.getFile(diagramResource);
       return file == null || file.getLocation() == null || !file.getLocation().toFile().exists();
     }
   }
   return super.isDeleted(element);
 }
 /** @generated */
 private ISelection getNavigatorSelection() {
   IDiagramDocument document = getDiagramDocument();
   if (document == null) {
     return StructuredSelection.EMPTY;
   }
   Diagram diagram = document.getDiagram();
   IFile file = WorkspaceSynchronizer.getFile(diagram.eResource());
   if (file != null) {
     SqlmodelNavigatorItem item = new SqlmodelNavigatorItem(diagram, file, false);
     return new StructuredSelection(item);
   }
   return StructuredSelection.EMPTY;
 }
 /** {@inheritDoc} */
 public List getAffectedFiles() {
   if (viewer != null) {
     EditPart editpart = viewer.getRootEditPart().getContents();
     if (editpart instanceof IGraphicalEditPart) {
       View view = (View) ((IGraphicalEditPart) editpart).getModel();
       if (view != null) {
         IFile f = WorkspaceSynchronizer.getFile(view.eResource());
         return f != null ? Collections.singletonList(f) : Collections.EMPTY_LIST;
       }
     }
   }
   return super.getAffectedFiles();
 }
 /** @generated */
 protected ISchedulingRule getSaveRule(Object element) {
   ResourceSetInfo info = getResourceSetInfo(element);
   if (info != null) {
     LinkedList<ISchedulingRule> rules = new LinkedList<ISchedulingRule>();
     for (Iterator<Resource> it = info.getLoadedResourcesIterator(); it.hasNext(); ) {
       Resource nextResource = it.next();
       IFile file = WorkspaceSynchronizer.getFile(nextResource);
       if (file != null) {
         rules.add(computeSchedulingRule(file));
       }
     }
     return new MultiRule((ISchedulingRule[]) rules.toArray(new ISchedulingRule[rules.size()]));
   }
   return null;
 }
 /** @generated */
 private long computeModificationStamp(ResourceSetInfo info) {
   int result = 0;
   for (Iterator it = info.getResourceSet().getResources().iterator(); it.hasNext(); ) {
     Resource nextResource = (Resource) it.next();
     IFile file = WorkspaceSynchronizer.getFile(nextResource);
     if (file != null) {
       if (file.getLocation() != null) {
         result += file.getLocation().toFile().lastModified();
       } else {
         result += file.getModificationStamp();
       }
     }
   }
   return result;
 }
 /** @generated */
 protected ISchedulingRule getSynchronizeRule(Object element) {
   ResourceSetInfo info = getResourceSetInfo(element);
   if (info != null) {
     Collection rules = new ArrayList();
     for (Iterator it = info.getResourceSet().getResources().iterator(); it.hasNext(); ) {
       Resource nextResource = (Resource) it.next();
       IFile file = WorkspaceSynchronizer.getFile(nextResource);
       if (file != null) {
         rules.add(ResourcesPlugin.getWorkspace().getRuleFactory().refreshRule(file));
       }
     }
     return new MultiRule((ISchedulingRule[]) rules.toArray(new ISchedulingRule[rules.size()]));
   }
   return null;
 }
 /** @generated */
 private static IEditorInput getEditorInput(Diagram diagram) {
   Resource diagramResource = diagram.eResource();
   for (EObject nextEObject : diagramResource.getContents()) {
     if (nextEObject == diagram) {
       return new FileEditorInput(WorkspaceSynchronizer.getFile(diagramResource));
     }
     if (nextEObject instanceof Diagram) {
       break;
     }
   }
   URI uri = EcoreUtil.getURI(diagram);
   String editorName =
       uri.lastSegment() + '#' + diagram.eResource().getContents().indexOf(diagram);
   IEditorInput editorInput = new URIEditorInput(uri, editorName);
   return editorInput;
 }
  private static IEditorInput getEditorInput(EObject item) {
    Resource res = item.eResource();
    for (EObject content : res.getContents()) {
      if (content == item) {
        return new FileEditorInput(WorkspaceSynchronizer.getFile(res));
      }
      if (content instanceof HierarchicalNode) {
        break;
      }
    }

    URI uri = EcoreUtil.getURI(item);
    String name = uri.lastSegment() + '#' + item.eResource().getContents().indexOf(item);
    IEditorInput input = new URIEditorInput(uri, name);
    return input;
  }
 /** @generated */
 protected ISchedulingRule getValidateStateRule(Object element) {
   ResourceSetInfo info = getResourceSetInfo(element);
   if (info != null) {
     Collection files = new ArrayList();
     for (Iterator it = info.getResourceSet().getResources().iterator(); it.hasNext(); ) {
       Resource nextResource = (Resource) it.next();
       IFile file = WorkspaceSynchronizer.getFile(nextResource);
       if (file != null) {
         files.add(file);
       }
     }
     return ResourcesPlugin.getWorkspace()
         .getRuleFactory()
         .validateEditRule((IFile[]) files.toArray(new IFile[files.size()]));
   }
   return null;
 }
 /** @generated */
 protected void updateCache(Object element) throws CoreException {
   ResourceSetInfo info = getResourceSetInfo(element);
   if (info != null) {
     for (Iterator it = info.getResourceSet().getResources().iterator(); it.hasNext(); ) {
       Resource nextResource = (Resource) it.next();
       IFile file = WorkspaceSynchronizer.getFile(nextResource);
       if (file != null && file.isReadOnly()) {
         info.setReadOnly(true);
         info.setModifiable(false);
         return;
       }
     }
     info.setReadOnly(false);
     info.setModifiable(true);
     return;
   }
 }
 /** @generated */
 public IStructuredSelection findSelection(IEditorInput anInput) {
   IDiagramDocument document =
       MIDDiagramEditorPlugin.getInstance().getDocumentProvider().getDiagramDocument(anInput);
   if (document == null) {
     return StructuredSelection.EMPTY;
   }
   Diagram diagram = document.getDiagram();
   if (diagram == null || diagram.eResource() == null) {
     return StructuredSelection.EMPTY;
   }
   IFile file = WorkspaceSynchronizer.getFile(diagram.eResource());
   if (file != null) {
     MIDNavigatorItem item = new MIDNavigatorItem(diagram, file, false);
     return new StructuredSelection(item);
   }
   return StructuredSelection.EMPTY;
 }
  /** @generated */
  protected void doValidateState(Object element, Object computationContext) throws CoreException {
    ResourceSetInfo info = getResourceSetInfo(element);
    if (info != null) {
      Collection files2Validate = new ArrayList();
      for (Iterator it = info.getResourceSet().getResources().iterator(); it.hasNext(); ) {
        Resource nextResource = (Resource) it.next();
        IFile file = WorkspaceSynchronizer.getFile(nextResource);
        if (file != null && file.isReadOnly()) {
          files2Validate.add(file);
        }
      }
      ResourcesPlugin.getWorkspace()
          .validateEdit(
              (IFile[]) files2Validate.toArray(new IFile[files2Validate.size()]),
              computationContext);
    }

    super.doValidateState(element, computationContext);
  }
  private void save(final Collection<Resource> resources, final IProgressMonitor monitor) {
    final SubMonitor resourceLoopMonitor =
        SubMonitor.convert(monitor, "Saving resources", resources.size()); // SUPPRESS
    // CHECKSTYLE
    // MagicNumber
    for (final Resource resource : resources) {
      try {
        final IWorkspaceRunnable runnable =
            new IWorkspaceRunnable() {

              @Override
              public void run(final IProgressMonitor monitor) throws CoreException {
                try {
                  resource.save(null);
                } catch (final IOException e) {
                  throw new CoreException(
                      new Status(
                          IStatus.ERROR,
                          ComponentUiPlugin.PLUGIN_ID,
                          "Failed to save Quick Fix for " + resource.getURI(),
                          e));
                }
              }
            };
        ResourcesPlugin.getWorkspace()
            .run(
                runnable,
                WorkspaceSynchronizer.getFile(resource),
                0,
                resourceLoopMonitor.newChild(1));
      } catch (final CoreException e) {
        StatusManager.getManager()
            .handle(
                new Status(
                    e.getStatus().getSeverity(),
                    ComponentUiPlugin.PLUGIN_ID,
                    e.getLocalizedMessage(),
                    e),
                StatusManager.SHOW | StatusManager.LOG);
      }
    }
  }
 /** @generated */
 public ICommand getParseCommand(IAdaptable element, final String newString, int flags) {
   final EObject target = (EObject) element.getAdapter(EObject.class);
   if (!validateValues(target, newString)) {
     return UnexecutableCommand.INSTANCE;
   }
   TransactionalEditingDomain editingDomain = TransactionUtil.getEditingDomain(target);
   if (editingDomain == null) {
     return UnexecutableCommand.INSTANCE;
   }
   IFile affectedFile = WorkspaceSynchronizer.getFile(target.eResource());
   return new AbstractTransactionalCommand(
       editingDomain,
       "Set Values",
       affectedFile == null ? null : Collections.singletonList(affectedFile)) { // $NON-NLS-1$
     protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
         throws ExecutionException {
       return new CommandResult(updateValues(target, newString));
     }
   };
 }
    /** @not-generated */
    @Override
    public void refresh() {
      removeDecoration();
      View view = (View) getDecoratorTarget().getAdapter(View.class);
      Resource viewResource = null;
      if (view != null) {
        viewResource = view.eResource();
      }
      if (viewResource == null) {
        return;
      }
      EditPart editPart = (EditPart) getDecoratorTarget().getAdapter(EditPart.class);
      if (editPart == null || editPart.getParent() == null || editPart.getViewer() == null) {
        return;
      }

      // query for all the validation markers of the current resource
      String elementId = SiriusGMFHelper.getViewId(view);
      if (elementId == null) {
        return;
      }

      // Directly retrieve the main Session resource
      // (session.getSessionResource()) as we know we put the marker on
      // it.
      Session currentSession = null;
      ResourceSet currentRs = viewResource.getResourceSet();
      for (Session session : SessionManager.INSTANCE.getSessions()) {
        if (currentRs == session.getTransactionalEditingDomain().getResourceSet()) {
          currentSession = session;
          break;
        }
      }
      Resource markedResource = currentSession == null ? null : currentSession.getSessionResource();
      IResource resource = WorkspaceSynchronizer.getFile(markedResource);

      if (resource == null || !resource.exists()) {
        return;
      }
      IMarker[] markers = null;
      try {
        markers = resource.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE);
      } catch (CoreException e) {
        DiagramPlugin.getDefault()
            .logError(Messages.StatusDecorator_validationMarkersFailureMsg, e);
      }
      if (markers == null || markers.length == 0) {
        return;
      }

      int severity = IMarker.SEVERITY_INFO;
      IMarker foundMarker = null;
      Label toolTip = null;
      for (int i = 0; i < markers.length; i++) {
        IMarker marker = markers[i];
        String attribute =
            marker.getAttribute(
                org.eclipse.gmf.runtime.common.ui.resources.IMarker.ELEMENT_ID, ""); // $NON-NLS-1$
        if (attribute.equals(elementId)) {
          int nextSeverity = marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
          Image nextImage = getImage(nextSeverity);
          if (foundMarker == null) {
            foundMarker = marker;
            toolTip =
                new Label(
                    marker.getAttribute(IMarker.MESSAGE, ""), // $NON-NLS-1$
                    nextImage);
          } else {
            if (toolTip.getChildren().isEmpty()) {
              Label comositeLabel = new Label();
              FlowLayout fl = new FlowLayout(false);
              fl.setMinorSpacing(0);
              comositeLabel.setLayoutManager(fl);
              comositeLabel.add(toolTip);
              toolTip = comositeLabel;
            }
            toolTip.add(
                new Label(
                    marker.getAttribute(IMarker.MESSAGE, ""), // $NON-NLS-1$
                    nextImage));
          }
          severity = (nextSeverity > severity) ? nextSeverity : severity;
        }
      }
      if (foundMarker == null) {
        return;
      }

      // add decoration
      if (editPart instanceof org.eclipse.gef.GraphicalEditPart) {
        IDecoration decoration = null;

        if (view instanceof Diagram) {
          // There is not yet defined decorator for a diagram
        } else if (view instanceof Edge) {
          decoration = getDecoratorTarget().addConnectionDecoration(getImage(severity), 50, true);
        } else {
          int margin = -1;
          margin =
              MapModeUtil.getMapMode(((org.eclipse.gef.GraphicalEditPart) editPart).getFigure())
                  .DPtoLP(margin);
          decoration =
              getDecoratorTarget()
                  .addShapeDecoration(
                      getImage(severity), IDecoratorTarget.Direction.NORTH_EAST, margin, true);
        }

        if (decoration != null) {
          setDecoration(decoration);

          // getDecaration() returns a {@link Decoration} instead of a
          // {@link IDecoration}
          getDecoration().setToolTip(toolTip);
        }
      }
    }
  /**
   * This method should be called within a workspace modify operation since it creates resources.
   *
   * @generated
   */
  public static Resource createDiagram(
      URI diagramURI, URI modelURI, IProgressMonitor progressMonitor) {
    TransactionalEditingDomain editingDomain =
        GMFEditingDomainFactory.INSTANCE.createEditingDomain();
    progressMonitor.beginTask(
        edu.toronto.cs.se.modelepedia.statemachine_mavo.diagram.part.Messages
            .StateMachine_MAVODiagramEditorUtil_CreateDiagramProgressTask,
        3);
    final Resource diagramResource = editingDomain.getResourceSet().createResource(diagramURI);
    final Resource modelResource = editingDomain.getResourceSet().createResource(modelURI);
    final String diagramName = diagramURI.lastSegment();
    AbstractTransactionalCommand command =
        new AbstractTransactionalCommand(
            editingDomain,
            edu.toronto.cs.se.modelepedia.statemachine_mavo.diagram.part.Messages
                .StateMachine_MAVODiagramEditorUtil_CreateDiagramCommandLabel,
            Collections.EMPTY_LIST) {
          protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
              throws ExecutionException {
            edu.toronto.cs.se.modelepedia.statemachine_mavo.StateMachine model =
                createInitialModel();
            attachModelToResource(model, modelResource);

            Diagram diagram =
                ViewService.createDiagram(
                    model,
                    edu.toronto.cs.se.modelepedia.statemachine_mavo.diagram.edit.parts
                        .StateMachineEditPart.MODEL_ID,
                    edu.toronto.cs.se.modelepedia.statemachine_mavo.diagram.part
                        .StateMachine_MAVODiagramEditorPlugin.DIAGRAM_PREFERENCES_HINT);
            if (diagram != null) {
              diagramResource.getContents().add(diagram);
              diagram.setName(diagramName);
              diagram.setElement(model);
            }

            try {
              modelResource.save(
                  edu.toronto.cs.se.modelepedia.statemachine_mavo.diagram.part
                      .StateMachine_MAVODiagramEditorUtil.getSaveOptions());
              diagramResource.save(
                  edu.toronto.cs.se.modelepedia.statemachine_mavo.diagram.part
                      .StateMachine_MAVODiagramEditorUtil.getSaveOptions());
            } catch (IOException e) {

              edu.toronto.cs.se.modelepedia.statemachine_mavo.diagram.part
                  .StateMachine_MAVODiagramEditorPlugin.getInstance()
                  .logError("Unable to store model and diagram resources", e); // $NON-NLS-1$
            }
            return CommandResult.newOKCommandResult();
          }
        };
    try {
      OperationHistoryFactory.getOperationHistory()
          .execute(command, new SubProgressMonitor(progressMonitor, 1), null);
    } catch (ExecutionException e) {
      edu.toronto.cs.se.modelepedia.statemachine_mavo.diagram.part
          .StateMachine_MAVODiagramEditorPlugin.getInstance()
          .logError("Unable to create model and diagram", e); // $NON-NLS-1$
    }
    setCharset(WorkspaceSynchronizer.getFile(modelResource));
    setCharset(WorkspaceSynchronizer.getFile(diagramResource));
    return diagramResource;
  }
    /** @generated */
    public void refresh() {
      removeDecoration();
      View view = (View) getDecoratorTarget().getAdapter(View.class);
      if (view == null || view.eResource() == null) {
        return;
      }
      EditPart editPart = (EditPart) getDecoratorTarget().getAdapter(EditPart.class);
      if (editPart == null || editPart.getViewer() == null) {
        return;
      }

      // query for all the validation markers of the current resource
      String elementId = ViewUtil.getIdStr(view);
      if (elementId == null) {
        return;
      }
      int severity = IMarker.SEVERITY_INFO;
      IMarker foundMarker = null;
      IResource resource = WorkspaceSynchronizer.getFile(view.eResource());
      if (resource == null || !resource.exists()) {
        return;
      }
      IMarker[] markers = null;
      try {
        markers = resource.findMarkers(MARKER_TYPE, true, IResource.DEPTH_INFINITE);
      } catch (CoreException e) {
        GSN1DiagramEditorPlugin.getInstance()
            .logError("Validation markers refresh failure", e); // $NON-NLS-1$
      }
      if (markers == null || markers.length == 0) {
        return;
      }
      Label toolTip = null;
      for (int i = 0; i < markers.length; i++) {
        IMarker marker = markers[i];
        String attribute =
            marker.getAttribute(
                org.eclipse.gmf.runtime.common.ui.resources.IMarker.ELEMENT_ID, ""); // $NON-NLS-1$
        if (attribute.equals(elementId)) {
          int nextSeverity = marker.getAttribute(IMarker.SEVERITY, IMarker.SEVERITY_INFO);
          Image nextImage = getImage(nextSeverity);
          if (foundMarker == null) {
            foundMarker = marker;
            toolTip =
                new Label(
                    marker.getAttribute(IMarker.MESSAGE, ""), // $NON-NLS-1$
                    nextImage);
          } else {
            if (toolTip.getChildren().isEmpty()) {
              Label comositeLabel = new Label();
              FlowLayout fl = new FlowLayout(false);
              fl.setMinorSpacing(0);
              comositeLabel.setLayoutManager(fl);
              comositeLabel.add(toolTip);
              toolTip = comositeLabel;
            }
            toolTip.add(
                new Label(
                    marker.getAttribute(IMarker.MESSAGE, ""), // $NON-NLS-1$
                    nextImage));
          }
          severity = (nextSeverity > severity) ? nextSeverity : severity;
        }
      }
      if (foundMarker == null) {
        return;
      }

      // add decoration
      if (editPart instanceof org.eclipse.gef.GraphicalEditPart) {
        if (view instanceof Edge) {
          setDecoration(getDecoratorTarget().addConnectionDecoration(getImage(severity), 50, true));
        } else {
          int margin = -1;
          if (editPart instanceof org.eclipse.gef.GraphicalEditPart) {
            margin =
                MapModeUtil.getMapMode(((org.eclipse.gef.GraphicalEditPart) editPart).getFigure())
                    .DPtoLP(margin);
          }
          setDecoration(
              getDecoratorTarget()
                  .addShapeDecoration(
                      getImage(severity), IDecoratorTarget.Direction.NORTH_EAST, margin, true));
        }
        getDecoration().setToolTip(toolTip);
      }
    }
 /** @generated */
 public final void stopResourceListening() {
   mySynchronizer.dispose();
   mySynchronizer = null;
 }