/** Open a new Window with the visualization of the selected information. */
  @Override
  public void run() {

    if (window == null) {
      return;
    }

    // get the activate page
    IWorkbenchPage page = window.getActivePage();
    if (page == null) {
      return;
    }
    IViewPart view = page.findView(ConstraintView.ID);
    if (view == null) {
      return;
    }

    if (!page.isPartVisible(view)) {
      // use the Resource Manager View id to open up view
      try {
        view = page.showView(ConstraintView.ID);
      } catch (PartInitException e) {
        System.err.println("Failed to open the Constrains View " + e);
      }
    }
    // Refresh the View
    if (view instanceof ConstraintView) ((ConstraintView) view).refresh();

    // Set Focus
    page.activate(view);
  }
コード例 #2
0
 /**
  * Finds a view with the given ID
  *
  * @param viewID the view ID
  * @return the view part
  * @throws PartInitException
  */
 public static IViewPart findView(String viewID) {
   IWorkbenchPage page = getActivePage();
   if (page != null) {
     return page.findView(viewID);
   }
   return null;
 }
コード例 #3
0
  /**
   * Changes the state of the TransformationView according to the currently selected shape
   *
   * @see ISelectionChangedListener#selectionChanged(SelectionChangedEvent event)
   */
  @Override
  public void selectionChanged(SelectionChangedEvent event) {

    // Get the TransformationView if it is open

    TransformationView transformationView =
        (TransformationView) workbenchPage.findView(TransformationView.ID);

    // Return if not

    if (transformationView == null) {
      return;
    }
    // Get the tree paths

    ITreeSelection selection = (ITreeSelection) event.getSelection();
    TreePath[] paths = selection.getPaths();

    // Remove the "selected" value from previously selected shapes

    for (IShape shape : selectedShapes) {
      shape.removeProperty("selected");
    }

    selectedShapes.clear();

    // Set the "selected" value to true for newly selected shapes

    for (TreePath path : paths) {
      Object selectedObject = path.getLastSegment();

      // Only perform the action for selected IShapes
      // (rather than GeometryComponents or null)

      if (selectedObject instanceof IShape) {
        IShape selectedShape = (IShape) selectedObject;

        selectedShape.setProperty("selected", "true");
        selectedShapes.add(selectedShape);
      }
    }

    // Set the TransformationView shape to null if nothing is selected
    // or there are multiple selections

    if (paths.length != 1) {
      transformationView.setShape(null);
      return;
    }

    Object selectedObject = paths[0].getLastSegment();

    // Determine if the shape of the TransformationView should be set

    if (selectedObject instanceof IShape) {
      transformationView.setShape((IShape) selectedObject);
    } else {
      transformationView.setShape(null);
    }
  }
コード例 #4
0
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
    IWorkbenchPage page = window.getActivePage();
    View view = (View) page.findView(View.ID);
    view.getViewer().refresh();

    // open dialog to get path
    FileDialog filedlg = new FileDialog(window.getShell(), SWT.SAVE);
    filedlg.setText("Create Sequence Diagram File");
    filedlg.setFilterPath("SystemRoot");
    filedlg.setFilterExtensions(new String[] {"di"});
    String selected = filedlg.open();

    // create & initial the sequence diagram
    MyCreater myCreater = new MyCreater();
    myCreater.init(window.getWorkbench(), new StructuredSelection()); // fixed bug
    IFile iFile = myCreater.create(selected);

    // create the model
    SequenceDiagram sdDiagram = new SequenceDiagram();
    sdDiagram.setiFile(iFile);
    sdDiagram.setFilePath(
        new Path(selected).removeFileExtension().addFileExtension("uml").toOSString());
    ModelManager.getInstance().AddModel(sdDiagram);

    // open the editor
    myCreater.open(iFile);

    // refresh the model viewer
    view.getViewer().refresh();

    return null;
  }
