/** @generated */
 public boolean isDeleted(Object element) {
   IDiagramDocument document = getDiagramDocument(element);
   if (document != null) {
     Resource diagramResource = document.getDiagram().eResource();
     if (diagramResource != null) {
       File file = getFile(diagramResource);
       return file != null && !file.exists();
     }
   }
   return super.isDeleted(element);
 }
 /** @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;
 }
 /** @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 */
 public TransactionalEditingDomain getEditingDomain() {
   return myDocument.getEditingDomain();
 }
 /** @generated */
 protected void doSaveDocument(
     IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
     throws CoreException {
   ResourceSetInfo info = getResourceSetInfo(element);
   if (info != null) {
     if (!overwrite && !info.isSynchronized()) {
       throw new CoreException(
           new Status(
               IStatus.ERROR,
               StateChartDiagramEditorPlugin.ID,
               IStatus.ERROR,
               Messages.StateChartDocumentProvider_UnsynchronizedFileSaveError,
               null));
     }
     fireElementStateChanging(element);
     try {
       monitor.beginTask(
           Messages.StateChartDocumentProvider_SaveDiagramTask,
           info.getResourceSet().getResources().size() + 1); // "Saving diagram"
       for (Iterator<Resource> it = info.getLoadedResourcesIterator(); it.hasNext(); ) {
         Resource nextResource = it.next();
         monitor.setTaskName(
             NLS.bind(
                 Messages.StateChartDocumentProvider_SaveNextResourceTask, nextResource.getURI()));
         if (nextResource.isLoaded() && !info.getEditingDomain().isReadOnly(nextResource)) {
           try {
             nextResource.save(StateChartDiagramEditorUtil.getSaveOptions());
           } catch (IOException e) {
             fireElementStateChangeFailed(element);
             throw new CoreException(
                 new Status(
                     IStatus.ERROR,
                     StateChartDiagramEditorPlugin.ID,
                     EditorStatusCodes.RESOURCE_FAILURE,
                     e.getLocalizedMessage(),
                     null));
           }
         }
         monitor.worked(1);
       }
       monitor.done();
       info.setModificationStamp(computeModificationStamp(info));
     } catch (RuntimeException x) {
       fireElementStateChangeFailed(element);
       throw x;
     }
   } else {
     URI newResoruceURI;
     List<IFile> affectedFiles = null;
     if (element instanceof URIEditorInput) {
       newResoruceURI = ((URIEditorInput) element).getURI();
     } else {
       fireElementStateChangeFailed(element);
       throw new CoreException(
           new Status(
               IStatus.ERROR,
               StateChartDiagramEditorPlugin.ID,
               0,
               NLS.bind(
                   Messages.StateChartDocumentProvider_IncorrectInputError,
                   new Object[] {
                     element, "org.eclipse.emf.common.ui.URIEditorInput"
                   }), //$NON-NLS-1$
               null));
     }
     if (false == document instanceof IDiagramDocument) {
       fireElementStateChangeFailed(element);
       throw new CoreException(
           new Status(
               IStatus.ERROR,
               StateChartDiagramEditorPlugin.ID,
               0,
               "Incorrect document used: "
                   + document
                   + " instead of org.eclipse.gmf.runtime.diagram.ui.resources.editor.document.IDiagramDocument",
               null)); //$NON-NLS-1$ //$NON-NLS-2$
     }
     IDiagramDocument diagramDocument = (IDiagramDocument) document;
     final Resource newResource =
         diagramDocument.getEditingDomain().getResourceSet().createResource(newResoruceURI);
     final Diagram diagramCopy = (Diagram) EcoreUtil.copy(diagramDocument.getDiagram());
     try {
       new AbstractTransactionalCommand(
           diagramDocument.getEditingDomain(),
           NLS.bind(Messages.StateChartDocumentProvider_SaveAsOperation, diagramCopy.getName()),
           affectedFiles) {
         protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
             throws ExecutionException {
           newResource.getContents().add(diagramCopy);
           return CommandResult.newOKCommandResult();
         }
       }.execute(monitor, null);
       newResource.save(StateChartDiagramEditorUtil.getSaveOptions());
     } catch (ExecutionException e) {
       fireElementStateChangeFailed(element);
       throw new CoreException(
           new Status(
               IStatus.ERROR, StateChartDiagramEditorPlugin.ID, 0, e.getLocalizedMessage(), null));
     } catch (IOException e) {
       fireElementStateChangeFailed(element);
       throw new CoreException(
           new Status(
               IStatus.ERROR, StateChartDiagramEditorPlugin.ID, 0, e.getLocalizedMessage(), null));
     }
     newResource.unload();
   }
 }
 /** @generated */
 protected void setDocumentContent(IDocument document, IEditorInput element) throws CoreException {
   IDiagramDocument diagramDocument = (IDiagramDocument) document;
   TransactionalEditingDomain domain = diagramDocument.getEditingDomain();
   if (element instanceof URIEditorInput) {
     URI uri = ((URIEditorInput) element).getURI();
     Resource resource = null;
     try {
       resource = domain.getResourceSet().getResource(uri.trimFragment(), false);
       if (resource == null) {
         resource = domain.getResourceSet().createResource(uri.trimFragment());
       }
       if (!resource.isLoaded()) {
         try {
           Map options = new HashMap(GMFResourceFactory.getDefaultLoadOptions());
           // @see 171060
           // options.put(org.eclipse.emf.ecore.xmi.XMLResource.OPTION_RECORD_UNKNOWN_FEATURE,
           // Boolean.TRUE);
           resource.load(options);
         } catch (IOException e) {
           resource.unload();
           throw e;
         }
       }
       if (uri.fragment() != null) {
         EObject rootElement = resource.getEObject(uri.fragment());
         if (rootElement instanceof Diagram) {
           document.setContent((Diagram) rootElement);
           return;
         }
       } else {
         for (Iterator it = resource.getContents().iterator(); it.hasNext(); ) {
           Object rootElement = it.next();
           if (rootElement instanceof Diagram) {
             document.setContent((Diagram) rootElement);
             return;
           }
         }
       }
       throw new RuntimeException(Messages.StateChartDocumentProvider_NoDiagramInResourceError);
     } catch (Exception e) {
       CoreException thrownExcp = null;
       if (e instanceof CoreException) {
         thrownExcp = (CoreException) e;
       } else {
         String msg = e.getLocalizedMessage();
         thrownExcp =
             new CoreException(
                 new Status(
                     IStatus.ERROR,
                     StateChartDiagramEditorPlugin.ID,
                     0,
                     msg != null ? msg : Messages.StateChartDocumentProvider_DiagramLoadingError,
                     e));
       }
       throw thrownExcp;
     }
   } else {
     throw new CoreException(
         new Status(
             IStatus.ERROR,
             StateChartDiagramEditorPlugin.ID,
             0,
             NLS.bind(
                 Messages.StateChartDocumentProvider_IncorrectInputError,
                 new Object[] {
                   element, "org.eclipse.emf.common.ui.URIEditorInput"
                 }), //$NON-NLS-1$
             null));
   }
 }
  @Override
  protected void doSaveDocument(
      IProgressMonitor monitor, Object element, IDocument document, boolean overwrite)
      throws CoreException {

    try {
      // Automatic validation with result
      IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
      CustomValidateAction action = new CustomValidateAction(page, (IEditorInput) element);
      monitor.setTaskName("Validation");
      action.run(monitor);
      if (!action.result) {
        // If validation failed, do not save
        ProblemsView problem = (ProblemsView) page.findView("org.eclipse.ui.views.ProblemView");
        page.activate(problem);
        monitor.setCanceled(true);
        return;
      }
    } catch (Exception e) {
      MindDiagramEditorPlugin.getInstance().logError("Problems occured during validation", e);
      return;
    }

    MindProxy mindRoot = MindProxyFactory.INSTANCE.getRootProxy();
    HashMap<String, Rectangle> boundsMemory = new HashMap<String, Rectangle>();
    HashMap<String, Bendpoints> bendpointsMemory = new HashMap<String, Bendpoints>();
    if (mindRoot != null) {
      SaveUtil.saveBounds(mindRoot.getEditPart(), boundsMemory, bendpointsMemory);
    }

    // Prepare the transaction that will prepare the main definition
    // All merged items are deleted because they must not be serialized
    TransactionalEditingDomain domain = getDiagramDocument(element).getEditingDomain();
    TransactionImpl transaction = new TransactionImpl(domain, false);
    EObject root = ((DiagramImpl) document.getContent()).getElement();

    ResourceSetInfo info = getResourceSetInfo(element);
    if (info != null) {
      if (!overwrite && !info.isSynchronized()) {
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                MindDiagramEditorPlugin.ID,
                IResourceStatus.OUT_OF_SYNC_LOCAL,
                Messages.MindDocumentProvider_UnsynchronizedFileSaveError,
                null));
      }
      info.stopResourceListening();
      fireElementStateChanging(element);
      try {
        monitor.beginTask(
            Messages.MindDocumentProvider_SaveDiagramTask,
            info.getResourceSet().getResources().size() + 1); // "Saving diagram"

        LazyLinkingResource xtextResource = null;
        GMFResource gmfResource = null;

        for (Iterator /*<org.eclipse.emf.ecore.resource.Resource>*/<?> it =
                info.getLoadedResourcesIterator();
            it.hasNext(); ) {
          Resource nextResource = (Resource) it.next();
          monitor.setTaskName(
              NLS.bind(Messages.MindDocumentProvider_SaveNextResourceTask, nextResource.getURI()));
          if (nextResource.isLoaded() && !info.getEditingDomain().isReadOnly(nextResource)) {
            if (nextResource instanceof LazyLinkingResource) {
              // Serialize later
              xtextResource = (LazyLinkingResource) nextResource;
            } else {
              // Save GMF
              try {
                if (nextResource instanceof GMFResource) gmfResource = (GMFResource) nextResource;
                nextResource.save(MindDiagramEditorUtil.getSaveOptions());
              } catch (IOException e) {
                fireElementStateChangeFailed(element);
                throw new CoreException(
                    new Status(
                        IStatus.ERROR,
                        MindDiagramEditorPlugin.ID,
                        EditorStatusCodes.RESOURCE_FAILURE,
                        e.getLocalizedMessage(),
                        null));
              }
            }
          }
          monitor.worked(1);
        }

        // Delete merged elements from the model before saving
        if (root instanceof AdlDefinitionCustomImpl) {
          try {
            transaction.start();
            prepareMainDefinitionBeforeSave((AdlDefinitionCustomImpl) root);
            transaction.commit();
          } catch (InterruptedException e) {
            MindDiagramEditorPlugin.getInstance().logError("Clean merge failed", e);
          } catch (RollbackException e) {
            MindDiagramEditorPlugin.getInstance().logError("Clean merge failed", e);
            transaction.rollback();
          } finally {
          }
        }

        // Merged items are deleted, they will not to be serialized
        // We can save xtext resource
        try {
          xtextResource.save(MindDiagramEditorUtil.getSaveOptions());
        } catch (IOException e) {
          fireElementStateChangeFailed(element);
          throw new CoreException(
              new Status(
                  IStatus.ERROR,
                  MindDiagramEditorPlugin.ID,
                  EditorStatusCodes.RESOURCE_FAILURE,
                  e.getLocalizedMessage(),
                  null));
        }

        // Restore merged elements
        if (root instanceof AdlDefinitionCustomImpl) {
          try {
            transaction.start();
            restoreMainDefinitionAfterSave((AdlDefinitionCustomImpl) root);
            transaction.commit();
          } catch (InterruptedException e) {
            MindDiagramEditorPlugin.getInstance().logError("Restore merge failed", e);
          } catch (RollbackException e) {
            e.printStackTrace();
            MindDiagramEditorPlugin.getInstance().logError("Restore merge failed", e);
            transaction.rollback();
          } finally {
          }
        }

        // Update diagram
        try {
          MindDiagramUpdateCommand update = new MindDiagramUpdateAllCommand(false);
          update.execute(new ExecutionEvent());
        } catch (ExecutionException e) {
          MindDiagramEditorPlugin.getInstance().logError("Update failed", e);
        } finally {
        }

        // Now that editParts have been recreated by the update,
        // we are able to restore the saved bounds
        if (mindRoot != null) {
          SaveUtil.restoreBounds(mindRoot.getEditPart(), boundsMemory, bendpointsMemory);
          boundsMemory.clear();
        }

        // DocumentProvider thinks resource is modified because of restoreMainDefinition
        // Set value to false
        gmfResource.setModified(false);

        monitor.done();
        info.setModificationStamp(computeModificationStamp(info));
      } catch (RuntimeException x) {
        fireElementStateChangeFailed(element);
        throw x;
      } finally {
        info.startResourceListening();
      }
    } else {
      URI newResoruceURI;
      List<IFile> affectedFiles = null;
      if (element instanceof FileEditorInput) {
        IFile newFile = ((FileEditorInput) element).getFile();
        affectedFiles = Collections.singletonList(newFile);
        newResoruceURI = URI.createPlatformResourceURI(newFile.getFullPath().toString(), true);
      } else if (element instanceof URIEditorInput) {
        newResoruceURI = ((URIEditorInput) element).getURI();
      } else {
        fireElementStateChangeFailed(element);
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                MindDiagramEditorPlugin.ID,
                0,
                NLS.bind(
                    Messages.MindDocumentProvider_IncorrectInputError,
                    new Object[] {
                      element,
                      "org.eclipse.ui.part.FileEditorInput",
                      "org.eclipse.emf.common.ui.URIEditorInput"
                    }), //$NON-NLS-1$ //$NON-NLS-2$
                null));
      }
      if (false == document instanceof IDiagramDocument) {
        fireElementStateChangeFailed(element);
        throw new CoreException(
            new Status(
                IStatus.ERROR,
                MindDiagramEditorPlugin.ID,
                0,
                "Incorrect document used: "
                    + document
                    + " instead of org.eclipse.gmf.runtime.diagram.ui.resources.editor.document.IDiagramDocument",
                null)); //$NON-NLS-1$ //$NON-NLS-2$
      }
      IDiagramDocument diagramDocument = (IDiagramDocument) document;
      final Resource newResource =
          diagramDocument.getEditingDomain().getResourceSet().createResource(newResoruceURI);
      final Diagram diagramCopy = (Diagram) EcoreUtil.copy(diagramDocument.getDiagram());
      try {
        new AbstractTransactionalCommand(
            diagramDocument.getEditingDomain(),
            NLS.bind(Messages.MindDocumentProvider_SaveAsOperation, diagramCopy.getName()),
            affectedFiles) {
          protected CommandResult doExecuteWithResult(IProgressMonitor monitor, IAdaptable info)
              throws ExecutionException {
            newResource.getContents().add(diagramCopy);
            return CommandResult.newOKCommandResult();
          }
        }.execute(monitor, null);
        newResource.save(MindDiagramEditorUtil.getSaveOptions());
      } catch (ExecutionException e) {
        fireElementStateChangeFailed(element);
        throw new CoreException(
            new Status(
                IStatus.ERROR, MindDiagramEditorPlugin.ID, 0, e.getLocalizedMessage(), null));
      } catch (IOException e) {
        fireElementStateChangeFailed(element);
        throw new CoreException(
            new Status(
                IStatus.ERROR, MindDiagramEditorPlugin.ID, 0, e.getLocalizedMessage(), null));
      }
      newResource.unload();
    }
  }