Java Code Examples for org.eclipse.xtext.ui.editor.utils.EditorUtils

The following examples show how to use org.eclipse.xtext.ui.editor.utils.EditorUtils. These examples are extracted from open source projects. 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 Project: n4js   Source File: N4JSResourceLinkHelper.java    License: Eclipse Public License 1.0 6 votes vote down vote up
@Override
public void activateEditor(final IWorkbenchPage page, final IStructuredSelection selection) {
	if (null != selection && !selection.isEmpty()) {
		final Object firstElement = selection.getFirstElement();
		if (firstElement instanceof ResourceNode) {
			SafeURI<?> nodeLocation = ((ResourceNode) firstElement).getLocation();
			if (nodeLocation.isFile()) {
				final URI uri = nodeLocation.toURI();
				final IEditorInput editorInput = EditorUtils.createEditorInput(new URIBasedStorage(uri));
				final IEditorPart editor = page.findEditor(editorInput);
				if (null != editor) {
					page.bringToTop(editor);
				} else {
					languageSpecificURIEditorOpener.open(uri, true);
				}
				return;
			}
		}
	}
	super.activateEditor(page, selection);
}
 
Example 2
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
	final XtextEditor xtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (xtextEditor != null) {
		final IXtextDocument document = xtextEditor.getDocument();
		document.priorityReadOnly(new IUnitOfWork.Void<XtextResource>()  {
			@Override
			public void process(XtextResource state) throws Exception {
				final QuickOutlinePopup quickOutlinePopup = createPopup(xtextEditor.getEditorSite().getShell());
				quickOutlinePopup.setEditor(xtextEditor);
				quickOutlinePopup.setInput(document);
				if (event.getTrigger() != null) {
					quickOutlinePopup.setEvent((Event) event.getTrigger());
				}
				quickOutlinePopup.open();
			}
		});
	}
	return null;
}
 
Example 3
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
	if (editor != null) {
		ISelection selection = editor.getSelectionProvider().getSelection();
		if (selection instanceof ITextSelection) {
			IWorkbenchWindow workbenchWindow = editor.getEditorSite().getWorkbenchWindow();
			editor.getDocument().priorityReadOnly(resource -> {
				openHierarchy(eObjectAtOffsetHelper.resolveElementAt(resource, ((ITextSelection) selection).getOffset()),
						workbenchWindow);
				return null;
			});
		}
	}
	return null;
}
 
Example 4
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	try {
		XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
		if (editor != null) {
			final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
			editor.getDocument().priorityReadOnly(new IUnitOfWork.Void<XtextResource>() {
				@Override
				public void process(XtextResource state) throws Exception {
					EObject target = eObjectAtOffsetHelper.resolveElementAt(state, selection.getOffset());
					findReferences(target);
				}
			});
		}
	} catch (Exception e) {
		LOG.error(Messages.FindReferencesHandler_3, e);
	}
	return null;
}
 
Example 5
@Override
public IEditorPart open(final URI uri, final EReference crossReference, final int indexInList, final boolean select) {
	Iterator<Pair<IStorage, IProject>> storages = mapper.getStorages(uri.trimFragment()).iterator();
	if (storages != null && storages.hasNext()) {
		try {
			IStorage storage = storages.next().getFirst();
			IEditorInput editorInput = EditorUtils.createEditorInput(storage);
			IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
			final IEditorPart editor = IDE.openEditor(activePage, editorInput, getEditorId());
			selectAndReveal(editor, uri, crossReference, indexInList, select);
			return EditorUtils.getXtextEditor(editor);
		} catch (WrappedException e) {
			logger.error("Error while opening editor part for EMF URI '" + uri + "'", e.getCause());
		} catch (PartInitException partInitException) {
			logger.error("Error while opening editor part for EMF URI '" + uri + "'", partInitException);
		}
	}
	return null;
}
 
Example 6
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	XtextEditor xtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (xtextEditor != null) {
		ITextSelection selection = (ITextSelection) xtextEditor.getSelectionProvider().getSelection();

		IRegion region = new Region(selection.getOffset(), selection.getLength());

		ISourceViewer internalSourceViewer = xtextEditor.getInternalSourceViewer();

		IHyperlink[] hyperlinks = getDetector().detectHyperlinks(internalSourceViewer, region, false);
		if (hyperlinks != null && hyperlinks.length > 0) {
			IHyperlink hyperlink = hyperlinks[0];
			hyperlink.open();
		}
	}		
	return null;
}
 
