Java Code Examples for org.eclipse.jdt.ui.JavaUI#openInEditor()

The following examples show how to use org.eclipse.jdt.ui.JavaUI#openInEditor() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: GlobalDerivedMemberAwareURIEditorOpener.java    From xtext-eclipse with Eclipse Public License 2.0 6 votes vote down vote up
@Override
public IEditorPart open(URI uri, Object context, boolean select) {
	try {
		if (context instanceof IMember) {
			if(uri != null) {
				URI sourceResourceURI = uri.trimFragment();
				IResourceServiceProvider serviceProvider = resourceServiceProviderRegistry
						.getResourceServiceProvider(sourceResourceURI);
				if (serviceProvider != null) {
					IDerivedMemberAwareEditorOpener opener = serviceProvider.get(IDerivedMemberAwareEditorOpener.class);
					if (opener != null) {
						return opener.open(sourceResourceURI, (IMember) context, select);
					}
				}
			}
			return JavaUI.openInEditor((IJavaElement) context, true, true);
		}
	} catch(Exception exc) {
		LOG.error("Error opening Java editor", exc);
	}
	return super.open(uri, select);
}
 
Example 2
Source File: QuickFixCompletionProposalWrapper.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run(IMarker marker) {
  try {
    IEditorPart part = EditorUtility.isOpenInEditor(cu);
    if (part == null) {
      part = JavaUI.openInEditor(cu, true, false);
      if (part instanceof ITextEditor) {
        ((ITextEditor) part).selectAndReveal(offset, length);
      }
    }
    if (part != null) {
      IEditorInput input = part.getEditorInput();
      IDocument doc = JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getDocument(
          input);
      proposal.apply(doc);
    }
  } catch (CoreException e) {
    CorePluginLog.logError(e);
  }
}
 
Example 3
Source File: OpenSuperImplementationAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void run(IMethod method) {
	if (method == null)
		return;
	if (!ActionUtil.isProcessable(getShell(), method))
		return;

	if (!checkMethod(method)) {
		MessageDialog.openInformation(getShell(), getDialogTitle(),
			Messages.format(ActionMessages.OpenSuperImplementationAction_no_super_implementation, BasicElementLabels.getJavaElementName(method.getElementName())));
		return;
	}

	try {
		IMethod impl= findSuperImplementation(method);
		if (impl != null) {
			JavaUI.openInEditor(impl, true, true);
		}
	} catch (CoreException e) {
		ExceptionHandler.handle(e, getDialogTitle(), ActionMessages.OpenSuperImplementationAction_error_message);
	}
}
 
Example 4
Source File: AddJavaDocStubAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void run(IStructuredSelection selection) {
	IMember[] members= getSelectedMembers(selection);
	if (members == null || members.length == 0) {
		return;
	}

	try {
		ICompilationUnit cu= members[0].getCompilationUnit();
		if (!ActionUtil.isEditable(getShell(), cu)) {
			return;
		}

		// open the editor, forces the creation of a working copy
		IEditorPart editor= JavaUI.openInEditor(cu);

		if (ElementValidator.check(members, getShell(), getDialogTitle(), false))
			run(members);
		JavaModelUtil.reconcile(cu);
		EditorUtility.revealInEditor(editor, members[0]);

	} catch (CoreException e) {
		ExceptionHandler.handle(e, getShell(), getDialogTitle(), ActionMessages.AddJavaDocStubsAction_error_actionFailed);
	}
}
 
Example 5
Source File: OverrideIndicatorManager.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Opens and reveals the defining method.
 */
public void open() {
	CompilationUnit ast= SharedASTProvider.getAST(fJavaElement, SharedASTProvider.WAIT_ACTIVE_ONLY, null);
	if (ast != null) {
		ASTNode node= ast.findDeclaringNode(fAstNodeKey);
		if (node instanceof MethodDeclaration) {
			try {
				IMethodBinding methodBinding= ((MethodDeclaration)node).resolveBinding();
				IMethodBinding definingMethodBinding= Bindings.findOverriddenMethod(methodBinding, true);
				if (definingMethodBinding != null) {
					IJavaElement definingMethod= definingMethodBinding.getJavaElement();
					if (definingMethod != null) {
						JavaUI.openInEditor(definingMethod, true, true);
						return;
					}
				}
			} catch (CoreException e) {
				ExceptionHandler.handle(e, JavaEditorMessages.OverrideIndicatorManager_open_error_title, JavaEditorMessages.OverrideIndicatorManager_open_error_messageHasLogEntry);
				return;
			}
		}
	}
	String title= JavaEditorMessages.OverrideIndicatorManager_open_error_title;
	String message= JavaEditorMessages.OverrideIndicatorManager_open_error_message;
	MessageDialog.openError(JavaPlugin.getActiveWorkbenchShell(), title, message);
}
 