コード例 #5
0
 /**
  * Attempts to find an appropriate view to emulate, this will either be the variables view or
  * the expressions view.
  *
  * @return a view to emulate or <code>null</code>
  */
 private AbstractDebugView getViewToEmulate() {
   IWorkbenchPage page =
       Activator.getDefault().getWorkbench().getActiveWorkbenchWindow().getActivePage();
   AbstractDebugView expressionsView =
       (AbstractDebugView) page.findView(IDebugUIConstants.ID_EXPRESSION_VIEW);
   if (expressionsView != null && expressionsView.isVisible()) {
     return expressionsView;
   }
   AbstractDebugView variablesView =
       (AbstractDebugView) page.findView(IDebugUIConstants.ID_VARIABLE_VIEW);
   if (variablesView != null && variablesView.isVisible()) {
     return variablesView;
   }
   if (expressionsView != null) {
     return expressionsView;
   }
   return variablesView;
 }
コード例 #6
0
 /**
  * DOC msjian Comment method "getContextView".
  *
  * @return
  */
 protected IViewPart getContextView() {
   IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
   String id = page.getPerspective().getId();
   String viewId = AbstractContextView.CTX_ID_DESIGNER;
   if (id.equals(IBrandingConfiguration.PERSPECTIVE_DQ_ID)) {
     viewId = AbstractContextView.CTX_ID_TDQ;
   }
   return page.findView(viewId);
 }
コード例 #7
0
 private void refreshProjectExplorer() {
   IWorkbenchPage workbenchPage = ForgeCommandPostProcessorHelper.getActiveWorkbenchPage();
   if (workbenchPage != null) {
     IViewPart projectExplorer =
         workbenchPage.findView("org.eclipse.ui.navigator.ProjectExplorer");
     if (projectExplorer != null && projectExplorer instanceof CommonNavigator) {
       ((CommonNavigator) projectExplorer).getCommonViewer().refresh();
     }
   }
 }
コード例 #8
0
  private void updatePropertiesView(IStructuredSelection selection) {
    IWorkbench workbench = PlatformUI.getWorkbench();
    if (workbench == null) return;
    IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
    if (window == null) return;
    IWorkbenchPage page = window.getActivePage();
    if (page == null) return;
    PropertySheet propertiesView = (PropertySheet) page.findView(IPageLayout.ID_PROP_SHEET);
    if (propertiesView == null) return;

    propertiesView.partActivated(EFactoryWithTreeEditor.this);
    propertiesView.selectionChanged(EFactoryWithTreeEditor.this, selection);
  }
 @Override
 public Object execute(ExecutionEvent event) throws ExecutionException {
   IWorkbenchWindow activeWorkbenchWindow = HandlerUtil.getActiveWorkbenchWindow(event);
   IWorkbenchPage activePage = activeWorkbenchWindow.getActivePage();
   if (activePage != null) {
     IViewPart view = activePage.findView(OverviewView.ID);
     if (view instanceof OverviewView) {
       OverviewView overviewView = (OverviewView) view;
       overviewView.refreshOverviewView();
     }
   }
   return null;
 }
コード例 #10
0
 @Override
 public Object execute(ExecutionEvent event) throws ExecutionException {
   IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
   ModelProvider persons = ModelProvider.INSTANCE;
   AddPersonDialog dialog = new AddPersonDialog(window.getShell());
   dialog.open();
   if (dialog.getPerson() != null) {
     persons.getPersons().add(dialog.getPerson());
     // Updating the display in the view
     IWorkbenchPage page = window.getActivePage();
     View view = (View) page.findView(View.ID);
     view.refresh();
   }
   return null;
 }
コード例 #11
0
ファイル: NewCommand.java プロジェクト: reedcourty/denafutsal
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {

    ViewData.instance().setModel(null);

    IWorkbenchPage activePage = HandlerUtil.getActiveWorkbenchWindow(event).getActivePage();
    activePage.hideView(activePage.findView(MainView.ID));
    try {
      activePage.showView(MainView.ID);
    } catch (PartInitException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }

    return null;
  }
コード例 #12
0
 private static TypeHierarchyViewPart openInViewPart(IWorkbenchWindow window, IMemberInfo input) {
   IWorkbenchPage page = window.getActivePage();
   try {
     TypeHierarchyViewPart result =
         (TypeHierarchyViewPart) page.findView(X10Constants.ID_TYPE_HIERARCHY);
     if (result != null) {
       result.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
     }
     result = (TypeHierarchyViewPart) page.showView(X10Constants.ID_TYPE_HIERARCHY);
     result.setInputElement(input);
     return result;
   } catch (CoreException e) {
     //			ExceptionHandler.handle(e, window.getShell(),
     //				Messages.OpenTypeHierarchyUtil_error_open_view, e.getMessage());
     X10DTUIPlugin.log(e);
   }
   return null;
 }
