Пример #1
0
  public JavaEditor openJavaEditor(IJavaElement javaElement) {
    IEditorPart part = EditorUtility.isOpenInEditor(javaElement);
    if (part == null) {
      try {
        part = JavaUI.openInEditor(javaElement);
      } catch (PartInitException e) {
        // ignore
      } catch (JavaModelException e) {
        // ignore
      }
    }

    IWorkbenchPage page = JavaPlugin.getActivePage();
    if (page != null && part != null) {
      page.bringToTop(part);
    }
    if (part != null) {
      part.setFocus();
    }
    if (part instanceof JavaEditor) {
      return (JavaEditor) part;
    }

    return null;
  }
Пример #2
0
  @Override
  public void doRun(ISelection selection, Event event, UIInstrumentationBuilder instrumentation) {
    instrumentation.metric("command", command);

    if (!(selection instanceof ITextSelection)) {
      instrumentation.metric("Problem", "Selection was not a TextSelection");
    }

    IWorkbenchPage page = DartToolsPlugin.getActivePage();
    if (page == null) {
      instrumentation.metric("Problem", "Page was null");
      return;
    }

    IEditorPart part = page.getActiveEditor();
    if (part == null) {
      instrumentation.metric("Problem", "Part was null");
      return;
    }

    IEditorInput editorInput = part.getEditorInput();
    IProject project = EditorUtility.getProject(editorInput);
    instrumentation.data("Project", project.getName());
    savePubspecFile(project);
    runPubJob(project);
  }