Example 7
@Override
protected String getQualifiedName(ExecutionEvent event) {
	XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (activeXtextEditor == null) {
		return null;
	}
	final ITextSelection selection = getTextSelection(activeXtextEditor);
	return activeXtextEditor.getDocument().priorityReadOnly(new IUnitOfWork<String, XtextResource>() {

		@Override
		public String exec(XtextResource xTextResource) throws Exception {
			EObject context = getContext(selection, xTextResource);
			EObject selectedElement = getSelectedName(selection, xTextResource);
			return getQualifiedName(selectedElement, context);
		}

	});
}
 
Example 8
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
	if (editor != null) {
		final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
		editor.getDocument().priorityReadOnly(new IUnitOfWork<Void, XtextResource>() {
			@Override
			public java.lang.Void exec(XtextResource resource) throws Exception {
				JvmIdentifiableElement jvmIdentifiable = jvmElementAtOffsetHelper.getJvmIdentifiableElement(resource, selection.getOffset());
				if (jvmIdentifiable != null) {
					IJavaElement javaType = javaElementFinder.findElementFor(jvmIdentifiable);
						if (javaType != null)
							openPresentation(editor, javaType, jvmIdentifiable);
				}
				return null;
			}
		});
	}
	return null;
}
 
Example 9
private void doPasteWithImportsOperation() {
	XbaseClipboardData xbaseClipboardData = ClipboardUtil
			.clipboardOperation(new Function<Clipboard, XbaseClipboardData>() {
				@Override
				public XbaseClipboardData apply(Clipboard input) {
					Object content = input.getContents(TRANSFER_INSTANCE);
					if (content instanceof XbaseClipboardData) {
						return (XbaseClipboardData) content;
					}
					return null;
				}
			});
	JavaImportData javaImportsContent = ClipboardUtil.getJavaImportsContent();
	String textFromClipboard = ClipboardUtil.getTextFromClipboard();
	XtextEditor xtextEditor = EditorUtils.getXtextEditor(getTextEditor());
	boolean addImports = shouldAddImports(xtextEditor.getDocument(), caretOffset(xtextEditor));
	if (xbaseClipboardData != null && !sameTarget(xbaseClipboardData)) {
		doPasteXbaseCode(xbaseClipboardData, addImports);
	} else if (javaImportsContent != null) {
		doPasteJavaCode(textFromClipboard, javaImportsContent, addImports);
	} else {
		textOperationTarget.doOperation(operationCode);
	}
}
 
Example 10
Source Project: xtext-eclipse   Source File: TypeChooser.java    License: Eclipse Public License 2.0 6 votes vote down vote up
public JvmDeclaredType choose(final List<JvmDeclaredType> candidateTypes, Iterable<TypeUsage> usages, final XtextResource resource) {
	XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor();
	if (activeXtextEditor==null) return null;
	revealInEditor(activeXtextEditor, usages, resource);
	Shell shell = Display.getDefault().getActiveShell();
	IStructuredContentProvider contentProvider = new ContentProvider();
	Dialog dialog = new Dialog(shell, new LabelProvider(labelProvider), contentProvider);
	dialog.setInput(candidateTypes);
	dialog.setInitialSelections((Object[])new JvmDeclaredType[] { candidateTypes.get(0) });
	int result = dialog.open();
	if(originalSelection != null)
		activeXtextEditor.getSelectionProvider().setSelection(originalSelection);
	if(result == Window.OK && dialog.getResult().length > 0) 
		return (JvmDeclaredType) dialog.getResult()[0];
	else 
		return null;
}
 