コード例 #13
0
  public static void install() {
    IWorkbenchPage page = CeylonTestUtil.getActivePage();

    IViewPart part = page.findView(PackageExplorerPart.VIEW_ID);
    if (part != null) {
      PackageExplorerPart packageExplorerPart = (PackageExplorerPart) part;
      install(packageExplorerPart);
    }

    page.addPartListener(
        new IPartListener2() {
          @Override
          public void partOpened(IWorkbenchPartReference partRef) {
            if (partRef.getId().equals(PackageExplorerPart.VIEW_ID)) {
              IWorkbenchPart part = partRef.getPart(false);
              if (part != null) {
                PackageExplorerPart packageExplorerPart = (PackageExplorerPart) part;
                install(packageExplorerPart);
              }
            }
          }

          @Override
          public void partVisible(IWorkbenchPartReference partRef) {}

          @Override
          public void partInputChanged(IWorkbenchPartReference partRef) {}

          @Override
          public void partHidden(IWorkbenchPartReference partRef) {}

          @Override
          public void partDeactivated(IWorkbenchPartReference partRef) {}

          @Override
          public void partClosed(IWorkbenchPartReference partRef) {}

          @Override
          public void partBroughtToTop(IWorkbenchPartReference partRef) {}

          @Override
          public void partActivated(IWorkbenchPartReference partRef) {}
        });
  }
コード例 #14
0
  @Override
  public void loadPixelPerfectData(IHvDevice device) {
    super.loadPixelPerfectData(device);

    // The windows tab hides the tree tab, so let's bring the tree tab
    // forward.

    IWorkbenchWindow[] windows =
        HierarchyViewerPlugin.getPlugin().getWorkbench().getWorkbenchWindows();
    for (IWorkbenchWindow window : windows) {
      IWorkbenchPage page = window.getActivePage();
      if (page.getPerspective().getId().equals(PixelPerfectPespective.ID)) {
        try {
          IWorkbenchPart part = page.findView(PixelPerfectTreeView.ID);
          if (part != null) {
            page.showView(PixelPerfectTreeView.ID);
          }
        } catch (PartInitException e) {

        }
      }
    }
  }
コード例 #15
0
  @Override
  public void loadViewTreeData(Window window) {
    super.loadViewTreeData(window);

    // The windows tab hides the property tab, so let's bring the property
    // tab
    // forward.

    IWorkbenchWindow[] windows =
        HierarchyViewerPlugin.getPlugin().getWorkbench().getWorkbenchWindows();
    for (IWorkbenchWindow currentWindow : windows) {
      IWorkbenchPage page = currentWindow.getActivePage();
      if (page.getPerspective().getId().equals(TreeViewPerspective.ID)) {
        try {
          IWorkbenchPart part = page.findView(PropertyView.ID);
          if (part != null) {
            page.showView(PropertyView.ID);
          }
        } catch (PartInitException e) {

        }
      }
    }
  }
コード例 #16
0
  private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IMemberInfo input)
      throws WorkbenchException, Exception {
    IWorkbench workbench = X10DTUIPlugin.getInstance().getWorkbench();
    // The problem is that the input element can be a working copy. So we first convert it to the
    // original element if
    // it exists.
    IMemberInfo perspectiveInput = input;

    if (input instanceof IMemberInfo) {
      if (!(input instanceof ITypeInfo)) {
        perspectiveInput = ((IMemberInfo) input).getDeclaringType();
      } else {
        perspectiveInput = input;
      }
    }
    ;
    IWorkbenchPage page =
        workbench.showPerspective(
            X10Constants.ID_HIERARCHYPERSPECTIVE,
            window,
            SearchUtils.getResource(perspectiveInput));

    TypeHierarchyViewPart part =
        (TypeHierarchyViewPart) page.findView(X10Constants.ID_TYPE_HIERARCHY);
    if (part != null) {
      part.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
    }
    part = (TypeHierarchyViewPart) page.showView(X10Constants.ID_TYPE_HIERARCHY);
    part.setInputElement(input);
    if (input instanceof IMemberInfo) {
      if (page.getEditorReferences().length == 0) {
        SearchUtils.openEditor(input);
      }
    }
    return part;
  }