Пример #3
0
 /** Retrieves the current {@link IProject} instance based on the currently opened editor. */
 public static IProject getCurrentProjectForOpenEditor() {
   IWorkbenchWindow activeWorkbenchWindow = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
   if (activeWorkbenchWindow != null && activeWorkbenchWindow.getActivePage() != null) {
     IEditorPart p = activeWorkbenchWindow.getActivePage().getActiveEditor();
     if (p == null) {
       IWorkbenchPart activePart = activeWorkbenchWindow.getActivePage().getActivePart();
       if (activePart instanceof PropertySheet) {
         ShowInContext showInContext = ((PropertySheet) activePart).getShowInContext();
         if (showInContext instanceof PropertyShowInContext) {
           IWorkbenchPart part = ((PropertyShowInContext) showInContext).getPart();
           if (part instanceof IEditorPart) {
             p = (IEditorPart) part;
           } else {
             JasperReportsPlugin.getDefault()
                 .logWarning("Unable to retrieve the current project for the open editor.");
             return null;
           }
         }
       }
     }
     IEditorInput editorInput = p.getEditorInput();
     IFile file = getFile(editorInput);
     if (file != null) {
       return file.getProject();
     }
   }
   return null;
 }
  private GradleProject getContext() {
    IWorkbench wb = PlatformUI.getWorkbench();
    IWorkbenchWindow win = wb.getActiveWorkbenchWindow();
    IWorkbenchPage page = win == null ? null : win.getActivePage();

    if (page != null) {
      ISelection selection = page.getSelection();
      if (selection instanceof IStructuredSelection) {
        IStructuredSelection ss = (IStructuredSelection) selection;
        if (!ss.isEmpty()) {
          Object obj = ss.getFirstElement();
          if (obj instanceof IResource) {
            IResource rsrc = (IResource) obj;
            IProject prj = rsrc.getProject();
            if (prj != null) {
              return GradleCore.create(prj);
            }
          }
        }
      }
      IEditorPart part = page.getActiveEditor();
      if (part != null) {
        IEditorInput input = part.getEditorInput();
        IResource rsrc = (IResource) input.getAdapter(IResource.class);
        if (rsrc != null) {
          IProject prj = rsrc.getProject();
          if (prj != null) {
            return GradleCore.create(prj);
          }
        }
      }
    }
    return null;
  }
  /**
   * Find Open Editor for the currently selected ModelExtensionDefinition
   *
   * @param selectedMedFile the mxd file to check
   * @return the currently open editor or <code>null</code> if none open
   */
  private static IEditorPart getOpenEditor(IFile selectedMedFile) {
    final IWorkbenchWindow window = Activator.getDefault().getCurrentWorkbenchWindow();

    if (window != null) {
      final IWorkbenchPage page = window.getActivePage();

      if (page != null) {
        // look through the open editors and see if there is one available for this model file.
        IEditorReference[] editors = page.getEditorReferences();

        for (int i = 0; i < editors.length; ++i) {
          IEditorPart editor = editors[i].getEditor(false);

          if (editor != null) {
            IEditorInput input = editor.getEditorInput();

            if (input instanceof IFileEditorInput) {
              if ((selectedMedFile != null)
                  && selectedMedFile.equals(((IFileEditorInput) input).getFile())) {
                return editor;
              }
            }
          }
        }
      }
    }

    return null;
  }
  /* (non-Javadoc)
   * @see org.eclipse.debug.ui.actions.IToggleBreakpointsTarget#toggleLineBreakpoints(org.eclipse.ui.IWorkbenchPart, org.eclipse.jface.viewers.ISelection)
   */
  public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection)
      throws CoreException {
    IEditorPart editorPart = (IEditorPart) part;
    IEditorInput editorInput = editorPart.getEditorInput();
    IResource resource = null;
    if (editorInput instanceof IFileEditorInput) {
      resource = ((IFileEditorInput) editorInput).getFile();
    }
    if (resource == null) {
      Display.getCurrent().beep();
      return;
    }

    ITextSelection textSelection = (ITextSelection) selection;
    int lineNumber = textSelection.getStartLine();
    IBreakpoint[] breakpoints =
        DebugPlugin.getDefault()
            .getBreakpointManager()
            .getBreakpoints(IAntDebugConstants.ID_ANT_DEBUG_MODEL);
    for (int i = 0; i < breakpoints.length; i++) {
      IBreakpoint breakpoint = breakpoints[i];
      if (resource.equals(breakpoint.getMarker().getResource())) {
        if (((ILineBreakpoint) breakpoint).getLineNumber() == (lineNumber + 1)) {
          DebugUITools.deleteBreakpoints(
              new IBreakpoint[] {breakpoint}, part.getSite().getShell(), null);
          return;
        }
      }
    }
    // create line breakpoint (doc line numbers start at 0)
    new AntLineBreakpoint(resource, lineNumber + 1);
  }
  private void doJSPELHyperlinkTestForELInTagBodyTest(
      String pageName, String template, String editorName) throws BadLocationException {
    IEditorPart editor = WorkbenchUtils.openEditor(pageName);
    assertTrue(editor instanceof JSPMultiPageEditor);
    JSPMultiPageEditor jspMultyPageEditor = (JSPMultiPageEditor) editor;
    ISourceViewer viewer = jspMultyPageEditor.getSourceEditor().getTextViewer();
    assertNotNull("Viewer couldn't be found for " + pageName, viewer);
    IDocument document = viewer.getDocument();
    IRegion reg =
        new FindReplaceDocumentAdapter(document).find(0, template, true, true, false, false);
    assertNotNull("Text: " + template + " not found", reg);

    IHyperlink[] links =
        elHyperlinkDetector.detectHyperlinks(
            viewer, new Region(reg.getOffset() + reg.getLength() - 1, 0), true);

    assertNotNull("Hyperlinks for EL:#{" + template + "} are not found", links);

    assertTrue("Hyperlinks for EL: #{" + template + "} are not found", links.length != 0);

    boolean found = false;
    for (IHyperlink link : links) {
      assertNotNull(link.toString());

      link.open();

      IEditorPart resultEditor =
          PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
      if (editorName.equals(resultEditor.getTitle())) {
        found = true;
        return;
      }
    }
    assertTrue("OpenOn have not opened " + editorName + " editor", found);
  }
 public boolean canToggleLineBreakpoints(IWorkbenchPart part, ISelection selection) {
   if (part instanceof IEditorPart && selection instanceof ITextSelection) {
     IEditorPart editor = (IEditorPart) part;
     IResource resource = (IResource) editor.getEditorInput().getAdapter(IResource.class);
     ITextSelection textSelection = (ITextSelection) selection;
     int lineNumber = textSelection.getStartLine();
     try {
       DRLInfo drlInfo = DroolsEclipsePlugin.getDefault().parseResource(resource, false);
       if (drlInfo != null) {
         RuleInfo ruleInfo = drlInfo.getRuleInfo(lineNumber);
         if (ruleInfo != null) {
           if (ruleInfo.getConsequenceDrlLineNumber() <= lineNumber) {
             return true;
           }
         }
         FunctionInfo functionInfo = drlInfo.getFunctionInfo(lineNumber);
         if (functionInfo != null) {
           if (functionInfo.getDrlLineNumber() <= lineNumber) {
             return true;
           }
         }
       }
     } catch (Throwable t) {
       DroolsEclipsePlugin.log(t);
     }
   }
   return false;
 }
 public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection)
     throws CoreException {
   if (part instanceof IEditorPart) {
     IEditorPart editor = (IEditorPart) part;
     IResource resource = (IResource) editor.getEditorInput().getAdapter(IResource.class);
     ITextSelection textSelection = (ITextSelection) selection;
     int lineNumber = textSelection.getStartLine();
     IBreakpoint[] breakpoints =
         DebugPlugin.getDefault()
             .getBreakpointManager()
             .getBreakpoints(IDroolsDebugConstants.ID_DROOLS_DEBUG_MODEL);
     for (int i = 0; i < breakpoints.length; i++) {
       IBreakpoint breakpoint = breakpoints[i];
       if (resource.equals(breakpoint.getMarker().getResource())) {
         if (breakpoint.getMarker().getType().equals(IDroolsDebugConstants.DROOLS_MARKER_TYPE)) {
           if (((DroolsLineBreakpoint) breakpoint).getDRLLineNumber() == (lineNumber + 1)) {
             breakpoint.delete();
             return;
           }
         }
       }
     }
     // TODO: drools breakpoints can only be created in functions and consequences
     DroolsLineBreakpoint lineBreakpoint = new DroolsLineBreakpoint(resource, lineNumber + 1);
     DebugPlugin.getDefault().getBreakpointManager().addBreakpoint(lineBreakpoint);
   }
 }
  public void toggleLineBreakpoints(IWorkbenchPart part, ISelection selection)
      throws CoreException {
    if (selection instanceof ITextSelection) {
      ITextSelection textSel = (ITextSelection) selection;
      IEditorPart editorPart = (IEditorPart) part.getAdapter(IEditorPart.class);
      IFileEditorInput fileInput = (IFileEditorInput) editorPart.getEditorInput();
      final IFile origSrcFile = fileInput.getFile();
      final int lineNumber = textSel.getStartLine() + 1;

      IWorkspaceRunnable wr =
          new IWorkspaceRunnable() {
            public void run(IProgressMonitor monitor) throws CoreException {
              IMarker marker = findBreakpointMarker(origSrcFile, lineNumber);
              if (marker != null) {
                // The following will delete the associated marker
                clearLineBreakpoint(origSrcFile, lineNumber);
              } else {
                // The following will create a marker as a side-effect
                setLineBreakpoint(origSrcFile, lineNumber);
              }
            }
          };
      try {
        getWorkspace().run(wr, null);
      } catch (CoreException e) {
        throw new DebugException(e.getStatus());
      }
    }
  }
  private ModelSet getModelSet(Object receiver) {
    if (receiver instanceof IWorkbenchPart) {
      try {

        /* First, retrieve the ModelSet from the Active Part (e.g. ActiveEditor, ModelExplorer, ...) */
        IWorkbenchPart currentPart = (IWorkbenchPart) receiver;
        ServicesRegistry servicesRegistry =
            (ServicesRegistry) currentPart.getAdapter(ServicesRegistry.class);

        if (servicesRegistry != null) {
          return ServiceUtils.getInstance().getModelSet(servicesRegistry);
        }

        /* If not found, retrieve the ModelSet from the Active Editor */
        IEditorPart activeEditor = EditorHelper.getCurrentEditor();
        if (activeEditor != null) {
          servicesRegistry = (ServicesRegistry) activeEditor.getAdapter(ServicesRegistry.class);

          if (servicesRegistry != null) {
            return ServiceUtils.getInstance().getModelSet(servicesRegistry);
          }
        }
      } catch (Exception ex) {
        return null; // NPE (getActiveEditor) or ServiceException (Service registry cannot be
                     // found). In both cases, we just don't handle the event. Fail silently.
      }
    }

    return null;
  }