Example 6
Source File: CorrectionMarkerResolutionGenerator.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
public void run(IMarker marker) {
	try {
		IEditorPart part= EditorUtility.isOpenInEditor(fCompilationUnit);
		if (part == null) {
			part= JavaUI.openInEditor(fCompilationUnit, true, false);
			if (part instanceof ITextEditor) {
				((ITextEditor) part).selectAndReveal(fOffset, fLength);
			}
		}
		if (part != null) {
			IEditorInput input= part.getEditorInput();
			IDocument doc= JavaPlugin.getDefault().getCompilationUnitDocumentProvider().getDocument(input);
			fProposal.apply(doc);
		}
	} catch (CoreException e) {
		JavaPlugin.log(e);
	}
}
 
Example 7
Source File: OpenTypeHierarchyUtil.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 6 votes vote down vote up
private static TypeHierarchyViewPart openInPerspective(IWorkbenchWindow window, IJavaElement[] input) throws WorkbenchException, JavaModelException {
	IWorkbench workbench= JavaPlugin.getDefault().getWorkbench();
	IJavaElement perspectiveInput= input.length == 1 ? input[0] : null;

	if (perspectiveInput != null && input[0] instanceof IMember) {
		if (input[0].getElementType() != IJavaElement.TYPE) {
			perspectiveInput= ((IMember)input[0]).getDeclaringType();
		} else {
			perspectiveInput= input[0];
		}
	}
	IWorkbenchPage page= workbench.showPerspective(JavaUI.ID_HIERARCHYPERSPECTIVE, window, perspectiveInput);

	TypeHierarchyViewPart part= (TypeHierarchyViewPart) page.findView(JavaUI.ID_TYPE_HIERARCHY);
	if (part != null) {
		part.clearNeededRefresh(); // avoid refresh of old hierarchy on 'becomes visible'
	}
	part= (TypeHierarchyViewPart) page.showView(JavaUI.ID_TYPE_HIERARCHY);
	part.setInputElements(input);
	if (perspectiveInput != null) {
		if (page.getEditorReferences().length == 0) {
			JavaUI.openInEditor(input[0], false, false); // only open when the perspective has been created
		}
	}
	return part;
}
 