コード例 #17
0
  /* (non-Javadoc)
   * @see org.eclipse.core.commands.IHandler#execute(org.eclipse.core.commands.ExecutionEvent)
   */
  @SuppressWarnings("rawtypes")
  @Override
  public Object execute(ExecutionEvent event) throws ExecutionException {
    // Get the view
    IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindow(event);
    IWorkbenchPage page = window.getActivePage();
    IViewPart view = page.findView(LogResourcesView.ID);
    // Get the selection
    ISelection selection = view.getSite().getSelectionProvider().getSelection();
    if ((selection != null) && (selection instanceof IStructuredSelection)) {
      if (!MessageDialog.openQuestion(
          Display.getDefault().getActiveShell(),
          Messages.RemoveLogResourceHandler_confirm_title,
          Messages.RemoveLogResourceHandler_confirm_question)) {
        return null;
      }

      // Collect for multi status
      List<IStatus> statuses = new ArrayList<IStatus>();
      Iterator it = ((IStructuredSelection) selection).iterator();
      while (it.hasNext()) {
        ILogResource log = (ILogResource) it.next();
        if (UIPlugin.getDefault().getLogResourceManager().isJobInProgress(log)) {
          // Log index is in use
          statuses.add(
              new Status(
                  IStatus.INFO,
                  UIPlugin.PLUGIN_ID,
                  NLS.bind(Messages.Generic_info_jobInProgress, log.getName())));
          continue;
        }

        // Close editors
        IEditorReference[] editorRefs =
            page.findEditors(
                (IEditorInput) log.getAdapter(IEditorInput.class),
                null,
                IWorkbenchPage.MATCH_INPUT);
        page.closeEditors(editorRefs, false);

        try {
          UIPlugin.getDefault().getLogResourceManager().remove(log);
        } catch (CoreException e) {
          statuses.add(e.getStatus());
        }
      }

      // Save log resources
      try {
        UIPlugin.getDefault().getLogResourceManager().saveState();
      } catch (CoreException e) {
        statuses.add(e.getStatus());
      }

      // Refresh resource view
      IRefreshablePart refresh = (IRefreshablePart) view.getAdapter(IRefreshablePart.class);
      if (refresh != null) {
        refresh.refresh();
      }

      if (!statuses.isEmpty()) {
        IStatus multiStatus =
            new MultiStatus(
                UIPlugin.PLUGIN_ID,
                0,
                statuses.toArray(new IStatus[statuses.size()]),
                Messages.RemoveLogResourceHandler_info_someCouldNotBeRemoved,
                null);
        // Log and show error
        UIPlugin.logAndShowError(new CoreException(multiStatus), false);
      }
    }
    return null;
  }
コード例 #18
0
  @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();
    }
  }
コード例 #19
0
 /**
  * get the cheet sheet view.
  *
  * @return CheatSheetView
  */
 public CheatSheetView findCheetSheet() {
   IWorkbench workbench = PlatformUI.getWorkbench();
   IWorkbenchWindow window = workbench.getActiveWorkbenchWindow();
   IWorkbenchPage page = window.getActivePage();
   return (CheatSheetView) page.findView(ICheatSheetResource.CHEAT_SHEET_VIEW_ID);
 }