Пример #12
0
  private void byteScalingHelper(int ix, long times, long bytes, String testName) throws Exception {
    ILaunchConfiguration config = createConfiguration(proj.getProject());
    ILaunchConfigurationWorkingCopy wc = config.getWorkingCopy();
    wc.setAttribute(
        ICDTLaunchConfigurationConstants.ATTR_PROGRAM_ARGUMENTS,
        String.valueOf(bytes) + " " + String.valueOf(times)); // $NON-NLS-1$
    wc.setAttribute(MassifLaunchConstants.ATTR_MASSIF_TIMEUNIT, MassifLaunchConstants.TIME_B);
    config = wc.doSave();

    doLaunch(config, testName);

    ValgrindViewPart view = ValgrindUIPlugin.getDefault().getView();
    IAction chartAction = getChartAction(view);
    assertNotNull(chartAction);
    chartAction.run();

    IEditorPart part =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
    if (part.getEditorInput() instanceof ChartEditorInput) {
      ChartEditorInput input = (ChartEditorInput) part.getEditorInput();
      HeapChart chart = input.getChart();
      assertEquals(HeapChart.getByteUnits()[ix], chart.getXUnits());
    } else {
      fail();
    }
  }
Пример #13
0
	private boolean openFileImpl(IProject project, IPath sourceLoc, int lineNumber) {
		if (sourceLoc == null || "??".equals(sourceLoc.toString())) return false;
		try {
			IEditorInput editorInput = getEditorInput(sourceLoc, project);
			IWorkbenchPage p= CUIPlugin.getActivePage();
			if (p != null) {
				if (editorInput == null) {
					p.openEditor(
							new STCSourceNotFoundEditorInput(project, sourceLoc, lineNumber),
							"org.eclipse.linuxtools.binutils.link2source.STCSourceNotFoundEditor",
							true);
				} else {
					IEditorPart editor = p.openEditor(editorInput, CUIPlugin.EDITOR_ID, true);
					if (lineNumber > 0 && editor instanceof ITextEditor){
						IDocumentProvider provider= ((ITextEditor)editor).getDocumentProvider();
						IDocument document= provider.getDocument(editor.getEditorInput());
						try {
							int start = document.getLineOffset(lineNumber-1);
							((ITextEditor)editor).selectAndReveal(start, 0);
							IWorkbenchPage page= editor.getSite().getPage();
							page.activate(editor);
							return true;
						} catch (BadLocationException x) {
							// ignore
						}
					}
				}
			}
		}
		catch (Exception _) {
		}
		return false;
	}