Example 8
Source File: XbaseEditorOpenClassFileTest.java    From xtext-xtend with Eclipse Public License 2.0 5 votes vote down vote up
public String getEditorContents(final IJavaElement javaElement) {
  try {
    final IEditorPart editor = JavaUI.openInEditor(javaElement);
    final Object adapter = editor.<IRewriteTarget>getAdapter(IRewriteTarget.class);
    final String text = ((IRewriteTarget) adapter).getDocument().get();
    this.helper.closeEditor(editor, false);
    return text;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 9
Source File: JavaCompilationParticipantTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
public void testBuildAddError() throws Exception {
  IProject project = getTestProject().getProject();

  // Verify that we have 1 existing GWT problem marker
  IMarker[] markers = getGWTProblemMarkers(project);
  assertEquals(1, markers.length);

  ICompilationUnit cu = testClass.getCompilationUnit();

  // Open the test class in the editor
  CompilationUnitEditor editor = (CompilationUnitEditor) JavaUI.openInEditor(cu);
  IEditorInput editorInput = editor.getEditorInput();

  // Edit the document to create a new error (add 'foobar' to the front of
  // the class name in a Java reference)
  IDocument document = editor.getDocumentProvider().getDocument(editorInput);
  TextEdit errorEdit = new InsertEdit(254, "foobar");
  errorEdit.apply(document);
  // Save the changes
  editor.doSave(null);

  // Rebuild the project
  rebuildTestProject();

  // Verify that we now have 2 GWT problem markers
  markers = getGWTProblemMarkers(project);
  assertEquals(2, markers.length);
}
 
Example 10
Source File: JsniMethodBodyCompletionProposalComputerTest.java    From gwt-eclipse-plugin with Eclipse Public License 1.0 5 votes vote down vote up
/**
 *  If length of line at 'lineNum' is 'len', then validate all proposals for invocation
 *  index varying from '(len - numCharsCompleted)' to 'len'.
 */
private static void validateExpectedProposals(IJavaProject javaProject,
    String fullyQualifiedClassName, String source, int lineNum, int numCharsCompleted,
    String... expectedProposals) throws CoreException, BadLocationException {
  IProgressMonitor monitor = new NullProgressMonitor();

  ICompilationUnit iCompilationUnit = JavaProjectUtilities.createCompilationUnit(
      javaProject, fullyQualifiedClassName, source);
  CompilationUnitEditor cuEditor = (CompilationUnitEditor) JavaUI.openInEditor(iCompilationUnit);

  ISourceViewer viewer = cuEditor.getViewer();
  IDocument document = viewer.getDocument();

  IRegion lineInformation = document.getLineInformation(lineNum);
  JsniMethodBodyCompletionProposalComputer jcpc = new JsniMethodBodyCompletionProposalComputer();

  for (int numCharsToOverwrite = 0; numCharsToOverwrite <= numCharsCompleted;
      numCharsToOverwrite++){
    int invocationOffset = lineInformation.getOffset()
        + lineInformation.getLength() - numCharsToOverwrite;
    JavaContentAssistInvocationContext context = new JavaContentAssistInvocationContext(
        viewer, invocationOffset, cuEditor);
    List<ICompletionProposal> completions = jcpc.computeCompletionProposals(
        context, monitor);

    int indentationUnits = JsniMethodBodyCompletionProposalComputer.measureIndentationUnits(
        document, lineNum, lineInformation.getOffset(), javaProject);
    List<String> expected = createJsniBlocks(javaProject, indentationUnits,
        expectedProposals);
    for (int i = 0; i < expected.size(); i++){
      String expectedBlock = expected.get(i).substring(numCharsCompleted - numCharsToOverwrite);
      expected.set(i, expectedBlock);
    }
    assertExpectedProposals(expected, completions, numCharsToOverwrite);
  }
}
 
Example 11
Source File: JavaUiCodeAppenderImpl.java    From jenerate with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void revealInEditor(IType objectClass, IJavaElement elementToReveal)
        throws JavaModelException, PartInitException {
    ICompilationUnit compilationUnit = objectClass.getCompilationUnit();
    IEditorPart javaEditor = JavaUI.openInEditor(compilationUnit);
    JavaUI.revealInEditor(javaEditor, elementToReveal);
}
 
Example 12
Source File: SortMembersAction.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void run(IStructuredSelection selection) {
	Shell shell= getShell();
	try {
		ICompilationUnit cu= getSelectedCompilationUnit(selection);
		if (cu == null) {
			return;
		}
		IType[] types= cu.getTypes();
		if (!hasMembersToSort(types)) {
			return;
		}
		if (!ActionUtil.isEditable(getShell(), cu)) {
			return;
		}

		SortMembersMessageDialog dialog= new SortMembersMessageDialog(getShell());
		if (dialog.open() != Window.OK) {
			return;
		}

		if (!ElementValidator.check(cu, getShell(), getDialogTitle(), false)) {
			return;
		}

		// open an editor and work on a working copy
		IEditorPart editor= JavaUI.openInEditor(cu);
		if (editor != null) {
			run(shell, cu, editor, dialog.isNotSortingFieldsEnabled());
		}
	} catch (CoreException e) {
		ExceptionHandler.handle(e, shell, getDialogTitle(), null);
	}
}
 
Example 13
Source File: CUCorrectionProposal.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
@Override
public void apply(IDocument document) {
	try {
		ICompilationUnit unit= getCompilationUnit();
		IEditorPart part= null;
		if (unit.getResource().exists()) {
			boolean canEdit= performValidateEdit(unit);
			if (!canEdit) {
				return;
			}
			part= EditorUtility.isOpenInEditor(unit);
			if (part == null) {
				part= JavaUI.openInEditor(unit);
				if (part != null) {
					fSwitchedEditor= true;
					document= JavaUI.getDocumentProvider().getDocument(part.getEditorInput());
				}
			}
			IWorkbenchPage page= JavaPlugin.getActivePage();
			if (page != null && part != null) {
				page.bringToTop(part);
			}
			if (part != null) {
				part.setFocus();
			}
		}
		performChange(part, document);
	} catch (CoreException e) {
		ExceptionHandler.handle(e, CorrectionMessages.CUCorrectionProposal_error_title, CorrectionMessages.CUCorrectionProposal_error_message);
	}
}
 
Example 14
Source File: JavadocHover.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
public static IEditorPart openDeclaration(IJavaElement element) throws PartInitException, JavaModelException {
	if (!(element instanceof IPackageFragment)) {
		return JavaUI.openInEditor(element);
	}
	
	IPackageFragment packageFragment= (IPackageFragment) element;
	ITypeRoot typeRoot;
	IPackageFragmentRoot root= (IPackageFragmentRoot) packageFragment.getAncestor(IJavaElement.PACKAGE_FRAGMENT_ROOT);
	if (root.getKind() == IPackageFragmentRoot.K_BINARY) {
		typeRoot= packageFragment.getClassFile(JavaModelUtil.PACKAGE_INFO_CLASS);
	} else {
		typeRoot= packageFragment.getCompilationUnit(JavaModelUtil.PACKAGE_INFO_JAVA);
	}

	// open the package-info file in editor if one exists
	if (typeRoot.exists())
		return JavaUI.openInEditor(typeRoot);

	// open the package.html file in editor if one exists
	Object[] nonJavaResources= packageFragment.getNonJavaResources();
	for (Object nonJavaResource : nonJavaResources) {
		if (nonJavaResource instanceof IFile) {
			IFile file= (IFile) nonJavaResource;
			if (file.exists() && JavaModelUtil.PACKAGE_HTML.equals(file.getName())) {
				return EditorUtility.openInEditor(file, true);
			}
		}
	}

	// select the package in the Package Explorer if there is no associated package Javadoc file
	PackageExplorerPart view= (PackageExplorerPart) JavaPlugin.getActivePage().showView(JavaUI.ID_PACKAGES);
	view.tryToReveal(packageFragment);
	return null;
}
 
Example 15
Source File: JvmImplementationOpener.java    From xtext-eclipse with Eclipse Public License 2.0 4 votes vote down vote up
protected IEditorPart openEditor(final IJavaElement element) throws JavaModelException, PartInitException {
	return JavaUI.openInEditor(element);
}
 
Example 16
Source File: CallHierarchyUI.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 4 votes vote down vote up
/**
 * Opens the element in the editor or shows an error dialog if that fails.
 *
 * @param element the element to open
 * @param shell parent shell for error dialog
 * @param activateOnOpen <code>true</code> if the editor should be activated
 * @return <code>true</code> iff no error occurred while trying to open the editor,
 *         <code>false</code> iff an error dialog was raised.
 */
public static boolean openInEditor(Object element, Shell shell, boolean activateOnOpen) {
       CallLocation callLocation= CallHierarchy.getCallLocation(element);

       try {
        IMember enclosingMember;
        int selectionStart;
		int selectionLength;

        if (callLocation != null) {
			enclosingMember= callLocation.getMember();
			selectionStart= callLocation.getStart();
			selectionLength= callLocation.getEnd() - selectionStart;
        } else if (element instanceof MethodWrapper) {
        	enclosingMember= ((MethodWrapper) element).getMember();
        	ISourceRange selectionRange= enclosingMember.getNameRange();
        	if (selectionRange == null)
        		selectionRange= enclosingMember.getSourceRange();
        	if (selectionRange == null)
        		return true;
        	selectionStart= selectionRange.getOffset();
        	selectionLength= selectionRange.getLength();
        } else {
            return true;
        }

		IEditorPart methodEditor = JavaUI.openInEditor(enclosingMember, activateOnOpen, false);
           if (methodEditor instanceof ITextEditor) {
               ITextEditor editor = (ITextEditor) methodEditor;
			editor.selectAndReveal(selectionStart, selectionLength);
           }
           return true;
       } catch (JavaModelException e) {
           JavaPlugin.log(new Status(IStatus.ERROR, JavaPlugin.getPluginId(),
                   IJavaStatusConstants.INTERNAL_ERROR,
                   CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_message, e));

           ErrorDialog.openError(shell, CallHierarchyMessages.OpenLocationAction_error_title,
               CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_message,
               e.getStatus());
           return false;
       } catch (PartInitException x) {
           String name;
       	if (callLocation != null)
       		name= callLocation.getCalledMember().getElementName();
       	else if (element instanceof MethodWrapper)
       		name= ((MethodWrapper) element).getName();
       	else
       		name= "";  //$NON-NLS-1$
           MessageDialog.openError(shell, CallHierarchyMessages.OpenLocationAction_error_title,
               Messages.format(
                   CallHierarchyMessages.CallHierarchyUI_open_in_editor_error_messageArgs,
                   new String[] { name, x.getMessage() }));
           return false;
       }
   }