/** Selects and reveals the given offset and length in the given editor part. */
  public static void revealInEditor(IEditorPart editor, final int offset, final int length) {
    if (editor instanceof ITextEditor) {
      ((ITextEditor) editor).selectAndReveal(offset, length);
      return;
    }

    // Support for non-text editor - try IGotoMarker interface
    if (editor instanceof IGotoMarker) {
      final IEditorInput input = editor.getEditorInput();
      if (input instanceof IFileEditorInput) {
        final IGotoMarker gotoMarkerTarget = (IGotoMarker) editor;
        WorkspaceModifyOperation op =
            new WorkspaceModifyOperation() {
              @Override
              protected void execute(IProgressMonitor monitor) throws CoreException {
                IMarker marker = null;
                try {
                  marker = ((IFileEditorInput) input).getFile().createMarker(IMarker.TEXT);
                  marker.setAttribute(IMarker.CHAR_START, offset);
                  marker.setAttribute(IMarker.CHAR_END, offset + length);

                  gotoMarkerTarget.gotoMarker(marker);

                } finally {
                  if (marker != null) {
                    marker.delete();
                  }
                }
              }
            };

        try {
          op.run(null);
        } catch (InvocationTargetException ex) {
          // reveal failed
        } catch (InterruptedException e) {
          Assert.isTrue(false, "this operation can not be canceled"); // $NON-NLS-1$
        }
      }
      return;
    }

    /*
     * Workaround: send out a text selection XXX: Needs to be improved, see
     * https://bugs.eclipse.org/bugs/show_bug.cgi?id=32214
     */
    if (editor != null && editor.getEditorSite().getSelectionProvider() != null) {
      IEditorSite site = editor.getEditorSite();
      if (site == null) {
        return;
      }

      ISelectionProvider provider = editor.getEditorSite().getSelectionProvider();
      if (provider == null) {
        return;
      }

      provider.setSelection(new TextSelection(offset, length));
    }
  }