Пример #14
0
  /** 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));
    }
  }
Пример #15
0
  private boolean isAllOpenEditorsOnWorkspace() {
    boolean onlyFilesEditorInput = true;
    IWorkbench workbench = SearchPlugin.getDefault().getWorkbench();
    IWorkbenchWindow[] windows = workbench.getWorkbenchWindows();
    for (int i = 0; i < windows.length; i++) {
      IWorkbenchPage[] pages = windows[i].getPages();
      for (int x = 0; x < pages.length; x++) {
        IEditorReference[] editorRefs = pages[x].getEditorReferences();
        for (int z = 0; z < editorRefs.length; z++) {
          IEditorPart ep = editorRefs[z].getEditor(false);
          if ((ep instanceof ITextEditor)) { // only dirty editors

            IEditorInput input = ep.getEditorInput();
            if (input instanceof IFileEditorInput) {
              continue;
            }
            if (input instanceof IPathEditorInput) {
              onlyFilesEditorInput = false;
            }
          }
        }
      }
    }
    return onlyFilesEditorInput;
  }
  /**
   * the command has been executed, so extract extract the needed information from the application
   * context.
   */
  public Object execute(ExecutionEvent event) throws ExecutionException {
    IEditorPart activeEditor = HandlerUtil.getActiveEditor(event);
    if (!ITextEditor.class.isAssignableFrom(activeEditor.getClass())) {
      return null;
    }
    ITextEditor iTextEditor = (ITextEditor) activeEditor;
    ISelection selection = iTextEditor.getSelectionProvider().getSelection();
    if (!ITextSelection.class.isAssignableFrom(selection.getClass())) {
      return null;
    }
    ITextSelection textSelection = (ITextSelection) selection;

    IHandlerService service =
        (IHandlerService) HandlerUtil.getActiveSite(event).getService(IHandlerService.class);
    try {
      if (textSelection.getLength() == 0) {
        service.executeCommand("org.eclipse.ui.edit.text.cut.line", null);
      } else {
        service.executeCommand("org.eclipse.ui.edit.cut", null);
      }
    } catch (NotDefinedException e) {
      throw new ExecutionException("Failed to cut line or selection", e);
    } catch (NotEnabledException e) {
      throw new ExecutionException("Failed to cut line or selection", e);
    } catch (NotHandledException e) {
      throw new ExecutionException("Failed to cut line or selection", e);
    }

    return null;
  }
 @Override
 public void apply(IDocument document) {
   try {
     ITranslationUnit unit = getTranslationUnit();
     IEditorPart part = null;
     if (unit.getResource().exists()) {
       boolean canEdit = performValidateEdit(unit);
       if (!canEdit) {
         return;
       }
       part = EditorUtility.isOpenInEditor(unit);
       if (part == null) {
         part = EditorUtility.openInEditor(unit);
         if (part != null) {
           document =
               CUIPlugin.getDefault().getDocumentProvider().getDocument(part.getEditorInput());
         }
       }
       IWorkbenchPage page = CUIPlugin.getActivePage();
       if (page != null && part != null) {
         page.bringToTop(part);
       }
       if (part != null) {
         part.setFocus();
       }
     }
     performChange(part, document);
   } catch (CoreException e) {
     ExceptionHandler.handle(
         e,
         CorrectionMessages.TUCorrectionProposal_error_title,
         CorrectionMessages.TUCorrectionProposal_error_message);
   }
 }
