A look into Spec

Today I’m going to write about implementing the UI.
Since I want to have a nice UI in Pharo I choose Spec to build it, because it’s an on going project and there are lot of effort there, also I want to try it :).
Searching I found some tutorials and demos but some were quite old and not fully compatible with current version of Spec, so I will do a brief tutorial.

Spec was developed by Benjamin Van Ryseghem, you can find more information in: https://pharo.fogbugz.com/default.asp?spec.5.5.2

Anyway I think that the best place to take a look is in the examples that comes under Spec in Spec-Examples-PolyWidgets (mainly) and Spec-Examples-Widgets.

Doing the minimun for opening a Window
We want an empty window… but our empty window, so… how?
1. We are going to create a class extending ComposableModel

ComposableModel subclass: #TestSpec
instanceVariableNames: ”
classVariableNames: ”
poolDictionaries: ”
category: ‘Flamel-UI’

2. We have to implement 2 methods
2.1. initializeWidgets which responsability is to setup the components we will use (right now nothing)

initializeWidgets
“nothing to do here”

2.2 defaultSpec (class side) which returns a Layout saying which components will be render. There is a number of different layouts implemented: SpecColumnLayout, SpecRowLayout, and in the class methods of SpecLayout you can find a lot more. We will choose a very easy one:

defaultSpec
<spec>
^ SpecLayout composed

In fact you can name the method as you want, only need to be annotated with the <spec> pragma.

3. Open the window, we evaluate in a workspace:

TestSpec new openWithSpec

And we obtain:

emptyWindow

Nice… but quite empty… let’s put something inside!

Adding a component
1. Choose the widget to add, you can see some in Spec-Widgets, we want a text area so we will choose a TextModel.
2. In order to render the component we need to: create it and the tell the layout that we want to render it
2.1. Create the widget: define an instance variable and instantiate it during the initializeWidget using the Spec way to do it:

initializeWidgets

self instantiateModels: #(
text TextModel
)

We need to define text as an instance variable because instantiateModels assume that and try the elements of the array as an association: variable – kind where variable is a property in the object and makes it point to a new instance of the kind, in order to avoid the troubles we will define the variable.

Be careful with this (as Sean mention) if you define the variable while you are debugging you can get some nasty errors, so the advice is to define the variable first and then open the window.

At this point if we get anxious to see our cool text component and we open the window we will see that is still empty, this is because we never added it to the layout! So it’s not rendered.
2.2. Add the component in the layout, for this we will modify the defaultSpec class method and add a getter for the text property:

defaultSpec
^SpecColumnLayout new
add: #text;
yourself

We need the getter because the layout tries to access the variable sending the symbol as a message
3. Open it

withComponent

Communicating Components
Now we can open a window and have our components, but now we want to have several components that depends between them.
We will build a window with a text editor, when the content in the text editor changes we will see the message “The text changed” we can accept that pressing a button that says “Ok” and then the message will change to “You are up to date” (until someone change the content in the text …).
For doing this we will use:
– a TextModel called: example
– a LabelModel called: changes, starts with the text: “You are up to date”
– a ButtonModel called: acceptChanges, starts disabled and with the label: “Ok”

initializeWidgets
self instantiateModels: #(
example TextModel
changes LabelModel
acceptChanges ButtonModel ).

changes text: ‘You are up to date’ .
acceptChanges
label: ‘Ok’;
disable.

This is like we had before, only that we use other components that needs a little more of configuration.

The real challenge here is to link some effects: when the contents of example changes we want to change the message in changes and enable acceptChanges.
For defining this kind of interactions we should define the method initializePresenters defining the interactions, lucky our models understand several useful message to define an action to perform for an event, an example for a TextModel #whenTextIsAccepted: , #whenTextChanged:, …
Let’s define the actions:

initializePresenter
example whenTextIsAccepted: [ changes text: ‘The text Changed’. acceptChanges enable ].
acceptChanges action: [ changes text: ‘You are up to date’. acceptChanges disable ].

In this part we are done, now remember that in order to render the components we need to add it to the layout:

defaultSpec
<spec>

^ SpecColumnLayout new
add: #example;
add: #changes;
add: #acceptChanges;
yourself.

And we see:

3iguales

Quite easy and good, but lets improve the layout and play a little:

defaultSpec
<spec>
^SpecLayout composed
newColumn: [ :mainColumn| mainColumn
add: #example;
newRow: [ :feedbackRow | feedbackRow
add: #changes;
add: #acceptChanges]];
yourself.

2iguales

Better but still a little detail:

defaultSpec
<spec>
^SpecLayout composed
newColumn: [ :mainColumn| mainColumn
add: #example;
newRow: [ :feedbackRow | feedbackRow
add: #changes;
add: #acceptChanges
] height: 26.];

yourself.

final

A lot better! And It was quite easy, we can see that is well separated the layout from the components, and that we have a nice proposal for organizing our UI-Code:

  • We define the layout in #defaultSpec
  • We instantiate the components we are going to use in #initializeWidget
  • We define the interactions in: #initializePresenter.

This is very nice, but now I have a UI that separates the logic but still has a lot of responsibilities, is the UI who knows if I’ve accepted a change or if I’m up to date, also knows exactly what to tell me… I don’t think that this is the UI responsibility I want to model a class and that the UI shows it and not all in one like we have now.
And how do we do it?

Using a Model
We will have a model behind our window in 3 easy steps:
1. Create the model when initializing (you can create it or receive it, as you want, I will show the simplest way)

initialize
model := AcceptableText new. “replace for your domain class”
super initialize .

2. define the widgets, is almost the same that before

initializeWidgets
self instantiateModels: #(
example TextModel
changes LabelModel
acceptChanges ButtonModel ).

acceptChanges
label: ‘Ok’;
disable.

3. define the interaction

initializePresenter
example whenTextChanged: [:changed|
model text: changed.
self updateContents].

acceptChanges action: [
model acceptChanges.
self updateContents ]

updateContents
changes text: model status .
acceptChanges enabled: model hasUnreadChanges .

Look that when we are defining the actions we do 2 things:

1) modify the model
2) update the content of the widgets to show the new state of the model

We can see this actions that are using blocks as controllers (in a MVC pattern) since they modify the model from an input in the view and then update the view to show the new state in the model, in other frameworks we can use Bindings that do exactly the same.

In fact Ben pointed that Spec is far more closer from a MVP pattern than an MVC

In order to write a good UI we have to be very careful in how much code goes there, we probably will like to have small controllers delegating in the model instead of big controllers that does all the work for the model if we are not careful there we may end with anemic objects and spaghetti uis.

But to much talk and see how it ends:

final

Basically the same that before but now we have the linked ui using our domain object! Quite nice, and really really really simple to use.

Advertisements

The class definition message

Q: What is a class definition in Smalltalk?

A: Just another message send!

I love that simplicity… We don’t need control structures because we send messages and as we have an abstraction that represents some piece of code everything is happiness (yeah… blocks are cool stuff).

But still knowing it I go to the System Browser… I see the class definition and I don’t think that is another common message send, in fact when I realize that I can write that “magic code” in a workspace and have the same effect (creating the class) and see it in the system browser I said wow! After a while I thought “so lame… of course is just a message send”.

But however I go to the class definition again select an instance variable and I want to apply the rename refactoring… so… I ask for suggestions… and I got… nothing… just selecting a string and that confused me and then I realize, ok it’s just a message send and is just a string as argument so… that’s logic. The thing is that is not true that is just a message send… because for some reason we expect more in some points, by example when we are in the class definition…

So I did some prototypes for changing the representation and meanwhile I change my mind in the process.

1. The class definition is not represented as a message node

I was radical… I said: A Class Definition is always a class definition, so I changed the parser and when parsing I tried to parse a class definition
The prototype for this can be found in:

MCHttpRepository
location: ‘http://smalltalkhub.com/mc/gisela/ParsingClassDefinition/main&#8217;
user: ”
password: ”

I started with some issues here… The main one is:
How do I know I’m in a class definition, in the prototype you will see a very “innocent” implementation for realizing this… I just assume that if the message identifier I parsed is #subclass: it’s because a full message definition. There is no way to know if you are in a class definition until you finish the parsing.
Lot of the behavior is similar to a message send, and to implement the program node API we have to see how to share this code, it seems an efort without a real motive, because all the problems I was having relies in the fact that I assumed that a class definition is not a message send…

2.The class definition is created from a message send

Something in between, I still changed the parser but… transforming the message node parsed only if it was a class definition.
The prototype is in:

MCHttpRepository
location: ‘http://smalltalkhub.com/mc/gisela/MessageClassDefinition/main&#8217;
user: ”
password: ”

I had less problems 🙂 but still some strange behaviors, it was because I changed the AST and all the users of the ast should change, specially the visitors because now you have classDefinitionNode, categoryNode, variableDefinitionNode (…).

And then I have lots of failling test and for olving in the major part I endedUp delegating in the message node reference I had hold.
But this was expected, since I changed the AST structure in some point all the users of that structures need to be modified, but ended up having like the same that before… lot of behavior shared between a message node and a class definition, and sometimes the “new representation wasn’t even desiarable.
By example asking for suggestions… if I’m writting a method and write somthing like:

Object
subclass: #JunkClass
instanceVariableNames: ‘zzz’
classVariableNames: ”
poolDictionaries: ”
category: ‘DeleteMe-1’.

If I ask for suggestions in zzz I expect something like… “Extract local” and no “Rename” but in the definition space… I want that behavior, so… since that I decided that in some ocassions you look the class definition message as a special stuf, and that depends on the context where you are, so changed the parser wasn’t so great because at that point you don’t how they would like to treat that particular message, that it’s mostly user-decision.

3. Request the class definition explicitly

I don’t change the parser, I add a message to the nodes “asClassDefinition”

MCHttpRepository
location: ‘http://smalltalkhub.com/mc/gisela/ClassDefEnhaceTree/main&#8217;
user: ”
password: ”