Example 11
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
  try {
    Object _xblockexpression = null;
    {
      this.syncUtil.totalSync(false);
      final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
      if ((editor != null)) {
        ISelection _selection = editor.getSelectionProvider().getSelection();
        final ITextSelection selection = ((ITextSelection) _selection);
        final IXtextDocument document = editor.getDocument();
        this.importer.importStaticMethod(document, selection);
      }
      _xblockexpression = null;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 12
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
  try {
    Object _xblockexpression = null;
    {
      this.syncUtil.totalSync(false);
      final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
      if ((editor != null)) {
        ISelection _selection = editor.getSelectionProvider().getSelection();
        final ITextSelection selection = ((ITextSelection) _selection);
        final IXtextDocument document = editor.getDocument();
        this.importer.importStaticMethod(document, selection);
      }
      _xblockexpression = null;
    }
    return _xblockexpression;
  } catch (Throwable _e) {
    throw Exceptions.sneakyThrow(_e);
  }
}
 
Example 13
/**
 * If a platform plugin URI is given, a read-only Xtext editor is opened and returned. {@inheritDoc}
 *
 * @see {@link org.eclipse.emf.common.util.URI#isPlatformPlugin()}
 */
@Override
public IEditorPart open(final URI uri, final EReference crossReference, final int indexInList, final boolean select) {
  IEditorPart result = super.open(uri, crossReference, indexInList, select);
  if (result == null && (uri.isPlatformPlugin() || OSGI_RESOURCE_URL_PROTOCOL.equals(uri.scheme()))) {
    final IModelLocation modelLocation = getModelLocation(uri.trimFragment());
    if (modelLocation != null) {
      PlatformPluginStorage storage = new PlatformPluginStorage(modelLocation);
      IEditorInput editorInput = new XtextReadonlyEditorInput(storage);
      IWorkbenchPage activePage = workbench.getActiveWorkbenchWindow().getActivePage();
      try {
        IEditorPart editor = IDE.openEditor(activePage, editorInput, editorID);
        selectAndReveal(editor, uri, crossReference, indexInList, select);
        return EditorUtils.getXtextEditor(editor);
      } catch (WrappedException e) {
        LOG.error("Error while opening editor part for EMF URI '" + uri + "'", e.getCause()); //$NON-NLS-1$ //$NON-NLS-2$
      } catch (PartInitException partInitException) {
        LOG.error("Error while opening editor part for EMF URI '" + uri + "'", partInitException); //$NON-NLS-1$ //$NON-NLS-2$
      }
    }
  }
  return result;
}
 
Example 14
Source Project: n4js   Source File: EditorOverlay.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private void draw() {
	XtextEditor editor = EditorUtils.getActiveXtextEditor();
	if (editor != null && (hoveredElement != null || !selectedElements.isEmpty())) {
		ISourceViewer isv = editor.getInternalSourceViewer();
		styledText = isv.getTextWidget();
		drawSelection();
	} else {
		clear();
	}
}
 
Example 15
Source Project: n4js   Source File: CFGraph.java    License: Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor
 */
public CFGraph() {
	locFileProvider = new DefaultLocationInFileProvider();
	editor = EditorUtils.getActiveXtextEditor();
	styledText = editor.getInternalSourceViewer().getTextWidget();
	layoutDone = false;
}
 
Example 16
@Override
public void open(IWorkbenchPage page) {
	try {
		IEditorInput input = EditorUtils.createEditorInput(storage);
		IEditorDescriptor editorDescriptor = IDE.getEditorDescriptor(storage.getName());
		IEditorPart opened = IDE.openEditor(page, input, editorDescriptor.getId());
		if (region != null && opened instanceof ITextEditor) {
			ITextEditor openedTextEditor = (ITextEditor) opened;
			openedTextEditor.selectAndReveal(region.getOffset(), region.getLength());
		}
	} catch (PartInitException e) {
		LOG.error(e.getMessage(), e);
	}
}
 
Example 17
protected TextAttribute createTextAttribute(String id, TextStyle defaultTextStyle) {
	TextStyle textStyle = new TextStyle();
	preferencesAccessor.populateTextStyle(id, textStyle, defaultTextStyle);
	int style = textStyle.getStyle();
	Font fontFromFontData = EditorUtils.fontFromFontData(textStyle.getFontData());
	return new TextAttribute(EditorUtils.colorFromRGB(textStyle.getColor()), EditorUtils.colorFromRGB(textStyle
			.getBackgroundColor()), style, fontFromFontData);
}
 
Example 18
public IEditorInput findOriginalSource(IEditorInput input) {
	IFile resource = ResourceUtil.getFile(input);
	if (resource == null) {
		return input;
	}

	IEditorInput original = findOriginalSourceForOuputFolderCopy(input);
	if (original != input) {
		return original;
	}

	IEclipseTrace trace = traceInformation.getTraceToSource(resource);
	if (trace == null) {
		return input;
	}

	for (ILocationInEclipseResource candidate : trace.getAllAssociatedLocations()) {
		if (languageInfo.equals(candidate.getLanguage())) {
			IStorage storage = candidate.getPlatformResource();
			if (storage != null) {
				return EditorUtils.createEditorInput(storage);
			}
		}
	}

	return input;
}
 
Example 19
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	try {
		syncUtil.totalSync(false);
		final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
		if (editor != null) {
			final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
			final IXtextDocument document = editor.getDocument();
			XtextResource resource = document.priorityReadOnly(new IUnitOfWork<XtextResource, XtextResource>() {
				@Override
				public XtextResource exec(XtextResource state) throws Exception {
					return resourceCopier.loadIntoNewResourceSet(state);
				}
			});
			XExpression expression = expressionUtil.findSelectedExpression(resource, selection);
			if(expression != null) {
				ExtractVariableRefactoring introduceVariableRefactoring = refactoringProvider.get();
				if(introduceVariableRefactoring.initialize(editor, expression)) {
					ITextRegion region = locationInFileProvider.getFullTextRegion(expression);
					editor.selectAndReveal(region.getOffset(), region.getLength());
					ExtractVariableWizard wizard = new ExtractVariableWizard(introduceVariableRefactoring);
					RefactoringWizardOpenOperation_NonForking openOperation = new RefactoringWizardOpenOperation_NonForking(
							wizard);
					openOperation.run(editor.getSite().getShell(), "Extract Local Variable");
				}
			}
		}
	} catch (InterruptedException e) {
		return null;
	} catch (Exception exc) {
		LOG.error("Error during refactoring", exc);
		MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error during refactoring", exc.getMessage()
				+ "\nSee log for details");
	}
	return null;
}
 