Пример #18
0
  private synchronized void checkFile() {
    if (fActiveEditor == null) return;
    IEditorInput input = fActiveEditor.getEditorInput();
    IPath location = null;

    if (input instanceof IFileEditorInput) {
      IFile file = ((IFileEditorInput) input).getFile();
      location = file.getLocation();
    } else if (input instanceof FileStoreEditorInput) {
      location = URIUtil.toPath(((FileStoreEditorInput) input).getURI());
    } else if (input instanceof CommonSourceNotFoundEditorInput) {
      Object artifact = ((CommonSourceNotFoundEditorInput) input).getArtifact();
      if (artifact instanceof CSourceNotFoundElement) {
        location = new Path(((CSourceNotFoundElement) artifact).getFile());
      }
    }

    if (location != null
        && fExpectedFile != null
        && location.lastSegment().equals(fExpectedFile.lastSegment())) {
      fFileFound = true;

      if (fActiveEditor instanceof ITextEditor) {
        IDocumentProvider docProvider = ((ITextEditor) fActiveEditor).getDocumentProvider();
        fAnnotationModel = docProvider.getAnnotationModel(fActiveEditor.getEditorInput());
        fAnnotationModel.addAnnotationModelListener(this);

        checkAnnotations();
      } else if (fActiveEditor instanceof CommonSourceNotFoundEditor) {
        // No annotation will be painted if source not found.
        fAnnotationFound = true;
      }
    }
  }
  @Override
  public Object getHoverInfo2(ITextViewer textViewer, IRegion hoverRegion) {
    IEditorPart editor = getEditor();
    if (editor == null) {
      return null;
    }
    IFile file = (IFile) editor.getEditorInput().getAdapter(IFile.class);
    if (file == null) {
      return null;
    }
    if (!ContentTypeUtils.isGroovyLikeFileName(file.getName())) {
      return null;
    }

    // first check to see if there would be a debug hover
    // if so, don't do any more work
    if (!alwaysReturnInformation) {
      // Object o = new Object();
      Object o = debugHover.getHoverInfo2(textViewer, hoverRegion);
      if (o != null) {
        // don't actually return anything since we
        // want the real debug hover to do the actual work
        return null;
      }
    }

    IJavaElement[] elements = getJavaElementsAt(textViewer, hoverRegion);
    if (shouldComputeHover(elements)) {
      // might be null and if so, punt to the JavadocHover
      return computeHover(hoverRegion, elements);
    } else {
      return null;
    }
  }
  public String getFactoryId() {
    IEditorPart editor = getEditor(false);
    if (editor == null) {
      if (input == null) {
        String memento = getModel().getPersistedState().get(MEMENTO_KEY);
        if (memento != null) {
          try {
            XMLMemento createReadRoot = XMLMemento.createReadRoot(new StringReader(memento));
            IMemento inputMem = createReadRoot.getChild(IWorkbenchConstants.TAG_INPUT);
            if (inputMem != null) {
              return inputMem.getString(IWorkbenchConstants.TAG_FACTORY_ID);
            }
          } catch (WorkbenchException e) {
            return null;
          }
        }
        return null;
      }

      IPersistableElement persistable = input.getPersistable();
      return persistable == null ? null : persistable.getFactoryId();
    }

    IPersistableElement persistable = editor.getEditorInput().getPersistable();
    return persistable == null ? null : persistable.getFactoryId();
  }