コード例 #20
0
  @Override
  public void createPartControl(Composite parent) {

    fileManager = new FileManager(new SetupContextHelper());

    parent.setLayout(new GridLayout());
    viewer = new TableViewer(parent);
    viewer.getTable().setLayoutData(new GridData(SWT.FILL, SWT.FILL, true, true));
    viewer.setLabelProvider(new ViewLabelProvider());
    viewer.setContentProvider(new BasicContentProvider());
    viewer.setInput(fileManager);
    viewer.addSelectionChangedListener(
        new ISelectionChangedListener() {

          @Override
          public void selectionChanged(SelectionChangedEvent event) {
            if (event.getSelection() instanceof StructuredSelection) {
              inputData = null;
              eventManager.sendInputDataUpdate(null);
              selectedFile =
                  (String) ((StructuredSelection) event.getSelection()).getFirstElement();
              update(currentOperation);
            }
          }
        });
    ColumnViewerToolTipSupport.enableFor(viewer);

    DropTargetAdapter dropListener =
        new DropTargetAdapter() {
          @Override
          public void drop(DropTargetEvent event) {
            Object dropData = event.data;
            if (dropData instanceof TreeSelection) {
              TreeSelection selectedNode = (TreeSelection) dropData;
              Object obj[] = selectedNode.toArray();
              List<String> paths = new ArrayList<String>();
              for (int i = 0; i < obj.length; i++) {
                if (obj[i] instanceof IFile) {
                  IFile file = (IFile) obj[i];
                  paths.add(file.getLocation().toOSString());
                }
              }

              if (!paths.isEmpty()) fileManager.addFiles(paths.toArray(new String[paths.size()]));

            } else if (dropData instanceof String[]) {
              fileManager.addFiles((String[]) dropData);
            }
            viewer.setInput(fileManager);
          }
        };

    DropTarget dt =
        new DropTarget(viewer.getControl(), DND.DROP_MOVE | DND.DROP_DEFAULT | DND.DROP_COPY);
    dt.setTransfer(
        new Transfer[] {
          TextTransfer.getInstance(),
          FileTransfer.getInstance(),
          ResourceTransfer.getInstance(),
          LocalSelectionTransfer.getTransfer()
        });
    dt.addDropListener(dropListener);

    csw = new ChangeSliceWidget(parent);
    csw.addSliceChangeListener(
        new ISliceChangeListener() {

          @Override
          public void sliceChanged(SliceChangeEvent event) {
            inputData = null;
            eventManager.sendInputDataUpdate(null);
            String ss = Slice.createString(csw.getCurrentSlice());
            currentSliceLabel.setText("Current slice of data: [" + ss + "]");
            currentSliceLabel.getParent().layout(true);
            update(currentOperation);
          }
        });

    csw.disable();

    final MenuManager rightClick = new MenuManager();
    createActions(rightClick);
    viewer.getControl().setMenu(rightClick.createContextMenu(viewer.getControl()));

    getSite()
        .getPage()
        .addSelectionListener(
            "org.dawnsci.processing.ui.processingView",
            new ISelectionListener() {

              @Override
              public void selectionChanged(IWorkbenchPart part, ISelection selection) {

                if (selection instanceof StructuredSelection
                    && ((StructuredSelection) selection).getFirstElement()
                        instanceof OperationDescriptor) {
                  OperationDescriptor des =
                      (OperationDescriptor) ((StructuredSelection) selection).getFirstElement();
                  try {

                    currentOperation = des.getSeriesObject();
                    update(currentOperation);
                  } catch (InstantiationException e) {
                    logger.error(e.getMessage(), e);
                  }
                } else {
                  if (getOperations() == null || getOperations().length == 0) {
                    output.clear();
                  }
                }
              }
            });

    currentSliceLabel = new Label(parent, SWT.WRAP);
    currentSliceLabel.setText("Current slice of data: [ - - - - -]");

    IWorkbenchPage page = getSite().getPage();
    IViewPart view = page.findView("org.dawnsci.processing.ui.output");
    output = (IPlottingSystem<Composite>) view.getAdapter(IPlottingSystem.class);

    view = page.findView("org.dawnsci.processing.ui.input");
    input = (IPlottingSystem<Composite>) view.getAdapter(IPlottingSystem.class);

    fileManager.addFileListener(
        new IFilesAddedListener() {

          @Override
          public void filesAdded(FileAddedEvent event) {

            String[] paths = event.getPaths();
            boolean[] success = event.getSuccess();

            int first = -1;
            final List<String> failedPaths = new ArrayList<String>();
            for (int i = 0; i < success.length; i++) {
              if (success[i] && first < 0) first = i;
              if (!success[i]) failedPaths.add(paths[i]);
            }

            String dsName = "";

            try {
              dsName = " (" + fileManager.getContext().getDatasetNames().get(0) + ")";
            } catch (Exception e) {
              // ignore
            }

            final String dsn = dsName;

            final int f = first;

            Display.getDefault()
                .syncExec(
                    new Runnable() {

                      @Override
                      public void run() {
                        if (f < 0) {
                          MessageDialog.openError(
                              getSite().getShell(),
                              "Error loading files",
                              "None of the selected files contained suitable datasets" + dsn + "!");
                          return;
                        }

                        if (!failedPaths.isEmpty()) {
                          StringBuilder sb = new StringBuilder();
                          sb.append("Failed to load: ");
                          for (String p : failedPaths) sb.append(p + ", ");
                          sb.append("did not contain suitable datasets");
                          sb.append(dsn);

                          MessageDialog.openError(
                              getSite().getShell(), "Error loading some files", sb.toString());
                        }
                      }
                    });

            if (f < 0) return;

            final String path = paths[first];

            Display.getDefault()
                .syncExec(
                    new Runnable() {

                      @Override
                      public void run() {
                        viewer.refresh();
                        viewer.setSelection(new StructuredSelection(path), true);
                      }
                    });
          }
        });

    eventManager.addOperationRunnerListener(
        new IOperationGUIRunnerListener.Stub() {
          @Override
          public void updateRequested() {
            update(currentOperation);
          }
        });

    // hook up delete key to remove from list
    viewer
        .getTable()
        .addKeyListener(
            new KeyListener() {

              @Override
              public void keyReleased(KeyEvent e) {}

              @Override
              public void keyPressed(KeyEvent e) {
                if (e.keyCode == SWT.DEL) {
                  clearSelected();
                }
              }
            });
  }