And then let the user of that tree decide in which case he is and if it’s who apply to do the transformation or not.

With this approach the direct user of the ast must know if he wants this representation or not, the original tree doesn’t change, and we can think that is that we let that two representation exists, is a similar approach to the semantic analysis by default you don’t have the information and if you want that you explicitly need to say… ok do the analysis.
And in the end

I finish in the beginning, the AST represents the syntax structure and that is how we understand it and how we manipulate it, sometimes we want a transformation, we want more and we enhance that structure for better understanding.

At least for the suggestions it was only in the class definition view. And after dealing with the consequences of change I get convinced that we send message and that’s it, we don’t have and neither need an special syntax for defining a class, is just sending the right message to the right object, it’s simple and it’s very good.

And when we want another approach now we can have it, very easily.

 

Defining the UI

The main feature we want for the rewriting tool UI it’s to be example driven. Two very similar examples:

Option 1 – All in the same view

Imagen

Option 2 – A tabed view

Imagen

Imagen

Option 3 – A 3-Column layout

Screenshot from 2013-06-14 21:57:42

We also want to be possible:

  • select a method and drop into the example text editor.
  • manipulate the ASTs nodes in the text editor to make simple define transformations and matching.
  • highlight the matched parts from the example.
  • select scopes to apply the rule.
  • preview the changes.
  • show the transformation in the example expression.
  • modify an expression throw the example or writing the pattern.
  • output the smalltalk valid code that produces the effect we see in the example.

Next steps…

Now we have a very powerful tool but quite complex to use… The pattern’s definitions ends up been confusing and lot of people dismiss the tool for this.

The fact that the patterns are strings is one of the causes in misunderstanding and encourage to produce lot of mistakes, when we want to match an expression thinking in a method definition we think in terms of: a method contains this statement, or declares this variable and not in complex regular expressions, it’s also true that sometimes we end up with a cryptic expression, hard to understand by others (even for ourselves).

It would be great to have a very expressive api for what we want to do, for example make possible to say something similar to:

“some scope” pattern
includesStatement: anStatement;
hasTemporaryVariable: aVariable.

We should write some nice examples of usage and also take a look into the rewriting engine, we could do lot of improvements.

All of this sounds very ambitious, so I will start for defining an UI for make the patterns auto generated in an easy way with lot of cool features, specially example driven when building expressions.

Once we have the UI and a nice video showing how to use it… we can improve the API and make it more expressive and if we have time we will take a look in the rewrite engine… but first let’s do these easy to use!

A look into the rewrite tool

Trying to catch up with the current status in the rewrite tool my mentors suggested me to look into The Rewrite Tool, specially in a presentation from John Brant and Don Roberts.

I will write a short summary of what I read and then some conclusions about it.

The grammar of a method definition
The ultimate goal is to transform the code we have written, so we are going to focus in a method definition.
It’s very simple: we have the method name and a sequence of statements.
The method name can be unary, binary or keyword and the sequence node it’s conformed by temporary variables declaration (optional) and statements.

Representing the method definition
In the current implementation of Pharo we have an AST implemented that is very usefull for what we want to achive.
An AST or Abstract Syntax Tree is a tree representation of the syntax of an expresion.
So I will explain the main points in the representation of a method.
We have a MethodNode that contains (mainly) arguments, the selector (as the selector parts) and a body. Inside the body we have a SequenceNode that contains (mainly) the temporaries variables and a collection of statements. The statements can be any kind: AssigmentNode, ReturnNode, etc.
Its easier to inderstand with an example, if we have this method definition:

selector: arg1 and: arg2
|temp1 temp2|

temp1 := OrderedCollection new.
temp2 := arg1, arg2.
^temp1 + temp2

The AST will look like:
methodNode

Matching an expression
For matching the tool provides the possibility to indicate a pattern, and the ability to specify throw symbols different meta variables for matching.

The real power of the tool is the number of variants that admit, making it really flexible.

tableSymbols

Also exists the possibility to use another pattern for matching: {:node | <condition>} the node is a method node and the condition it’s valid Smalltalk code.

Some thoughts

  • In order to win flexibility, the patterns seems quite complex to write from scratch.
  • The real power for matching derives in the combination of symbols, but as the patterns are represented by strings it seems quite confusing.
  • Many times it’s easier to think in examples before writing the pattern.

A simple idea

The idea is very simple:

We want to change some code in a programmatic way

In order to do this, first we want to match the code we want and then change it.

Many times we want to match an expression having different information: about the selector, about the source code (temporary vars, statements).

Some examples:

  • all the methods with 2 arguments,
  • all methods called in a particular way
  • a method containing a specific statement.

The first conclusion is that we want a flexible way for matching.

In order to do transformations sometimes we want to refer to the existing code, sometimes this expressions are very complex.

My goal for this time is to develop tools to make simple writing searching patterns and easier writing transformations.

Here I will write about my GSoc project: Better rewriting rule tools implemented in Pharo Smalltalk, about the experience and progress.