Пример #21
0
  /**
   * Construct a query based on the state of the user interface controls, and possibly workbecnh.
   *
   * @return A catalog query
   */
  Query createQuery() {
    Query filter = new Query();
    filter.text = text.getText();

    if (filter.text == null || filter.text.length() == 0) {
      text.setText("1500 Poydras St, New Orleans, LA"); // $NON-NLS-1$
    }

    filter.bbox = new Envelope();
    if (bbox.getSelection()) {
      // TODO get current editor
      try {
        IEditorPart editor = getSite().getPage().getActiveEditor();
        Object obj = editor.getEditorInput();
        Class mapType = obj.getClass();
        Method get = mapType.getMethod("getExtent"); // $NON-NLS-1$
        Object value = get.invoke(obj);
        ReferencedEnvelope world = (ReferencedEnvelope) value;
        filter.bbox = world.transform(DefaultGeographicCRS.WGS84, true);
      } catch (Throwable t) {
        LocationUIPlugin.log("ha ha", t); // $NON-NLS-1$
      }
    }
    return filter;
  }
 public String getName() {
   IEditorPart editor = getEditor(false);
   if (input == null) {
     return editor == null ? getModel().getLocalizedLabel() : editor.getEditorInput().getName();
   }
   return editor == null ? input.getName() : editor.getEditorInput().getName();
 }