Example 20
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
	if (editor != null) {
		final IXtextDocument document = editor.getDocument();
		doOrganizeImports(document);
	}
	return null;
}
 
Example 21
Source Project: xtext-eclipse   Source File: AbstractEditorTest.java    License: Eclipse Public License 2.0 5 votes vote down vote up
private XtextEditor getXtextEditor(IEditorPart openEditor) throws NoSuchFieldException, IllegalAccessException {
	XtextEditor xtextEditor = EditorUtils.getXtextEditor(openEditor);
	if (xtextEditor != null) {
		ISourceViewer sourceViewer = xtextEditor.getInternalSourceViewer();
		((ProjectionViewer) sourceViewer).doOperation(ProjectionViewer.EXPAND_ALL);
		return xtextEditor;
	} else if (openEditor instanceof ErrorEditorPart) {
		Field field = openEditor.getClass().getDeclaredField("error");
		field.setAccessible(true);
		throw new IllegalStateException("Couldn't open the editor.", ((Status) field.get(openEditor)).getException());
	} else {
		fail("Opened Editor with id:" + getEditorId() + ", is not an XtextEditor");
	}
	return null;
}
 
Example 22
Source Project: xtext-xtend   Source File: InsertStringHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
	if (editor != null) {
		// Hack, would be nicer with document edits, but this way we don't loose auto edit
		StyledText textWidget = editor.getInternalSourceViewer().getTextWidget();
		Event e = new Event();
		e.character = replaceChar;
		e.type = SWT.KeyDown;
		e.doit = true;
		textWidget.notifyListeners(SWT.KeyDown, e);
	}
	return null;
}
 
Example 23
Source Project: xtext-xtend   Source File: PasteJavaCodeHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	final XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (activeXtextEditor == null || !activeXtextEditor.isEditable()) {
		return null;
	}

	String clipboardText = ClipboardUtil.getTextFromClipboard();
	if (!Strings.isEmpty(clipboardText)) {
		JavaImportData javaImports = ClipboardUtil.getJavaImportsContent();
		doPasteJavaCode(activeXtextEditor, clipboardText, javaImports);
	}
	return null;
}
 
Example 24
Source Project: xtext-xtend   Source File: ExtractMethodHandler.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	try {
		syncUtil.totalSync(false);
		final XtextEditor editor = EditorUtils.getActiveXtextEditor(event);
		if (editor != null) {
			final ITextSelection selection = (ITextSelection) editor.getSelectionProvider().getSelection();
			final IXtextDocument document = editor.getDocument();
			XtextResource copiedResource = document.priorityReadOnly(new IUnitOfWork<XtextResource, XtextResource>() {
				@Override
				public XtextResource exec(XtextResource state) throws Exception {
					return resourceCopier.loadIntoNewResourceSet(state);
				}
			});
			List<XExpression> expressions = expressionUtil.findSelectedSiblingExpressions(copiedResource,
					selection);
			if (!expressions.isEmpty()) {
				ExtractMethodRefactoring extractMethodRefactoring = refactoringProvider.get();
				if (extractMethodRefactoring.initialize(editor, expressions, true)) {
					updateSelection(editor, expressions);
					ExtractMethodWizard wizard = wizardFactory.create(extractMethodRefactoring);
					RefactoringWizardOpenOperation_NonForking openOperation = new RefactoringWizardOpenOperation_NonForking(
							wizard);
					openOperation.run(editor.getSite().getShell(), "Extract Method");
				}
			}
		}
	} catch (InterruptedException e) {
		return null;
	} catch (Exception exc) {
		LOG.error("Error during refactoring", exc);
		MessageDialog.openError(Display.getCurrent().getActiveShell(), "Error during refactoring", exc.getMessage()
				+ "\nSee log for details");
	}
	return null;
}
 