Beispiel #2
0
 public static @Nullable ISelection getActiveSelection(@Nullable IWorkbenchSite site) {
   try {
     if (site == null) {
       return null;
     }
     IWorkbenchWindow workbenchWindow = site.getWorkbenchWindow();
     if (workbenchWindow == null) {
       return null;
     }
     IWorkbenchPage activePage = workbenchWindow.getActivePage();
     if (activePage == null) {
       return null;
     }
     IEditorPart activeEditor = activePage.getActiveEditor();
     if (activeEditor == null) {
       return null;
     }
     IEditorSite editorSite = activeEditor.getEditorSite();
     if (editorSite == null) {
       return null;
     }
     ISelectionProvider selectionProvider = editorSite.getSelectionProvider();
     if (selectionProvider == null) {
       return null;
     }
     return selectionProvider.getSelection();
   } catch (Exception e) {
     return null;
   }
 }
 private static void initializeHighlightRange(IEditorPart editorPart) {
   if (editorPart instanceof ITextEditor) {
     IAction toggleAction =
         editorPart
             .getEditorSite()
             .getActionBars()
             .getGlobalActionHandler(
                 ITextEditorActionDefinitionIds.TOGGLE_SHOW_SELECTED_ELEMENT_ONLY);
     boolean enable = toggleAction != null;
     if (enable && editorPart instanceof DartEditor) {
       enable =
           DartToolsPlugin.getDefault()
               .getPreferenceStore()
               .getBoolean(PreferenceConstants.EDITOR_SHOW_SEGMENTS);
     } else {
       enable = enable && toggleAction.isEnabled() && toggleAction.isChecked();
     }
     if (enable) {
       if (toggleAction instanceof TextEditorAction) {
         // Reset the action
         ((TextEditorAction) toggleAction).setEditor(null);
         // Restore the action
         ((TextEditorAction) toggleAction).setEditor((ITextEditor) editorPart);
       } else {
         // Uncheck
         toggleAction.run();
         // Check
         toggleAction.run();
       }
     }
   }
 }
  @Override
  public void setActivePage(IEditorPart part) {
    if (activeEditorPart == part) return;

    activeEditorPart = part;

    IActionBars actionBars = getActionBars();

    if (activeEditorPart != null && activeEditorPart instanceof ITextEditor) {
      IActionBars siteActionBars = ((IEditorSite) activeEditorPart.getEditorSite()).getActionBars();
      siteActionBars.setGlobalActionHandler(
          ITextEditorActionConstants.UNDO,
          getAction((ITextEditor) activeEditorPart, ITextEditorActionConstants.UNDO));
      siteActionBars.setGlobalActionHandler(
          ITextEditorActionConstants.REDO,
          getAction((ITextEditor) activeEditorPart, ITextEditorActionConstants.REDO));
      siteActionBars.updateActionBars();
    } else {
      if (part instanceof BPELEditor) {
        bpelEditor = (BPELEditor) part;
      }
      if (bpelEditor != null) {
        Object adapter = bpelEditor.getAdapter(ActionRegistry.class);
        if (adapter instanceof ActionRegistry) {
          ActionRegistry registry = (ActionRegistry) adapter;
          // COPY
          IAction action = registry.getAction(BPELCopyAction.ID);
          actionBars.setGlobalActionHandler(ActionFactory.COPY.getId(), action);
          // CUT
          action = registry.getAction(BPELCutAction.ID);
          actionBars.setGlobalActionHandler(ActionFactory.CUT.getId(), action);
          // PASTE
          action = registry.getAction(BPELPasteAction.ID);
          actionBars.setGlobalActionHandler(ActionFactory.PASTE.getId(), action);
          // DELETE
          action = registry.getAction(BPELDeleteAction.ID);
          actionBars.setGlobalActionHandler(ActionFactory.DELETE.getId(), action);
        }

        IWorkbenchPartSite site = bpelEditor.getSite();
        if (site instanceof IEditorSite) {
          ITextEditor textEditor = bpelEditor.getMultipageEditor().getTextEditor();
          IActionBars siteActionBars = ((IEditorSite) site).getActionBars();
          siteActionBars.setGlobalActionHandler(
              ITextEditorActionConstants.UNDO,
              getAction(textEditor, ITextEditorActionConstants.UNDO));
          siteActionBars.setGlobalActionHandler(
              ITextEditorActionConstants.REDO,
              getAction(textEditor, ITextEditorActionConstants.REDO));
          siteActionBars.updateActionBars();
        }
      }
    }

    if (actionBars != null) {
      // update menu bar and tool bar
      actionBars.updateActionBars();
    }
  }
  /**
   * Get the active nested contributor, if any.
   *
   * @return the active nested contributor, or null if any.
   */
  protected IEditorActionBarContributor getActiveContributor() {

    // If there is no nestedEditor, this contributor is used.
    if (activeNestedEditor == null) return this;

    //
    return activeNestedEditor.getEditorSite().getActionBarContributor();
  }
  private IProgressMonitor getProgressMonitor() {
    IWorkbenchPage wbPage = JavaPlugin.getActivePage();
    if (wbPage == null) return null;

    IEditorPart editor = wbPage.getActiveEditor();
    if (editor == null) return null;

    return editor.getEditorSite().getActionBars().getStatusLineManager().getProgressMonitor();
  }
 /** @generated */
 public Object execute(ExecutionEvent event) throws ExecutionException {
   IEditorPart diagramEditor = HandlerUtil.getActiveEditorChecked(event);
   Shell shell = diagramEditor.getEditorSite().getShell();
   assert diagramEditor instanceof DiagramEditor;
   TransactionalEditingDomain editingDomain = ((DiagramEditor) diagramEditor).getEditingDomain();
   LoadResourceAction.LoadResourceDialog loadResourceDialog =
       new LoadResourceAction.LoadResourceDialog(shell, editingDomain);
   loadResourceDialog.open();
   return null;
 }
 /**
  * DOC yyan Get active editor ID.
  *
  * @return Active editor ID
  */
 public static String getActiveEditorId() {
   IWorkbenchWindow workbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
   if (null == workbenchWindow) {
     return null;
   }
   IWorkbenchPage workbenchPage = workbenchWindow.getActivePage();
   if (null == workbenchPage) {
     return null;
   }
   IEditorPart part = workbenchPage.getActiveEditor();
   if (part == null) {
     return null;
   }
   return part.getEditorSite().getId();
 }
  /*
   * (non-Javadoc)
   *
   * @see
   * org.eclipse.ui.internal.e4.compatibility.WorkbenchPartReference#initialize
   * (org.eclipse.ui.IWorkbenchPart)
   */
  @Override
  public void initialize(IWorkbenchPart part) throws PartInitException {
    IConfigurationElement element = descriptor.getConfigurationElement();
    editorSite = new EditorSite(getModel(), part, this, element);
    if (element == null) {
      editorSite.setExtensionId(descriptor.getId());
    }
    editorSite.setActionBars(
        createEditorActionBars((WorkbenchPage) getPage(), descriptor, editorSite));
    IEditorPart editor = (IEditorPart) part;
    try {
      editor.init(editorSite, getEditorInput());
    } catch (PartInitException e) {
      if (editor instanceof ErrorEditorPart) {
        editor.init(editorSite, new NullEditorInput(this));
      } else {
        throw e;
      }
    }

    if (editor.getSite() != editorSite || editor.getEditorSite() != editorSite) {
      String id = descriptor == null ? getModel().getElementId() : descriptor.getId();
      throw new PartInitException(NLS.bind(WorkbenchMessages.EditorManager_siteIncorrect, id));
    }

    if (part instanceof IPersistableEditor) {
      if (editorState != null) {
        ((IPersistableEditor) part).restoreState(editorState);
      } else if (useIPersistableEditor()) {
        String mementoString = getModel().getPersistedState().get(MEMENTO_KEY);
        if (mementoString != null) {
          try {
            IMemento createReadRoot = XMLMemento.createReadRoot(new StringReader(mementoString));
            IMemento editorStateMemento =
                createReadRoot.getChild(IWorkbenchConstants.TAG_EDITOR_STATE);
            if (editorStateMemento != null) {
              ((IPersistableEditor) part).restoreState(editorStateMemento);
            }
          } catch (WorkbenchException e) {
            throw new PartInitException(e.getStatus());
          }
        }
      }
    }

    legacyPart = part;
    addPropertyListeners();
  }
  public DesignViewGraphicalViewer(IEditorPart editor, CommonSelectionManager manager) {
    super();
    this.editorPart = editor;
    setContextMenu(new DesignViewContextMenuProvider(editor, this, this));
    editor
        .getEditorSite()
        .registerContextMenu(
            "org.eclipse.wst.xsd.ui.popup.graph",
            getContextMenu(),
            internalSelectionProvider,
            false); //$NON-NLS-1$

    // make the internalSelectionProvider listen to graph view selection changes
    addSelectionChangedListener(internalSelectionProvider);
    internalSelectionProvider.addSelectionChangedListener(manager);
    manager.addSelectionChangedListener(this);

    setKeyHandler(new BaseGraphicalViewerKeyHandler(this));
  }