Пример #23
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;
   }
 }
  public boolean isReadOnly() {
    XSDSchema xsdSchema = null;
    try {
      IEditorPart editorPart = null;
      IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
      if (window != null) {
        IWorkbenchPage page = window.getActivePage();
        if (page != null) {
          editorPart = page.getActiveEditor();
        }
      }
      if (target instanceof XSDConcreteComponent) {
        xsdSchema = ((XSDConcreteComponent) target).getSchema();
      }
      if (editorPart == null) {
        return fallBackCheckIsReadOnly();
      }

      XSDSchema editorSchema = (XSDSchema) editorPart.getAdapter(XSDSchema.class);
      if (xsdSchema != null && xsdSchema == editorSchema) {
        return false;
      } else {
        return fallBackCheckIsReadOnly();
      }
    } catch (Exception e) {

    }
    return true;
  }
  /**
   * Returns a VDB editor given a vdb resource if editor is open
   *
   * @param vdb the vdb
   * @return the vdb editor
   */
  public static VdbEditor getVdbEditorForFile(IResource vdb) {
    if (vdb != null && vdb.exists()) {
      IWorkbenchWindow window = UiPlugin.getDefault().getCurrentWorkbenchWindow();

      if (window != null) {
        final IWorkbenchPage page = window.getActivePage();

        if (page != null) {
          // look through the open editors and see if there is one available for this model file.
          IEditorReference[] editors = page.getEditorReferences();
          for (int i = 0; i < editors.length; ++i) {

            IEditorPart editor = editors[i].getEditor(false);
            if (editor != null) {
              IEditorInput input = editor.getEditorInput();
              if (input instanceof IFileEditorInput) {
                if (vdb.equals(((IFileEditorInput) input).getFile())
                    || vdb.getFullPath()
                        .equals(((IFileEditorInput) input).getFile().getFullPath())) {
                  // found it;
                  if (ModelUtil.isVdbArchiveFile(vdb)) {
                    return (VdbEditor) editor;
                  }
                  break;
                }
              }
            }
          }
        }
      }
    }

    return null;
  }
