Skip to main content


Eclipse Community Forums
Forum Search:

Search      Help    Register    Login    Home
Home » Modeling » TMF (Xtext) » XText TextViewer instead of Editor
XText TextViewer instead of Editor [message #875558] Wed, 23 May 2012 00:40 Go to next message
Eclipse UserFriend
Hi,

Have created a simple query language to use with a BIRT ODA driver.

Instead of using the XText generated Editor for my query language, I
will need to present the user with a TextViewer in the DataSet Wizard in
order to specify the query string.

I am still a novice when it comes to XText, but I did look but haven't
found any documentation, examples or newsgroup entries regarding a use
case like this.

Can anyone give me an example on how to go about doing this.

thanks,
John
Re: XText TextViewer instead of Editor [message #875765 is a reply to message #875558] Wed, 23 May 2012 10:09 Go to previous messageGo to next message
Massimo Rabbi is currently offline Massimo RabbiFriend
Messages: 29
Registered: November 2010
Location: Padova
Junior Member
Hi John,
I don't know if it will fits your needs but you can use a plugin provided by the guys of Itemis, used in the Yakindu project.
They provide a JFace integration plugin and more stuff too.
I used it in my project (simply used the StyledTextXtextAdapter class). It worked fine.

More information can be found watching this video tutorial took from the latest EclipseCon Europe.
hxxp://www.fosslc.org/drupal/content/tmf-meets-gmf-combining-graphical-and-textual-modeling

Repository for the yakindu project is here:
hxxp://code.google.com/a/eclipselabs.org/p/yakindu/

You can checkout their code and have a look.
You can install the integration features you need using this update site
hxxp://updates.yakindu.com/indigo/milestones

Hope this helps.
Massimo.
Re: XText TextViewer instead of Editor [message #875939 is a reply to message #875558] Wed, 23 May 2012 15:32 Go to previous messageGo to next message
Sebastian Zarnekow is currently offline Sebastian ZarnekowFriend
Messages: 3118
Registered: July 2009
Senior Member
John,

if you use Xtext 2.3, you may want to have a look at the
EmbeddedEditorFactory.

Regards,
Sebastian
--
Need professional support for Eclipse Modeling?
Go visit: http://xtext.itemis.com

Am 23.05.12 02:40, schrieb John E. Conlon:
> Hi,
>
> Have created a simple query language to use with a BIRT ODA driver.
>
> Instead of using the XText generated Editor for my query language, I
> will need to present the user with a TextViewer in the DataSet Wizard in
> order to specify the query string.
>
> I am still a novice when it comes to XText, but I did look but haven't
> found any documentation, examples or newsgroup entries regarding a use
> case like this.
>
> Can anyone give me an example on how to go about doing this.
>
> thanks,
> John
>
>
>
>
Re: XText TextViewer instead of Editor [message #876125 is a reply to message #875765] Thu, 24 May 2012 00:22 Go to previous messageGo to next message
Eclipse UserFriend
Hi Massimo,

Yes, that worked great!

I did the same as you and used the StyledTextXtextAdapter with a StyleText.

The video tutorial was very informative as well.

thanks much,

John

On 05/23/2012 05:09 AM, Massimo Rabbi wrote:
> Hi John,
> I don't know if it will fits your needs but you can use a plugin
> provided by the guys of Itemis, used in the Yakindu project.
> They provide a JFace integration plugin and more stuff too.
> I used it in my project (simply used the StyledTextXtextAdapter class).
> It worked fine.
>
> More information can be found watching this video tutorial took from the
> latest EclipseCon Europe.
> hxxp://www.fosslc.org/drupal/content/tmf-meets-gmf-combining-graphical-and-textual-modeling
>
>
> Repository for the yakindu project is here:
> hxxp://code.google.com/a/eclipselabs.org/p/yakindu/
>
> You can checkout their code and have a look.
> You can install the integration features you need using this update site
> hxxp://updates.yakindu.com/indigo/milestones
>
> Hope this helps.
> Massimo.
Re: XText TextViewer instead of Editor [message #876268 is a reply to message #875939] Thu, 24 May 2012 09:23 Go to previous messageGo to next message
Vlad Dumitrescu is currently offline Vlad DumitrescuFriend
Messages: 431
Registered: July 2009
Location: Gothenburg
Senior Member
Sebastian Zarnekow wrote on Wed, 23 May 2012 17:32
John,
if you use Xtext 2.3, you may want to have a look at the
EmbeddedEditorFactory.


Hi Sebastian,

Would that be the recommended way to use an Xtext editor in a multi-page one too?

regards,
Vlad

[Updated on: Thu, 24 May 2012 12:10]

Report message to a moderator

Re: XText TextViewer instead of Editor [message #876548 is a reply to message #876268] Thu, 24 May 2012 20:25 Go to previous messageGo to next message
Sebastian Zarnekow is currently offline Sebastian ZarnekowFriend
Messages: 3118
Registered: July 2009
Senior Member
Hi Vlad,

I'd try something along these lines:

public class MultiPageEditor extends MultiPageEditorPart {

@Inject
private Provider<XtextEditor> editorProvider;

private XtextEditor editor;

@Override
protected void createPages() {
try {
editor = editorProvider.get();
int index = addPage(editor, getEditorInput());
setPageText(index, editor.getTitle());
} catch (PartInitException e) {
ErrorDialog.openError(
getSite().getShell(),
"Error creating nested text editor",
null,
e.getStatus());
}
}

@Override
public void doSave(IProgressMonitor monitor) {
editor.doSave(monitor);
}

@Override
public void doSaveAs() {
editor.doSaveAs();
setPageText(0, editor.getTitle());
setInput(editor.getEditorInput());
}

@Override
public boolean isSaveAsAllowed() {
return true;
}

}

The EmbeddedEditorFActory should be used to embed an editor in a
composite that is not an IEditorPart itself.

Regards,
Sebastian
--
Need professional support for Eclipse Modeling?
Go visit: http://xtext.itemis.com

Am 24.05.12 11:23, schrieb Vlad Dumitrescu:
> Sebastian Zarnekow wrote on Wed, 23 May 2012 17:32
>> John,
>> if you use Xtext 2.3, you may want to have a look at the
>> EmbeddedEditorFactory.
>
>
> Hi Sebastian,
>
> Would that be the recommended way to use a Xtext editor in a multi-page
> one too?
>
> regards,
> Vlad
>
Re: XText TextViewer instead of Editor [message #876556 is a reply to message #876548] Thu, 24 May 2012 20:35 Go to previous messageGo to next message
Vlad Dumitrescu is currently offline Vlad DumitrescuFriend
Messages: 431
Registered: July 2009
Location: Gothenburg
Senior Member
Thanks a lot, a code example was more than I expected as an answer! Smile

regards,
Vlad
Re: XText TextViewer instead of Editor [message #905954 is a reply to message #875558] Fri, 31 August 2012 11:10 Go to previous messageGo to next message
Tommaso De Sica is currently offline Tommaso De SicaFriend
Messages: 131
Registered: March 2012
Location: Italy
Senior Member

Hi at all,

does it work also on Eclipse 4?

I don't understand what I have to put in my @PostContruct method to see the xtext editor.

Very thank you.
Re: XText TextViewer instead of Editor [message #906357 is a reply to message #905954] Sat, 01 September 2012 07:57 Go to previous messageGo to next message
Tommaso De Sica is currently offline Tommaso De SicaFriend
Messages: 131
Registered: March 2012
Location: Italy
Senior Member

I made several steps ahead from yesterday.

Now I've got this doubt: in my part I have to insert a code like this:
StyledText styledText=new StyledText(parent, SWT.BORDER);
		StyledTextXtextAdapter xtextAdapter=new StyledTextXtextAdapter(getInjector());
xtextAdapter.adapt(styledText);


what is "getInjector()"?

Basic Eclipse 4 injection or com.google.inject.Injector that use also in StyledTextXtextAdapter definition? How can I get it?

Thanks all.
Re: XText TextViewer instead of Editor [message #906390 is a reply to message #906357] Sat, 01 September 2012 10:14 Go to previous messageGo to next message
Massimo Rabbi is currently offline Massimo RabbiFriend
Messages: 29
Registered: November 2010
Location: Padova
Junior Member
Hi Tommaso,
I don't know where you get the code snippet you copy-pasted.
However the injector you need to pass there is an instance of com.google.inject.Injector. It should be the injector relative to your dsl language.
You can get this injector via the generated plugin class inside the generated ui XText project (method getInjector(String languageName)).

Regards,
Massimo.
Re: XText TextViewer instead of Editor [message #994043 is a reply to message #876548] Wed, 26 December 2012 08:16 Go to previous messageGo to next message
kavitha Mising name is currently offline kavitha Mising nameFriend
Messages: 9
Registered: March 2011
Junior Member
Hi Sebastian

I did try to use the MPE eq: you have mentioned,

Quote:

public class MultiPageEditor extends MultiPageEditorPart {

@Inject
private Provider<XtextEditor> editorProvider;

private XtextEditor editor;


but for me editor = editorProvider.get(); was giving a null pointer exception

Is there anything else I need to do for the @Injector to populate the values for editorProvider.

Please let me know

Thanks
Kavitha
Re: XText TextViewer instead of Editor [message #994100 is a reply to message #994043] Wed, 26 December 2012 11:38 Go to previous messageGo to next message
Christian Dietrich is currently offline Christian DietrichFriend
Messages: 14661
Registered: July 2009
Senior Member
http://koehnlein.blogspot.de/2012/11/xtext-tip-how-do-i-get-guice-injec
tor.html?m=1

--
Need training, onsite consulting or any other kind of help for Xtext?
Go visit http://xtext.itemis.com or send a mail to xtext at itemis dot de


Twitter : @chrdietrich
Blog : https://www.dietrich-it.de
Re: XText TextViewer instead of Editor [message #1000729 is a reply to message #994100] Tue, 15 January 2013 10:43 Go to previous messageGo to next message
kavitha Mising name is currently offline kavitha Mising nameFriend
Messages: 9
Registered: March 2011
Junior Member
Hi Christian ,

Thanks for the link, it was really useful. I am able to add XtextEditor on a MultiPageEditor.

Now I have one more issue, I am trying to add the EMF editor as another page on the MPE where the XtextEditor is already added.

How can I link the EMF editor to the xtext input file (the dsl file).

Please let me know your comments.

Thanks,
Kavitha
Re: XText TextViewer instead of Editor [message #1000758 is a reply to message #1000729] Tue, 15 January 2013 11:42 Go to previous messageGo to next message
Christian Dietrich is currently offline Christian DietrichFriend
Messages: 14661
Registered: July 2009
Senior Member
HI,

sorry have no idea about is. you should be able to access the resource.

~Christian


Twitter : @chrdietrich
Blog : https://www.dietrich-it.de
Re: XText TextViewer instead of Editor [message #1729511 is a reply to message #875765] Thu, 14 April 2016 22:09 Go to previous messageGo to next message
Parsa Pourali is currently offline Parsa PouraliFriend
Messages: 210
Registered: February 2014
Senior Member
Hi Guys,

Not sure if you still check the forum after 5 years or not Very Happy but could you please let me know how did you make the StyledTextXtextAdapter work ! The video also is deleted Sad

This is my code:
		IXtextFakeContextResourcesProvider contextProvider=new IXtextFakeContextResourcesProvider() {

			@Override
			public void populateFakeResourceSet(ResourceSet fakeResourceSet, XtextResource fakeResource) {
				fakeResource=xtextResource;
				fakeResourceSet=xtextResource.getResourceSet();			
			}
		};


		StyledTextXtextAdapter xTextAdaptor = new StyledTextXtextAdapter(xtextInjector,contextProvider);
		xTextAdaptor.adapt(shellContainer.styledText);


The functionality is there! The problem is that the textEditor is totally empty and it does not show me the particular object that I want from Model. When I press ctrl+space I get the root of the model ! As if there is nothing in the Xtext resource file.

I'd appreciate if you could help me on this,
Thanks,
Bests

Re: XText TextViewer instead of Editor [message #1729516 is a reply to message #1729511] Fri, 15 April 2016 03:47 Go to previous messageGo to next message
Christian Dietrich is currently offline Christian DietrichFriend
Messages: 14661
Registered: July 2009
Senior Member
Can you please share a complete example? where does xtextResource come from?

Twitter : @chrdietrich
Blog : https://www.dietrich-it.de
Re: XText TextViewer instead of Editor [message #1729517 is a reply to message #1729516] Fri, 15 April 2016 03:53 Go to previous messageGo to next message
Christian Dietrich is currently offline Christian DietrichFriend
Messages: 14661
Registered: July 2009
Senior Member
btw

fakeResource=xtextResource;
fakeResourceSet=xtextResource.getResourceSet();

does not work in java.



Twitter : @chrdietrich
Blog : https://www.dietrich-it.de
Re: XText TextViewer instead of Editor [message #1729519 is a reply to message #1729516] Fri, 15 April 2016 04:04 Go to previous messageGo to next message
Parsa Pourali is currently offline Parsa PouraliFriend
Messages: 210
Registered: February 2014
Senior Member
Hi Christian,

Thank you for your reply, I am using the code from sirius+Xtext integration on github. I just changed the code a little bit to run with double click on the object rather than a java extension.

So, if you just take a look at the createXtextEditor() method, there is segment for creating EmbeddedEditor. I just removed this EmbeddedEditor and added my code for SttyledTextXtextAdapter. So, the xtextresource is created based on the semantic element that I pass to this class. It is Weird because it works fine for the EmbeddedEditor and shows the text for the semantic element, but when I use StyledXtextAdapter it doesn't work and gives me empty text editor as if resource is totally empty! I can use content assistant and coloring is working but I guess the resource is just not set ! Confused

BTW, can I use StyledXtextCellEditor instead of StyledXtextAdapter ? They are pretty much the same, right ?

Thanks a lot,
Best Regards,
Parsa

/******************************************************************************
 * Copyright (c) 2011 Obeo  and others.
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the Eclipse Public License v1.0
 * which accompanies this distribution, and is available at
 * http://www.eclipse.org/legal/epl-v10.html
 *
 * Contributors:
 *    Obeo  - initial API and implementation
 ****************************************************************************/

package org.obeonetwork.dsl.viewpoint.xtext.support;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.Rectangle;
import org.eclipse.emf.common.util.BasicMonitor;
import org.eclipse.emf.common.util.URI;
import org.eclipse.emf.compare.Comparison;
import org.eclipse.emf.compare.EMFCompare;
import org.eclipse.emf.compare.merge.BatchMerger;
import org.eclipse.emf.compare.merge.IBatchMerger;
import org.eclipse.emf.compare.merge.IMerger;
import org.eclipse.emf.compare.rcp.EMFCompareRCPPlugin;
import org.eclipse.emf.compare.scope.DefaultComparisonScope;
import org.eclipse.emf.compare.scope.IComparisonScope;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.util.EcoreUtil;
import org.eclipse.emf.transaction.RecordingCommand;
import org.eclipse.emf.transaction.TransactionalEditingDomain;
import org.eclipse.emf.transaction.util.TransactionUtil;
import org.eclipse.gef.EditPartViewer;
import org.eclipse.gmf.runtime.diagram.ui.editparts.DiagramRootEditPart;
import org.eclipse.gmf.runtime.diagram.ui.editparts.IGraphicalEditPart;
import org.eclipse.gmf.runtime.diagram.ui.parts.DiagramEditDomain;
import org.eclipse.gmf.runtime.diagram.ui.parts.IDiagramEditDomain;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.sirius.viewpoint.DSemanticDecorator;
import org.eclipse.sirius.viewpoint.ViewpointPackage;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.custom.VerifyKeyListener;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.events.VerifyEvent;
import org.eclipse.swt.graphics.Font;
import org.eclipse.swt.graphics.FontData;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Decorations;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.xtext.nodemodel.ICompositeNode;
import org.eclipse.xtext.nodemodel.util.NodeModelUtils;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.resource.IResourceFactory;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.resource.XtextResourceSet;
import org.eclipse.xtext.ui.editor.XtextSourceViewer;
import org.eclipse.xtext.ui.editor.embedded.EmbeddedEditor;
import org.eclipse.xtext.ui.editor.embedded.EmbeddedEditorFactory;
import org.eclipse.xtext.ui.editor.embedded.EmbeddedEditorModelAccess;
import org.eclipse.xtext.ui.editor.embedded.IEditedResourceProvider;
import org.eclipse.xtext.ui.editor.info.ResourceWorkingCopyFileEditorInput;
import org.eclipse.xtext.ui.editor.model.IXtextDocument;
import org.eclipse.xtext.util.concurrent.IUnitOfWork;

import com.google.inject.Injector;

/* largely inspired by "org.eclipse.xtext.gmf.glue" from XText examples */
public class XtextEmbeddedEditor {

	private static int MIN_EDITOR_WIDTH = 100;

	private static int MIN_EDITOR_HEIGHT = 20;

	private IGraphicalEditPart hostEditPart;

	private IEditorPart diagramEditor;

	private EmbeddedEditorModelAccess xtextPartialEditor;

	private final Injector xtextInjector;

	private Resource originalResource;

	private XtextResource xtextResource;

	private String semanticElementFragment;

	private Decorations xtextEditorComposite;

	private EmbeddedEditor xTextEmbeddedEditor;

	public XtextEmbeddedEditor(IGraphicalEditPart editPart,
			Injector xtextInjector) {
		this.hostEditPart = editPart;
		this.xtextInjector = xtextInjector;
	}

	protected EObject resolveSemanticElement(IGraphicalEditPart hostEditPart) {
		EObject eObject = hostEditPart.resolveSemanticElement();
		if (isDSemanticDecorator(eObject)) {
			DSemanticDecorator semanticDecorator = (DSemanticDecorator) eObject;
			return semanticDecorator.getTarget();
		}
		return resolveSemanticElement(hostEditPart);
	}

	private boolean isDSemanticDecorator(EObject eObject) {
		return ViewpointPackage.eINSTANCE.getDSemanticDecorator().isInstance(
				eObject);
	}

	public void showEditor() {
		try {
			EObject originalSemanticElement = resolveSemanticElement(hostEditPart);
			if (originalSemanticElement == null) {
				return;
			}
			this.originalResource = originalSemanticElement.eResource();
			// Clone root EObject
			EObject semanticElement = EcoreUtil.copy(originalResource
					.getContents().get(0));
			if (this.xtextResource == null) {
				this.xtextResource = createVirtualXtextResource(
						originalResource.getURI(), semanticElement);
			}

			// TODO manage multi resource with Xtext Linking or Scoping service
			semanticElementFragment = originalResource
					.getURIFragment(originalSemanticElement);
			if (semanticElementFragment == null
					|| "".equals(semanticElementFragment)) {
				return;
			}
			IDiagramEditDomain diagramEditDomain = hostEditPart
					.getDiagramEditDomain();
			diagramEditor = ((DiagramEditDomain) diagramEditDomain)
					.getEditorPart();
			createXtextEditor();
		} catch (Exception e) {
			Activator.logError(e);
		} finally {
			if (hostEditPart != null) {
				hostEditPart.refresh();
			}
		}
	}

	/**
	 * Close this editor.
	 * 
	 * @param isReconcile
	 */
	public void closeEditor(boolean isReconcile) {
		if (xtextPartialEditor != null) {
			if (isReconcile) {
				try {
					updateXtextResource();
				} catch (Exception exc) {
					Activator.logError(exc);
				}
			}
			// xtextEditor.dispose();
			if (xtextEditorComposite != null) {
				this.xtextEditorComposite.dispose();
				xtextEditorComposite = null;
			}
			xtextPartialEditor = null;
		}
	}

	private XtextResource createVirtualXtextResource(URI uri,
			EObject semanticElement) throws IOException {
		IResourceFactory resourceFactory = xtextInjector
				.getInstance(IResourceFactory.class);
		// TODO use the synthetic scheme.
		XtextResourceSet rs = xtextInjector.getInstance(XtextResourceSet.class);
		rs.setClasspathURIContext(getClass());
		// Create virtual resource
		XtextResource xtextVirtualResource = (XtextResource) resourceFactory
				.createResource(URI.createURI(uri.toString()));
		rs.getResources().add(xtextVirtualResource);

		// Populate virtual resource with the given semantic element to edit
		xtextVirtualResource.getContents().add(semanticElement);

		// Save and reparse in order to initialize virtual Xtext resource
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		xtextVirtualResource.save(out, Collections.emptyMap());
		xtextVirtualResource.reparse(new String(out.toByteArray()));

		return xtextVirtualResource;
	}

	protected void updateXtextResource() throws IOException,
			BadLocationException {
		String newText = xtextPartialEditor.getSerializedModel();
		xtextResource.reparse(newText);
		EcoreUtil.resolveAll(xtextResource);
		final IParseResult parseResult = xtextResource.getParseResult();
		if (!parseResult.hasSyntaxErrors() && !hasDanglingRefs(xtextResource)) {
			reconcile(originalResource, xtextResource);
		}
	}

	private boolean hasDanglingRefs(XtextResource xtextResource2) {
		return EcoreUtil.UnresolvedProxyCrossReferencer.find(xtextResource2)
				.size() > 0;
	}

	private void reconcile(Resource resourceInSirius,
			XtextResource resourceInEmbeddedEditor) {
		try {

			IComparisonScope scope = new DefaultComparisonScope(
					resourceInSirius, resourceInEmbeddedEditor, null);
			final Comparison comparison = EMFCompare.builder().build()
					.compare(scope);

			IMerger.Registry mergerRegistry = EMFCompareRCPPlugin.getDefault()
					.getMergerRegistry();
			final IBatchMerger merger = new BatchMerger(mergerRegistry);

			final TransactionalEditingDomain editingDomain = TransactionUtil
					.getEditingDomain(originalResource);
			editingDomain.getCommandStack().execute(
					new RecordingCommand(editingDomain,
							"update resource after direct text edit") {

						@Override
						protected void doExecute() {
							merger.copyAllRightToLeft(
									comparison.getDifferences(),
									new BasicMonitor());
						}
					});
		} catch (Exception e) {
			Activator.logError(e);
		}

	}

	/**
	 * Create the XText editor
	 * 
	 * @param editorInput
	 *            the editor input
	 * @throws Exception
	 */
	protected void createXtextEditor() throws Exception {
		DiagramRootEditPart diagramEditPart = (DiagramRootEditPart) hostEditPart
				.getRoot();
		Composite parentComposite = (Composite) diagramEditPart.getViewer()
				.getControl();

		EObject semanticElementInDocument = xtextResource
				.getEObject(semanticElementFragment);
		ICompositeNode rootNode = xtextResource.getParseResult().getRootNode();
		String allText = rootNode.getText();
		ICompositeNode elementNode = NodeModelUtils
				.findActualNodeFor(semanticElementInDocument);
		String prefix = allText.substring(0, elementNode.getOffset() - 1);
		String editablePart = allText.substring(elementNode.getOffset(),
				elementNode.getEndOffset());
		String suffix = allText.substring(elementNode.getEndOffset());
		xtextEditorComposite = new Decorations(parentComposite, SWT.RESIZE
				| SWT.ON_TOP | SWT.BORDER);
		xtextEditorComposite.setLayout(new FillLayout());

/* I remove this part:
		EmbeddedEditorFactory factory = new EmbeddedEditorFactory();
		xtextInjector.injectMembers(factory);
		xTextEmbeddedEditor = factory.newEditor(new IEditedResourceProvider() {

			@Override
			public XtextResource createResource() {
				return xtextResource;
			}
		}).showErrorAndWarningAnnotations().withParent(xtextEditorComposite);
		xtextPartialEditor = xTextEmbeddedEditor.createPartialEditor(prefix,
				editablePart, suffix, true);
*/

// Add this part instead
IXtextFakeContextResourcesProvider contextProvider=new IXtextFakeContextResourcesProvider() {

			@Override
			public void populateFakeResourceSet(ResourceSet fakeResourceSet, XtextResource fakeResource) {
				fakeResource=xtextResource;
				fakeResourceSet=xtextResource.getResourceSet();			
			}
		};


		StyledTextXtextAdapter xTextAdaptor = new StyledTextXtextAdapter(xtextInjector,contextProvider);
		xTextAdaptor.adapt(shellContainer.styledText);

//
		addKeyVerifyListener();
		setEditorBounds();
		xtextEditorComposite.setVisible(true);
		xtextEditorComposite.forceFocus();
	}

	private void addKeyVerifyListener() {
		final StyledText xtextTextWidget = xTextEmbeddedEditor.getViewer()
				.getTextWidget();
		xtextTextWidget.addVerifyKeyListener(new VerifyKeyListener() {
			public void verifyKey(VerifyEvent e) {
				int keyCode = e.keyCode;
				if ((e.stateMask & SWT.CTRL) != 0
						&& ((keyCode == SWT.KEYPAD_CR) || (keyCode == SWT.CR))) {
					e.doit = false;
					closeEditor(true);
				}
				if (keyCode == SWT.ESC) {
					e.doit = false;
					closeEditor(false);
				}

			}
		});
	}

	private void setEditorBounds() {
		// mind the added newlines
		String editString = xtextPartialEditor.getEditablePart();

		int numLines = StringUtil.getNumLines(editString);
		int numColumns = StringUtil.getMaxColumns(editString);

		IFigure figure = hostEditPart.getFigure();
		Rectangle bounds = figure.getBounds().getCopy();
		DiagramRootEditPart diagramEditPart = (DiagramRootEditPart) hostEditPart
				.getRoot();
		IFigure contentPane = diagramEditPart.getContentPane();
		contentPane.translateToAbsolute(bounds);
		EditPartViewer viewer = hostEditPart.getViewer();
		Control control = viewer.getControl();
		while (control != null && false == control instanceof Shell) {
			bounds.translate(control.getBounds().x, control.getBounds().y);
			control = control.getParent();
		}

		Font font = figure.getFont();
		FontData fontData = font.getFontData()[0];
		int fontHeightInPixel = fontData.getHeight();

		int width = Math.max(fontHeightInPixel * (numColumns + 3),
				MIN_EDITOR_WIDTH);
		int height = Math.max(fontHeightInPixel * (numLines + 4),
				MIN_EDITOR_HEIGHT);
		xtextEditorComposite.setBounds(bounds.x - 200, bounds.y - 120, width,
				height);
		xtextEditorComposite.setBounds(bounds.x - 200, bounds.y - 120,
				width + 250, height + 50);
	}

}

[Updated on: Fri, 15 April 2016 04:06]

Report message to a moderator

Re: XText TextViewer instead of Editor [message #1729522 is a reply to message #1729519] Fri, 15 April 2016 05:17 Go to previous messageGo to next message
Christian Dietrich is currently offline Christian DietrichFriend
Messages: 14661
Registered: July 2009
Senior Member
sry i have no idea on that how it is intended to be used.ntl this is what works for me

@Override
	public void createPartControl(Composite parent) {
		Model model = MyDslFactory.eINSTANCE.createModel();
		Greeting g1 = MyDslFactory.eINSTANCE.createGreeting();
		Greeting g2 = MyDslFactory.eINSTANCE.createGreeting();
		Greeting g3 = MyDslFactory.eINSTANCE.createGreeting();
		g1.setName("G1");
		g2.setName("G2");
		g3.setName("G3");
		model.getGreetings().add(g1);
		model.getGreetings().add(g2);
		model.getGreetings().add(g3);
		
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		
		IXtextFakeContextResourcesProvider fake = new IXtextFakeContextResourcesProvider() {
			
			@Override
			public void populateFakeResourceSet(ResourceSet fakeResourceSet, XtextResource fakeResource) {
				
				fakeResource.getContents().add(model);
				
				try {
					fakeResource.save(out, SaveOptions.newBuilder().format().getOptions().toOptionsMap());
					fakeResource.reparse(new String(out.toByteArray(), Charsets.UTF_8));
					
				} catch (IOException e) {
					e.printStackTrace();
				}
			
			}
		};
		
		
		StyledTextXtextAdapter adapter = new StyledTextXtextAdapter(injector, fake );
		StyledText styledText = new StyledText(parent,SWT.NONE);
		adapter.adapt(styledText);
		ICompositeNode node = NodeModelUtils.findActualNodeFor(((Model)adapter.getFakeResourceContext().getFakeResource().getContents().get(0)).getGreetings().get(1));
		styledText.setText(new String(out.toByteArray(), Charsets.UTF_8));
		adapter.setVisibleRegion(node.getOffset(),  node.getLength());
	}


Twitter : @chrdietrich
Blog : https://www.dietrich-it.de
Re: XText TextViewer instead of Editor [message #1729583 is a reply to message #1729522] Fri, 15 April 2016 16:14 Go to previous messageGo to next message
Parsa Pourali is currently offline Parsa PouraliFriend
Messages: 210
Registered: February 2014
Senior Member
Thanks a lot Christian,

It is working now Smile Now I see how it works Smile

BTW, Do you know if I can embed this StyledTextAdapter in a label of a transition/edge? Currently I'm just showing this styledtext as a popup to the user, but I have seen in Yakindu they embedded sth like this into the label of the transition.

Thanks again,
Best Regards,
Parsa
Re: XText TextViewer instead of Editor [message #1729649 is a reply to message #1729522] Sat, 16 April 2016 23:34 Go to previous messageGo to next message
Parsa Pourali is currently offline Parsa PouraliFriend
Messages: 210
Registered: February 2014
Senior Member
Hi again Christian,

I found that the StyledXtextAdapter shows the full text of my DSL file perfectly. However, when I pass the offset and length of my node to the setVisibleRegion(), it throws the following error. And, I am sure that the length of file is OK and the offset exists. I tried to trace the code and found that when I pass the setVisibleRegion(1752,9) , it turns out to become (3503,-1752) somewhere inside and have no idea why ! I though you might have some idea !

Thanks,
Bests,
Parsa
java.lang.IllegalArgumentException: Invalid visible region argument
	at org.eclipse.jface.text.TextViewer.setVisibleRegion(TextViewer.java:3678)
	at org.eclipse.jface.text.source.projection.ProjectionViewer.setVisibleRegion(ProjectionViewer.java:703)
	at org.yakindu.base.xtext.utils.jface.viewers.StyledTextXtextAdapter.setVisibleRegion(StyledTextXtextAdapter.java:269)
	at com.uwaterloo.cs.forml.viewpoint.xtext.support.AbstractXtextEmbeddedEditor.createPartControl(AbstractXtextEmbeddedEditor.java:499)
	at com.uwaterloo.cs.forml.viewpoint.xtext.support.AbstractXtextEmbeddedEditor.createXtextEditor(Unknown Source)
	at com.uwaterloo.cs.forml.viewpoint.xtext.support.AbstractXtextEmbeddedEditor.showEditor(Unknown Source)
	at com.uwaterloo.cs.forml.viewpoint.xtext.support.XtextEmbeddedEditorForGuard.showEditor(XtextEmbeddedEditorForGuard.java:106)
	at com.uwaterloo.cs.forml.viewpoint.xtext.support.CreateEmbeddedEditors$1.run(CreateEmbeddedEditors.java:107)
	at org.eclipse.swt.widgets.Synchronizer.syncExec(Synchronizer.java:186)
	at org.eclipse.ui.internal.UISynchronizer.syncExec(UISynchronizer.java:145)
	at org.eclipse.swt.widgets.Display.syncExec(Display.java:4761)
	at com.uwaterloo.cs.forml.viewpoint.xtext.support.CreateEmbeddedEditors.runFormViewTransitionEditor(CreateEmbeddedEditors.java:70)
	at com.uwaterloo.cs.forml.viewpoint.xtext.support.action.OpenXtextEmbeddedEditor.execute(OpenXtextEmbeddedEditor.java:70)
	at org.eclipse.sirius.business.internal.helper.task.operations.ExternalJavaActionTask.execute(ExternalJavaActionTask.java:93)
	at org.eclipse.sirius.business.internal.helper.task.ExecuteToolOperationTask.executeTask(ExecuteToolOperationTask.java:106)
	at org.eclipse.sirius.business.internal.helper.task.ExecuteToolOperationTask.executeTask(ExecuteToolOperationTask.java:117)
	at org.eclipse.sirius.business.internal.helper.task.ExecuteToolOperationTask.execute(ExecuteToolOperationTask.java:90)
	at org.eclipse.sirius.business.api.helper.task.TaskExecutor.execute(TaskExecutor.java:64)
	at org.eclipse.sirius.tools.api.command.SiriusCommand.doExecute(SiriusCommand.java:80)
	at org.eclipse.emf.transaction.RecordingCommand.execute(RecordingCommand.java:135)
	at org.eclipse.sirius.diagram.ui.tools.api.command.GMFCommandWrapper.doExecuteWithResult(GMFCommandWrapper.java:102)
	at org.eclipse.gmf.runtime.emf.commands.core.command.AbstractTransactionalCommand.doExecute(AbstractTransactionalCommand.java:247)
	at org.eclipse.emf.workspace.AbstractEMFOperation.execute(AbstractEMFOperation.java:150)
	at org.eclipse.sirius.diagram.ui.tools.internal.commands.WrappingCommandIgnoringAffectedFiles.execute(WrappingCommandIgnoringAffectedFiles.java:124)
	at org.eclipse.core.commands.operations.DefaultOperationHistory.execute(DefaultOperationHistory.java:516)
	at org.eclipse.sirius.diagram.ui.tools.internal.editor.DDiagramCommandStack.execute(DDiagramCommandStack.java:71)
	at org.eclipse.sirius.diagram.ui.tools.internal.editor.DDiagramCommandStack.execute(DDiagramCommandStack.java:52)
	at org.eclipse.gmf.runtime.diagram.ui.parts.DiagramCommandStack.execute(DiagramCommandStack.java:156)
	at org.eclipse.gmf.runtime.diagram.ui.editparts.ConnectionEditPart.performRequest(ConnectionEditPart.java:1476)
	at org.eclipse.sirius.diagram.ui.edit.api.part.AbstractDiagramEdgeEditPart.performRequest(AbstractDiagramEdgeEditPart.java:703)
	at org.eclipse.gef.tools.SelectEditPartTracker.performOpen(SelectEditPartTracker.java:194)
	at org.eclipse.gef.tools.SelectEditPartTracker.handleDoubleClick(SelectEditPartTracker.java:137)
	at org.eclipse.gef.tools.AbstractTool.mouseDoubleClick(AbstractTool.java:1069)
	at org.eclipse.gef.tools.SelectionTool.mouseDoubleClick(SelectionTool.java:527)
	at org.eclipse.gef.EditDomain.mouseDoubleClick(EditDomain.java:231)
	at org.eclipse.gef.ui.parts.DomainEventDispatcher.dispatchMouseDoubleClicked(DomainEventDispatcher.java:291)
	at org.eclipse.draw2d.LightweightSystem$EventHandler.mouseDoubleClick(LightweightSystem.java:518)
	at org.eclipse.swt.widgets.TypedListener.handleEvent(TypedListener.java:196)
	at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
	at org.eclipse.swt.widgets.Display.sendEvent(Display.java:4362)
	at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1113)
	at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4180)
	at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3769)
	at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$4.run(PartRenderingEngine.java:1127)
	at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
	at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:1018)
	at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:156)
	at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:694)
	at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:337)
	at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:606)
	at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
	at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:139)
	at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:134)
	at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:104)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:380)
	at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:235)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:669)
	at org.eclipse.equinox.launcher.Main.basicRun(Main.java:608)
	at org.eclipse.equinox.launcher.Main.run(Main.java:1515)
	at org.eclipse.equinox.launcher.Main.main(Main.java:1488)
Re: XText TextViewer instead of Editor [message #1729654 is a reply to message #1729649] Sun, 17 April 2016 07:48 Go to previous messageGo to next message
Christian Dietrich is currently offline Christian DietrichFriend
Messages: 14661
Registered: July 2009
Senior Member
No. You have to Debug. Do you Use a styledtext oder a styledtextex

Twitter : @chrdietrich
Blog : https://www.dietrich-it.de
Re: XText TextViewer instead of Editor [message #1729730 is a reply to message #1729654] Mon, 18 April 2016 14:51 Go to previous messageGo to next message
Parsa Pourali is currently offline Parsa PouraliFriend
Messages: 210
Registered: February 2014
Senior Member
Hi Christian,
Not sure what you mean by styledtextex, but I am using StyledText. my code is below. I found that this is related to the bug: https://bugs.eclipse.org/bugs/show_bug.cgi?id=352847

The bug is saying that offset = master.getLineOffset(line); should be changed to offset += master.getLineOffset(line); and in my case, I guess the it is the other way around !
	public void createPartControl(Composite parent, EObject elem) {

		ByteArrayOutputStream out = new ByteArrayOutputStream();

		IXtextFakeContextResourcesProvider fake = new
				IXtextFakeContextResourcesProvider() {

			@Override
			public void populateFakeResourceSet(ResourceSet fakeResourceSet,
					XtextResource fakeResource) {

				
				fakeResource.getContents().clear();
				fakeResource.getContents().add(EcoreUtil.getRootContainer(elem));

				try {
					fakeResource.save(out,
							SaveOptions.newBuilder().format().getOptions().toOptionsMap());
					fakeResource.reparse(new String(out.toByteArray(), Charsets.UTF_8));

				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		};
		StyledTextXtextAdapter adapter=new StyledTextXtextAdapter(xtextInjector, fake);
		StyledText styledText = new StyledText(parent,SWT.WRAP );
		adapter.adapt(styledText);

		ICompositeNode node = NodeModelUtils.findActualNodeFor((adapter.getFakeResourceContext().getFakeResource().getEObject(semanticElementFragment)));
		String s =node.getText();
		

		styledText.setText(new String(out.toByteArray(), Charsets.UTF_8));
		
		adapter.setVisibleRegion((node.getOffset(), node.getLength()));
	}


and this is the code for XtextSourceViewer visible region:
/**
	 * Overwritten to handle offset properly.
	 */
	@Override
	protected boolean updateSlaveDocument(IDocument slaveDocument,
			int modelRangeOffset, int modelRangeLength)
			throws BadLocationException {
		if (slaveDocument instanceof ProjectionDocument) {
			ProjectionDocument projection = (ProjectionDocument) slaveDocument;

			int offset = modelRangeOffset;
			int length = modelRangeLength;

			if (!isProjectionMode()) {
				// mimic original TextViewer behavior
				IDocument master = projection.getMasterDocument();
				int line = master.getLineOfOffset(modelRangeOffset);
				offset += master.getLineOffset(line);
				length = (modelRangeOffset - offset) + modelRangeLength;
			}

			try {
				// fHandleProjectionChanges= false;
				setPrivateHandleProjectionChangesField(false);
				projection.replaceMasterDocumentRanges(offset, length);
			} finally {
				// fHandleProjectionChanges= true;
				setPrivateHandleProjectionChangesField(true);
			}
			return true;
		}
		return false;
	}


Just thought it might be useful to know !
Thanks,
Bests,
Parsa

[Updated on: Mon, 18 April 2016 15:04]

Report message to a moderator

Re: XText TextViewer instead of Editor [message #1729732 is a reply to message #1729730] Mon, 18 April 2016 14:55 Go to previous messageGo to next message
Christian Dietrich is currently offline Christian DietrichFriend
Messages: 14661
Registered: July 2009
Senior Member
sry i fear you have to digg yourself

Twitter : @chrdietrich
Blog : https://www.dietrich-it.de
Re: XText TextViewer instead of Editor [message #1729744 is a reply to message #1729732] Mon, 18 April 2016 15:55 Go to previous message
Parsa Pourali is currently offline Parsa PouraliFriend
Messages: 210
Registered: February 2014
Senior Member
Hi Christian,

I just disregarded the Yakindu implementation of set visible region and have written my own class to override the set visible region for my purpose and it is working perfectly Smile

Thanks,
Parsa
Previous Topic:Re: [XCore] The Body of the method
Next Topic:Disable formatting feature
Goto Forum:
  


Current Time: Fri Mar 29 00:57:12 GMT 2024

Powered by FUDForum. Page generated in 0.04212 seconds
.:: Contact :: Home ::.

Powered by: FUDforum 3.0.2.
Copyright ©2001-2010 FUDforum Bulletin Board Software

Back to the top