Beispiel #11
0
 public static IEditorPart open(Match match, int offset, int length, boolean activate)
     throws PartInitException, JavaModelException {
   IEditorPart editor = null;
   Object element = match.getElement();
   if (element instanceof IJavaElement) {
     editor = JavaUI.openInEditor((IJavaElement) element);
   }
   if (editor != null && activate) editor.getEditorSite().getPage().activate(editor);
   if (editor instanceof ITextEditor) {
     ITextEditor textEditor = (ITextEditor) editor;
     textEditor.selectAndReveal(offset, length);
   } else if (editor != null) {
     if (element instanceof IFile) {
       IFile file = (IFile) element;
       showWithMarker(editor, file, offset, length);
     }
   }
   return editor;
 }
  private void openedByBrowser(Item item, URL url) {
    if (url == null || item == null) {
      return;
    }

    WebBrowserEditorInput input = new WebBrowserEditorInput(url);
    // add for bug TDI-21189 at 2012-6-8,that a document exist is only opened one time in studio
    try {
      IWorkbenchPage page = getActivePage();
      IEditorReference[] iEditorReference = page.getEditorReferences();
      for (IEditorReference editors : iEditorReference) {
        if (WebBrowserEditor.WEB_BROWSER_EDITOR_ID.equals(editors.getId())) {
          IEditorPart iEditorPart = editors.getEditor(true);
          if (iEditorPart != null && iEditorPart instanceof WebBrowserEditor) {
            WebBrowserEditorInput webBrowserEditorInput =
                (WebBrowserEditorInput) iEditorPart.getEditorInput();
            if (webBrowserEditorInput != null && url.equals(webBrowserEditorInput.getURL())) {
              // page.activate(iEditorPart);
              iEditorPart.init(iEditorPart.getEditorSite(), webBrowserEditorInput);
              DocumentationUtil.setPartItemId(
                  (WebBrowserEditor) iEditorPart,
                  item.getProperty().getId(),
                  ERepositoryObjectType.getItemType(item));
              return;
            }
          }
        }
      }
      input.setName(item.getProperty().getLabel());
      input.setToolTipText(
          item.getProperty().getLabel() + " " + item.getProperty().getVersion()); // $NON-NLS-1$
      IEditorPart editorPart = page.openEditor(input, WebBrowserEditor.WEB_BROWSER_EDITOR_ID);
      if (editorPart != null && editorPart instanceof WebBrowserEditor) {
        DocumentationUtil.setPartItemId(
            (WebBrowserEditor) editorPart,
            item.getProperty().getId(),
            ERepositoryObjectType.getItemType(item));
      }
    } catch (PartInitException e) {
      MessageBoxExceptionHandler.process(e);
    }
  }
  /** @see org.eclipse.ui.part.IPage#setActionBars(org.eclipse.ui.IActionBars) */
  @Override
  public void setActionBars(final IActionBars actionBars) {
    // Override the undo and redo global action handlers
    // to use the contributor action handlers
    IActionBars partActionBars = null;
    if (contributor instanceof IEditorPart) {
      final IEditorPart editorPart = (IEditorPart) contributor;
      partActionBars = editorPart.getEditorSite().getActionBars();
    } else if (contributor instanceof IViewPart) {
      final IViewPart viewPart = (IViewPart) contributor;
      partActionBars = viewPart.getViewSite().getActionBars();
    }

    if (partActionBars != null) {
      IAction action = partActionBars.getGlobalActionHandler(ActionFactory.UNDO.getId());
      if (action != null) {
        actionBars.setGlobalActionHandler(ActionFactory.UNDO.getId(), action);
      }
      action = partActionBars.getGlobalActionHandler(ActionFactory.REDO.getId());
      if (action != null) {
        actionBars.setGlobalActionHandler(ActionFactory.REDO.getId(), action);
      }
    }
  }
    @SuppressWarnings("deprecation")
    void handleActivated(AspectResourceInfo resourceInfo) throws CoreException, IOException {
      boolean exists = false;
      long lastModified = 0;
      IPath location = resourceInfo.getFile().getLocation();
      if (location != null) {
        File localFile = location.toFile();
        exists = localFile.exists();
        lastModified = localFile.lastModified();
      }

      // Careful: avoid using editor.getFileInput().exists() since it causes
      // the file cache to be updated and fires the resource change listener.
      // This prevents us from prompting the user for action if the editor is
      // visible.
      if (resourceInfo.getFileExists() && !exists) { // File was deleted
        String[] buttons = {
          Messages.SynchronizationManager_saveButtonLabel, IDialogConstants.CLOSE_LABEL
        };

        // Bugzilla 330513
        // avoid using activeWindow to get a shell - there are cases where these
        // error dialogs are opened before the active window has been created
        // (e.g. resource load failures during editor startup)
        while (true) {
          MessageDialog dialog =
              new MessageDialog(
                  editor.getEditorSite().getShell(),
                  Messages.SynchronizationManager_deleted_title,
                  null, // accept the default windowing system icon
                  Messages.SynchronizationManager_deleted_message,
                  MessageDialog.QUESTION,
                  buttons,
                  0);

          if (dialog.open() == Window.OK) {
            SaveAsDialog saveAsDialog = new SaveAsDialog(editor.getEditorSite().getShell());
            saveAsDialog.setOriginalFile(resourceInfo.getFile());
            saveAsDialog.open();

            IPath path = saveAsDialog.getResult();
            if (path != null) {
              boolean saveSuccess =
                  handler.saveFileAs(
                      resourceInfo, ResourcesPlugin.getWorkspace().getRoot().getFile(path));
              if (saveSuccess) {
                resourceInfo.resetSynchronizeStamp();
                break;
              }
            }
          } else {
            handler.closeEditor();
            break;
          }
        }
      } else if (lastModified != resourceInfo.getSynchronizeStamp()) {
        String msg =
            NLS.bind(
                Messages.SynchronizationManager_refresh_message,
                (new String[] {resourceInfo.getFile().toString()}));
        boolean refresh =
            MessageDialog.openQuestion(
                editor.getEditorSite().getShell(),
                Messages.SynchronizationManager_refresh_title,
                msg);

        if (refresh) {
          handler.refresh(resourceInfo);
          resourceInfo.resetSynchronizeStamp();
        } else {
          /*
           * Update Synchronize Stamp so further editor activations
           * will not display prompt to refresh.
           */
          resourceInfo.resetSynchronizeStamp();
        }
      }
      IFile file = resourceInfo.getFile();
      if (file.exists()
          && (!file.isLocal(IResource.DEPTH_ZERO)
              || !resourceInfo.getFile().isSynchronized(IResource.DEPTH_ZERO)))
        file.refreshLocal(IResource.DEPTH_ZERO, new NullProgressMonitor());
    }
 private IStatusLineManager getStatusLineManager() {
   IStatusLineManager statusLineManager =
       editor.getEditorSite().getActionBars().getStatusLineManager();
   statusLineManager.setCancelEnabled(true);
   return statusLineManager;
 }
  @Override
  public void run(final IAction action) {
    TITANDebugConsole.println("Add import called: ");
    if (targetEditor == null || !(targetEditor instanceof TTCN3Editor)) {
      return;
    }

    targetEditor.getEditorSite().getActionBars().getStatusLineManager().setErrorMessage(null);

    IFile file = (IFile) targetEditor.getEditorInput().getAdapter(IFile.class);
    if (file == null) {
      targetEditor
          .getEditorSite()
          .getActionBars()
          .getStatusLineManager()
          .setErrorMessage(FILENOTIDENTIFIABLE);
      return;
    }

    if (!TITANNature.hasTITANNature(file.getProject())) {
      targetEditor
          .getEditorSite()
          .getActionBars()
          .getStatusLineManager()
          .setErrorMessage(TITANNature.NO_TITAN_FILE_NATURE_FOUND);
      return;
    }

    IPreferencesService prefs = Platform.getPreferencesService();
    boolean reportDebugInformation =
        prefs.getBoolean(
            ProductConstants.PRODUCT_ID_DESIGNER,
            PreferenceConstants.DISPLAYDEBUGINFORMATION,
            true,
            null);

    int offset;
    if (!selection.isEmpty()
        && selection instanceof TextSelection
        && !"".equals(((TextSelection) selection).getText())) {
      if (reportDebugInformation) {
        TITANDebugConsole.println("text selected: " + ((TextSelection) selection).getText());
      }
      TextSelection tSelection = (TextSelection) selection;
      offset = tSelection.getOffset() + tSelection.getLength();
    } else {
      offset = ((TTCN3Editor) targetEditor).getCarretOffset();
    }

    DeclarationCollector declarationCollector =
        OpenDeclarationHelper.findVisibleDeclarations(
            targetEditor,
            new TTCN3ReferenceParser(false),
            ((TTCN3Editor) targetEditor).getDocument(),
            offset,
            false);

    if (declarationCollector == null) {
      return;
    }

    List<DeclarationCollectionHelper> collected = declarationCollector.getCollected();
    if (collected.isEmpty()) {
      // FIXME add semantic check guard on project level.
      ProjectSourceParser projectSourceParser =
          GlobalParser.getProjectSourceParser(file.getProject());
      if (reportDebugInformation) {
        TITANDebugConsole.println("No visible elements found");
      }
      for (String moduleName2 : projectSourceParser.getKnownModuleNames()) {
        Module module2 = projectSourceParser.getModuleByName(moduleName2);
        if (module2 != null) {
          // Visit each file in the project one by
          // one instead of
          // "module2.getAssignments().addDeclaration(declarationCollector)".
          Assignments assignments = module2.getAssignments();
          for (int i = 0; i < assignments.getNofAssignments(); i++) {
            assignments.getAssignmentByIndex(i).addDeclaration(declarationCollector, 0);
          }
        }
      }

      if (declarationCollector.getCollectionSize() == 0) {
        targetEditor
            .getEditorSite()
            .getActionBars()
            .getStatusLineManager()
            .setErrorMessage(NOTTTCN3DECLARATION);
        return;
      }

      if (reportDebugInformation) {
        TITANDebugConsole.println("Elements were only found in not visible modules");
      }

      DeclarationCollectionHelper resultToInsert = null;
      if (collected.size() == 1) {
        resultToInsert = collected.get(0);
      } else {
        OpenDeclarationLabelProvider labelProvider = new OpenDeclarationLabelProvider();
        ElementListSelectionDialog dialog =
            new ElementListSelectionDialog(new Shell(Display.getDefault()), labelProvider);
        dialog.setTitle("Add Import");
        dialog.setMessage("Choose element to generate an import statement for.");
        dialog.setElements(collected.toArray());
        if (dialog.open() == Window.OK) {
          if (reportDebugInformation) {
            TITANDebugConsole.getConsole()
                .newMessageStream()
                .println("Selected: " + dialog.getFirstResult());
          }
          resultToInsert = (DeclarationCollectionHelper) dialog.getFirstResult();
        }
      }

      if (resultToInsert == null) {
        return;
      }

      IFile newfile = (IFile) resultToInsert.location.getFile();
      String moduleName = projectSourceParser.containedModule(newfile);
      Module newModule = projectSourceParser.getModuleByName(moduleName);
      if (newModule == null) {
        targetEditor
            .getEditorSite()
            .getActionBars()
            .getStatusLineManager()
            .setErrorMessage("Could not identify the module in file " + newfile.getName());
        return;
      }

      String ttcnName = newModule.getIdentifier().getTtcnName();
      TITANDebugConsole.println("the new module to insert: " + ttcnName);

      final IFile actualFile = (IFile) targetEditor.getEditorInput().getAdapter(IFile.class);
      String actualModuleName = projectSourceParser.containedModule(actualFile);
      Module actualModule = projectSourceParser.getModuleByName(actualModuleName);

      int insertionOffset =
          ((TTCN3Module) actualModule).getAssignmentsScope().getLocation().getOffset() + 1;

      MultiTextEdit multiEdit = new MultiTextEdit(insertionOffset, 0);
      RewriteSessionEditProcessor processor =
          new RewriteSessionEditProcessor(
              ((TTCN3Editor) targetEditor).getDocument(),
              multiEdit,
              TextEdit.UPDATE_REGIONS | TextEdit.CREATE_UNDO);
      multiEdit.addChild(new InsertEdit(insertionOffset, "\nimport from " + ttcnName + " all;\n"));

      try {
        processor.performEdits();
      } catch (BadLocationException e) {
        ErrorReporter.logExceptionStackTrace(e);
      }
    } else {
      if (reportDebugInformation) {
        for (DeclarationCollectionHelper foundDeclaration : collected) {
          TITANDebugConsole.println(
              "declaration:"
                  + foundDeclaration.location.getFile()
                  + ": "
                  + foundDeclaration.location.getOffset()
                  + " - "
                  + foundDeclaration.location.getEndOffset()
                  + " is available");
        }
      }
    }

    Display.getDefault()
        .asyncExec(
            new Runnable() {
              @Override
              public void run() {
                MessageDialog.openWarning(
                    new Shell(Display.getDefault()),
                    "Study feature",
                    "Adding a missing importation is still under study");
              }
            });
  }