Example 25
Source Project: xtext-xtend   Source File: XtendFormatterPreview.java    License: Eclipse Public License 2.0 5 votes vote down vote up
public XtendFormatterPreview forEmbeddedEditor(EmbeddedEditor editorHandle) {
	if (this.editorHandle != null) {
		throw new IllegalStateException("This formatter preview is already binded to an embedet editor");
	}
	this.editorHandle = editorHandle;
	this.modelAccess = editorHandle.createPartialEditor();
	this.marginPainter = new MarginPainter(editorHandle.getViewer());
	final RGB rgb = PreferenceConverter.getColor(preferenceStoreAccess.getPreferenceStore(),
			AbstractDecoratedTextEditorPreferenceConstants.EDITOR_PRINT_MARGIN_COLOR);
	marginPainter.setMarginRulerColor(EditorUtils.colorFromRGB(rgb));
	editorHandle.getViewer().addPainter(marginPainter);
	return this;
}
 
Example 26
@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {
  XtextEditor xtextEditor = EditorUtils.getActiveXtextEditor(event);
  if (xtextEditor != null && xtextEditor.getEditorInput() instanceof XtextReadonlyEditorInput) {
    return null;
  }
  return super.execute(event);
}
 
Example 27
Source Project: sarl   Source File: AbstractSarlLaunchShortcut.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public IResource getLaunchableResource(IEditorPart editorpart) {
	final XtextEditor xtextEditor = EditorUtils.getXtextEditor(editorpart);
	if (xtextEditor != null) {
		return xtextEditor.getResource();
	}
	return null;
}
 
Example 28
Source Project: sarl   Source File: AbstractSarlLaunchShortcut.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void launch(IEditorPart editor, String mode) {
	final XtextEditor xtextEditor = EditorUtils.getXtextEditor(editor);
	final ISelection selection = xtextEditor.getSelectionProvider().getSelection();
	if (selection instanceof ITextSelection) {
		final ITextSelection sel = (ITextSelection) selection;
		final EObject obj = xtextEditor.getDocument().readOnly(resource -> {
			final IParseResult parseRes = resource.getParseResult();
			if (parseRes == null) {
				return null;
			}
			final ICompositeNode rootNode = parseRes.getRootNode();
			final ILeafNode node = NodeModelUtils.findLeafNodeAtOffset(rootNode, sel.getOffset());
			return NodeModelUtils.findActualSemanticObjectFor(node);
		});
		if (obj != null) {
			final EObject elt = EcoreUtil2.getContainerOfType(obj, getValidEObjectType());
			if (elt != null) {
				searchAndLaunch(mode, elt);
				return;
			}
		}
	} else if (selection != null) {
		launch(selection, mode);
		return;
	}
	// Default launching
	searchAndLaunch(mode, xtextEditor.getResource());
}
 
Example 29
Source Project: sarl   Source File: CorrectIndentationHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
	final XtextEditor activeXtextEditor = EditorUtils.getActiveXtextEditor(event);
	if (activeXtextEditor == null) {
		return null;
	}
	final IXtextDocument doc = activeXtextEditor.getDocument();
	final ITextSelection selection = (ITextSelection) activeXtextEditor.getSelectionProvider().getSelection();
	final IRegion region = new Region(selection.getOffset(), selection.getLength());
	this.formatterProvider.get().format(doc, region);
	return null;
}
 
Example 30
protected IEditorPart openDefaultEditor(IStorage storage, URI uri) throws PartInitException {
	IEditorInput editorInput = EditorUtils.createEditorInput(storage); 
	IWorkbenchPage page = getWorkbench().getActiveWorkbenchWindow().getActivePage();
	return IDE.openEditor(page, editorInput, PlatformUI.getWorkbench().getEditorRegistry().getDefaultEditor(
			uri.lastSegment()).getId());
}