Tuesday, August 26, 2014

Graphical Views for Xtext ctd.

(Read my previous post for a rationale on graphical views)

No matter with what graphics technology you choose to implement a diagram for your Xtext-based language, there are a few things you should know in order to connect the diagram view/editor to the rest of the infrastructure.

Let us first have a look how to implement a context menu action for the Xtext editor to show the element at the current cursor position in the diagram. In Eclipse, you have to implement a handler for such an action. Xtext offers a bunch of classes making your life easier. EditorUtils detects the Xtext editor for the handler’s action and EObjectAtOffsetHelper finds the semantic model element at a given text offset.

As the document – and thereby the model parsed from it – is subject to editing, you have to make sure nobody is changing it while you traverse it to derive your diagram. You can execute code in a read transaction on the XtextDocument by wrapping it in an IUnitOfWork that you pass to the XtextDocument#readOnly method.

The following snipped shows an example handler written in Xtend.

Note that the @Inject annotation in the example requires you to use your language's executable extension factory when you register the handler class it in the plugin.xml of your language's UI plug-in. See the Xtext documentation for details.

To navigate from a diagram element back to it’s element definition in the text, you need to store some back reference. The model element itself is not suitable, as its lifecycle is bound to the one of the editor, and the parser is even free to expunge model elements whenever the document is re-parsed. As Xtext is based on EMF, each model element has a unique URI. You should always use these URIs to store references to model elements beyond the boundaries of a read/write transaction. An element’s URI is provided by EMF's EcoreUtil#getURI method.

Having the URI, the navigation to the respective model element’s definition is easiest to implement using Xtext’s IURIEditorOpener. If your diagram view supports selection listeners, the respective Xtend code could look like this:


lidochca G said...
This comment has been removed by the author.
Jan Köhnlein said...

@lidocha Please post Xtext related questions in the Xtext forum http://www.eclipse.org/forums/index.php?t=thread&frm_id=27

lidochca G said...

OK, I am sorry, I tried.

ameni said...

Is there any way to use a date picker in Xtext? I want to display a calendar and allow the user to pick a date.
Many thanks in advance

Jan Köhnlein said...

There is no standard datepicker for SWT, but you can google for one. Then customize the appropriate Xtext service, e.g. contentassist or hyperlinks according to the Xtext documentation to trigger it.

ameni said...

Thanks a lot for your response. I used the content assist :)