Пример #26
0
  private void handleEditorActivated(IEditorPart editorPart) {
    if (editorPart.getEditorInput() instanceof IFileEditorInput) {
      IFileEditorInput input = (IFileEditorInput) editorPart.getEditorInput();

      handleSelectionChanged(new StructuredSelection(input.getFile()));
    }
  }
  /**
   * Provide the initialization of the listeners additions. The Window, Part, and Document Listener
   * are added. Note that sensor shell should be instantiated before this method is called because
   * <code>processActivity()</code> method uses sensor shell instance.
   */
  private void registerListeners() {
    IWorkbench workbench = EclipseSensorPlugin.getInstance().getWorkbench();

    // :RESOLVED: JULY 1, 2003
    // Supports the multiple window for sensor collection.
    IWorkbenchWindow[] activeWindows = workbench.getWorkbenchWindows();

    // Check if window listener is not added yet. Otherwise multi instances are notified.
    if (this.windowListener == null) {
      this.windowListener = new WindowListenerAdapter();
      workbench.addWindowListener(new WindowListenerAdapter());
    }

    for (int i = 0; i < activeWindows.length; i++) {
      IWorkbenchPage activePage = activeWindows[i].getActivePage();
      activePage.addPartListener(new PartListenerAdapter());
      IEditorPart activeEditorPart = activePage.getActiveEditor();

      // Adds this EclipseSensorPlugin instance to IDocumentListener
      // only when activeEditorPart is the instance of ITextEditor
      // so that null case is also ignored.
      if (activeEditorPart instanceof ITextEditor) {
        // Sets activeTextEditor. Otherwise a first activated file would not be recorded.
        this.activeTextEditor = (ITextEditor) activeEditorPart;
        // Gets opened file since the initial opened file is not notified from IPartListener.
        URI fileResource = EclipseSensor.this.getFileResource(this.activeTextEditor);

        Map<String, String> keyValueMap = new HashMap<String, String>();
        keyValueMap.put(EclipseSensorConstants.SUBTYPE, "Open");
        keyValueMap.put(EclipseSensorConstants.UNIT_TYPE, EclipseSensorConstants.FILE);
        keyValueMap.put(
            EclipseSensorConstants.UNIT_NAME, EclipseSensor.this.extractFileName(fileResource));
        this.addDevEvent(
            EclipseSensorConstants.DEVEVENT_EDIT,
            fileResource,
            keyValueMap,
            "Opened " + fileResource.toString());

        IDocumentProvider provider = this.activeTextEditor.getDocumentProvider();
        IDocument document = provider.getDocument(activeEditorPart.getEditorInput());

        // Initially sets active buffer and threshold buffer.
        // Otherwise a first activated buffer would not be recorded.
        this.activeBufferSize = document.getLength();
        this.thresholdBufferSize = document.getLength();
        document.addDocumentListener(new DocumentListenerAdapter());
      }
    }

    // Handles breakpoint set/unset event.
    IBreakpointManager bpManager = DebugPlugin.getDefault().getBreakpointManager();
    bpManager.addBreakpointListener(new BreakPointerSensor(this));

    // Listens to debug event.
    DebugPlugin.getDefault().addDebugEventListener(new DebugSensor(this));

    // Creates instance to handle build error.
    this.buildErrorSensor = new BuildErrorSensor(this);
  }
 private IEditorInput getActiveEditorInput() {
   IEditorInput result = null;
   if (activePart instanceof IEditorPart) {
     IEditorPart editorPart = (IEditorPart) activePart;
     result = editorPart.getEditorInput();
   }
   return result;
 }
  public static IEditorInput getEditorInput() {
    IEditorPart activeEditor = getActiveEditor();
    if (activeEditor != null) {
      return activeEditor.getEditorInput();
    }

    return null;
  }
  /** Test that modifications to the editor's content will notify reconciling listeners */
  public void testModificationReconciling() throws Exception {
    IFile file = getOrCreateFile(PROJECT_NAME + "/" + "reconcilingmodificationtest.xml");
    IWorkbenchPage activePage =
        PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    final int[] state = new int[2];
    Arrays.fill(state, -1);
    ISourceReconcilingListener listener =
        new ISourceReconcilingListener() {
          int mod = 0;

          public void reconciled(
              IDocument document,
              IAnnotationModel model,
              boolean forced,
              IProgressMonitor progressMonitor) {
            state[1] = mod++;
          }

          public void aboutToBeReconciled() {
            state[0] = mod++;
          }
        };
    IEditorPart editor =
        IDE.openEditor(activePage, file, "org.eclipse.wst.sse.ui.StructuredTextEditor.test");
    try {
      assertTrue("Not a StructuredTextEditor", editor instanceof StructuredTextEditor);
      addReconcilingListener((StructuredTextEditor) editor, listener);
      waitForReconcile(state);
      assertTrue(
          "Initial: Reconciling did not complete in a timely fashion",
          state[0] != -1 && state[1] != -1);
      assertTrue(
          "Initial: aboutToBeReconciled not invoked first (" + state[0] + ")", state[0] == 0);
      assertTrue(
          "Initial: reconciled not invoked after aboutToBeReconciled (" + state[1] + ")",
          state[1] == 1);
      IDocument document =
          ((StructuredTextEditor) editor)
              .getDocumentProvider()
              .getDocument(editor.getEditorInput());
      assertTrue("Editor doesn't have a document", document != null);
      document.set("<?xml version=\"1.0\" ?>");
      Arrays.fill(state, -1);
      waitForReconcile(state);
      assertTrue(
          "Modified: Reconciling did not complete in a timely fashion",
          state[0] != -1 && state[1] != -1);
      assertTrue(
          "Modified: aboutToBeReconciled not invoked first (" + state[0] + ")", state[0] == 2);
      assertTrue(
          "Modified: reconciled not invoked after aboutToBeReconciled (" + state[1] + ")",
          state[1] == 3);
    } finally {
      if (editor != null && activePage != null) {
        activePage.closeEditor(editor, false);
      }
    }
  }