コード例 #21
0
  private void selectFiles(IProject project, List<? extends IResource> createdFiles) {
    // Attempt to select the newly created files in the Package Explorer
    IWorkbench workbench = AdtPlugin.getDefault().getWorkbench();
    IWorkbenchPage page = workbench.getActiveWorkbenchWindow().getActivePage();
    IViewPart viewPart = page.findView(JavaUI.ID_PACKAGES);
    if (viewPart != null) {
      IWorkbenchPartSite site = viewPart.getSite();
      IJavaProject javaProject = null;
      try {
        javaProject = BaseProjectHelper.getJavaProject(project);
      } catch (CoreException e) {
        AdtPlugin.log(e, null);
      }
      final ISelectionProvider provider = site.getSelectionProvider();
      if (provider != null) {
        List<TreePath> pathList = new ArrayList<TreePath>();
        for (IResource file : createdFiles) {
          // Create a TreePath for the given file,
          // which should be the JavaProject, followed by the folders down to
          // the final file.
          List<Object> segments = new ArrayList<Object>();
          segments.add(file);
          IContainer folder = file.getParent();
          if (folder != null && !(folder instanceof IProject)) {
            segments.add(folder);
            // res folder
            folder = folder.getParent();
            if (folder != null && !(folder instanceof IProject)) {
              segments.add(folder);
            }
          }
          // project
          segments.add(javaProject);

          Collections.reverse(segments);
          TreePath path = new TreePath(segments.toArray());
          pathList.add(path);

          // IDEA: Maybe normalize the files backwards (IFile objects aren't unique)
          // by maybe using the package explorer icons instead
        }

        TreePath[] paths = pathList.toArray(new TreePath[pathList.size()]);
        final TreeSelection selection = new TreeSelection(paths);

        provider.setSelection(selection);

        // Workaround: The above doesn't always work; it will frequently select
        // some siblings of the real files. I've tried a number of workarounds:
        // normalizing the IFile objects by looking up the canonical ones via
        // their relative paths from the project; deferring execution with
        // Display.asyncRun; first calling select on the parents, etc.
        // However, it turns out a simple workaround works best: Calling this
        // method TWICE. The first call seems to expand all the necessary parents,
        // and the second call ensures that the correct children are selected!
        provider.setSelection(selection);

        viewPart.setFocus();
      }
    }
  }
コード例 #22
0
 private void refreshTodosView() {
   IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
   Optional<TodosView> view =
       Optional.ofNullable((TodosView) page.findView("com.starterkit3.views.TodosView"));
   if (view.isPresent()) view.get().refreshTable();
 }