Get your own free workspace
View
 

CS298

Page history last edited by PBworks 4 years ago

 

 

CS298 - JavaFX as a DSL in Scala / Groovy

by Sadiya Hameed (sadiya AT gmail.com)

Advisor: Dr. Cay Horstmann

Computer Science Dept., San Jose State University

 

From Dr. Horstmann's Project idea page:

At the JavaOne 2007 conference, Java FX was introduced as scripting language for Flash-like effects in Java Swing.

It seems unfortunate that it is yet another language. The modern trend is to provide domain-specific languages (DSLs) inside a larger host language. The goal of this project is to implement the functionality of Java FX as DSLs into the Scala and Groovy languages, and to reason about the suitability of these languages as DSL hosts. Scala claims to have been invented for just this purpose, and Groovy has had practical success in providing DSLs for XML builders, ORM, etc.

 

Link to CS297 Blog: cs297

Project proposal(CS297):  cs297proposal.pdf

CS297 Report: 297 Report.pdf

CS298 Proposal: CS298 - Proposal.pdf

 

Project Timeline:

 

Timeline

 

Task

 

Week 1, 2         (1/24 – 2/06)

Prepare and submit the CS298 proposal. Binding with expressions in Scala and Groovy

Week 3 to 5      (2/07 – 2/27)

Simulate dur operator in Scala and Groovy

Week 6, 7         (2/28 – 3/12)

Simulate do/do later keywords in Scala and Groovy

Week 8, 9         (3/13 – 3/26)

Implement list comprehension features from JavaFX in Scala and Groovy

Week 10 to 13  (3/27 – 4/23)

Write up of CS298 report

Week 14, 15     (4/24 – 5/07)

Submit report to committee and prepare oral presentation

 

To do:

  1. Groovy bind with expressions                                            
  2. Create Groovy sample application
  3. Incorporate bind into Scala sample application        (use JLabel)           
  4. set background color of JPanel                                          
  5. Is there a compiler option to check implicit conversions?  
  6. Write up on Bind with expressions in Scala and Groovy
  7. Check circular dependencies in bind and bind to self

Report (1st draft):

298 Report (1st draft).pdf

 

 


 

Week 12: (04/10 – 04/16)

 

To do:

  1. Fix Report outline
  2. Edit the Achievements
  3. Write up on bind 

     

1. Report Outline *Updated*

Introduction     

1. Domain Specific Languages 

2. JavaFX       

2.1. List of Important Features 

2.1.1.   Incremental dependency-based Evaluation       

2.1.2.   Triggers (Insert, delete and update)      

2.1.4.   dur operator    

2.1.5.   do and do later

2.1.6.   Sample JavaFX application

3. Host Languages

3.1. Scala        

3.1.1.   Operators as valid Identifiers    

3.1.2.   Single Parameter methods as infix operator       

3.1.3.   Parameterless methods

3.1.4.   Properties        

3.1.5.   Functions         

3.1.6.   Mixin Class Composition         

3.1.7.   Views              

3.2. Groovy     

3.2.1.   Parenthesis less methods & named parameters 

3.2.2.   Closure           

3.2.3.   Categories       

3.2.4.   DelegatingMetaClass

3.2.5.   ExpandoMetaClass

3.2.6.   Dynamic method invocation?

4. Rich Graphical User Interface DSL  

4.1.  DSL in Scala           

4.1.1.   Incremental dependency-based Evaluation (Bind)

            4.1.1.1.   Bound Property       

            4.1.1.2.   Bound Swing Components

            4.1.1.3.   Bound Bean Property

4.1.1.4.   Bind with Expressions

4.1.2.   dur operator

4.1.3.   do and do later

4.1.4.   Assessment of Scala as a DSL Host

4.2.  DSL in Groovy        

4.2.1.   Incremental dependency-based Evaluation (Bind)

4.2.1.1.   Bound Property

            4.2.1.2.   Bound Swing Components

4.2.1.3.   Bind with Expressions

4.2.2.   dur operator

4.2.3.   do and do later

4.2.4.   Assessment of Groovy as a DSL Host

4.3.      Sample Application

5. Evaluation of Scala and Groovy as DSL Host

6. Conclusion  

References      

Appendix A: Code      

1. Scala Code 

2. Groovy Code

 

2. Three Achievements *Updated*

1.      Evaluation of Scala / Groovy as DSL hosts.

2.      Working with developing languages, fluid feature sets and nascent IDEs.

3.      Innovatively utilizing dynamic features of Scala / Groovy.

 

3. Writeup on Bind

I started with the explanation of bind in JavaFX,  I am stuck at trying to create a sample that shows bind to function. The examples from net don't work directly on the version of JavaFX in my Netbeans,  I have converted one to the old syntax but on converting to the bare bone function bind between model and view it has stopped working. But after wasting a few hours on the code I moved on to the wrtite up for Scala bind. Will look into creating a simple example after writeup on bind for Scala and Groovy is done.

The first draft of JavaFX bind: JavaFX bind.pdf

 

The first draft of Scala Bind writeup: Scala Bind.pdf

Contains sections on Bound Property and Bound Swing Components

 

Also fixed the code for "Bind with expressions" example from last week. Created a BoundJFormattedTextField to allow binding with Double type BoundProp as Dr. Horstmann suggested.

Code:

      val field1 = new JFormattedTextField;      

      val field2 = new JFormattedTextField;

 

      var Celsius = new BoundPropDouble;

      var Fahrenheit = new BoundPropDouble;

      Fahrenheit bind (Celsius * 1.8) + 32.0;     

 

      Celsius := 45;

 

      field1.value bind Celsius;

      field2.value bind Fahrenheit; 

 

Source Code: src[TemperatureConverter v2].zip

 


 

Week 11: (04/03 – 04/09)

 

To do:

  1. Report outline
  2. Three Achievements
  3. Write up on bind with expressions  -- working on sample application

     

 

1. Report Outline

 

Introduction     

1. Domain Specific Languages 

2. JavaFX       

2.1. List of Important Features 

2.1.1.   Incremental dependency-based Evaluation       

2.1.2.   Triggers (Insert, delete and update)      

2.1.4.   dur operator    

2.1.5.   do and do later

2.1.6.   Sample JavaFX application

3. Scala           

3.1. List of Features     

3.1.1.   Operators as valid Identifiers    

3.1.2.   Single Parameter methods as infix operator       

3.1.3.   Parameterless methods

3.1.4.   Properties        

3.1.5.   Functions         

3.1.6.   Mixin Class Composition         

3.1.7.   Views  

4. Groovy        

4.1. List of Features     

4.1.1.   Parenthesis less methods & named parameters 

4.1.2.   Closure           

4.1.3.   Categories       

4.1.4.   DelegatingMetaClass

4.1.5.   ExpandoMetaClass

4.1.6.   Dynamic method invocation?

5. Prototype DSLs      

5.1.      Scala Prototype           

5.1.1.   Incremental dependency-based Evaluation (Bind)

            5.1.1.1.   Bound Property

            5.1.1.2.   Bound Bean Property

            5.1.1.3.   Bound Swing Components

5.1.1.4.   Bind with Expressions

5.1.2.   dur operator

5.1.3.   do and do later

5.1.4.   Assessment of Scala as a DSL Host

5.2.      Groovy Prototype        

5.2.1.   Incremental dependency-based Evaluation (Bind)

5.2.1.1.   Bound Property

            5.2.1.2.   Bound Swing Components

5.2.1.3.   Bind with Expressions

5.2.2.   dur operator

5.2.3.   do and do later

5.2.4.   Assessment of Groovy as a DSL Host

5.3.      Sample Application

6. Evaluation/Comparison of Scala and Groovy as DSL Host

7. Conclusion  

References      

Appendix A: Code      

1. Scala Code 

2. Groovy Code

 

2. Three Achievements

1.      Evaluation and comparison of the dynamic features of Scala / Groovy and assessment of the ability of these languages to be DSL hosts.

2.      Creation of sample JavaFX like DSL for rich internet application development  with features providing easier and more readable syntax, and requiring less boiler plate code.

3.      Creation of powerful features like bind, useful in user interface development and many other domains.

 

3. Writeup on Bind with Expressions

I was trying to create a basic example to include in the report to explain bind (bind with swing components and bind with expressions). It is a basic application where you enter the temperature in Celsius and it converts it to Fahrenheit.

 

 

I am stuck at the following issue:

 

Code:

 var Celsius = new BoundPropDouble;

 var Fahrenheit = new BoundPropDouble;

 Fahrenheit bind (Celsius * 1.8) + 32.0;       //show off bind with expressions

 

 Celsius := 45;      //updates Fahrenheit's value

 

 //Issue: Celsius is a BoundProp of type Double and field.text is a BoundProp of type String.. How can I allow binding between two different types?

 field1.text bind Celsius;                    //show off bind with swing components

 field2.text bind Fahrenheit; 

Source Code: src[Temperature Converter].zip

Right now it is hacked so that TextField text is a BoundProp of type Double.. just to see the flow of work.

 

 


 

 

Week 10: (03/27 – 04/02)

Hours: 10

 

To do:

  1. Scala dur operator                                                         
  2. Groovy dur operator                                                           
  3. Groovy do & do later                -- Stuck!
  4. Property Literals                    

     

4. Property Literals

Seems like this is something we tried last semester and stopped when we ended up having to create new classes (e.g TextField) and manually write fire property change events for each property (e.g Text) since the property change events were not getting fired when the components were changed through GUI so we had to create our own Document Listeners.

 

1. Scala - dur operator

Changed the syntax of the dur operator to remove the clunkier bind part.

 

JavaFX syntax: loadingScreenOpacity = [1.0,0.99..0.0] dur 1000; 

 

Old Scala syntax for dur:    

var loadingScreenOpacity = new BoundProp[Int];

var arr = new Array[Int](10);

loadingScreenOpacity bind (arr dur 1000); 

 

New Scala syntax for dur:   

var loadingScreenOpacity = new BoundProp[Int];

loadingScreenOpacity dur (1 to 5, 1000);      //Can say 1 to 5 because Scala implicitly converts the Int to Range which has a function "to" for generating a range of numbers (only                                               //works on integers)

 

dur Code in BoundProp class:

def dur(arr: Seq[T], millisecs: Long) = {       //Seq is the parent class of all collections in Scala, T is the type of BoundProp

    val internal = this;                        //Had to store "this"(reference to BoundProp) to a local variable since inside the Runnable "this" refers to something else.

    var t = new Thread(new Runnable()

        {

            def run = {             

              for (i <- 0 to arr.length-1) {

                internal := arr(i);              

                Thread.sleep(millisecs);  

              }                                              

            }       

        });

    t.start();   

}

 

2. Groovy - dur operator

Changed the dur operator syntax in Groovy as well to get rid of bind. Also instead of ArrayList the due now accepts the java.utils.Collections class.

 

Old Groovy syntax:

BoundProp<Integer> loadingScreenOpacity = new BoundProp<Integer>(this);

loadingScreenOpacity.bind([1,2,3,4,5].dur(1000));

 

New Groovy syntax:

BoundProp<Integer> loadingScreenOpacity = new BoundProp<Integer>(this);

loadingScreenOpacity.dur([1,2,3,4,5], 1000);

 

dur Code in BoundProp class:

def dur(Collection<T> coll, Long milliSecs){   

        Closure func = {   

            for (i in 0..coll.size-1) {                           

                set(coll[i]);

                Thread.sleep(milliSecs);   

            }                 

        };

        new Thread(func).start();

}

 

3. Groovy - do/doLater

Last time we created the do/doLater functions and this week I was trying to port them into Object (or ThreadUtil) so that they were accessible everywhere.

 

Using Categories:

First attempt was using Groovy's categories, create something like a ThreadUtil (as suggested by Prof. Horstmann for the Scala code.. to create do/doLater as static methods in a ThreadUtil class rather than Object class to make it more Scalable)

 

Code for Usage of doLater and do:

use(ThreadUtilCategory){

      doLater {

           println("This will run in the EDT thread");        

      }

 

      doOutside {

           println("This will run in a New Thread");        

      }

}

 

Code for ThreadUtilCategory class:

class ThreadUtilCategory {

    static def doLater(Object obj, Closure func) {

        SwingUtilities.invokeLater(func);

    }

    static void doOutside(Object obj, Closure func){

         new Thread(func).start();    //closure implements runnable

    }

}

 

Using DelegatingMetaClass:

But Groovy says we can create new control structures with it so there has to be a way to add do/doLater to Object class and seamlessly say:

 

doLater{

   //....

}

 

So I tried the DelegatingMetaClass feature which we used to add bind to Groovy.

 

Code to for ObjectMetaClass:

package groovy.runtime.metaclass.java.lang;

 

class ObjectMetaClass extends DelegatingMetaClass{

    ObjectMetaClass(MetaClass metaclass){

        super(metaclass);      

    }

 

    public Object invokeStaticMethod(Object a_object, String a_methodName, Object[] a_arguments){

        if(a_methodName == "doLater"){       

            SwingUtilities.invokeLater((Closure)a_arguments[0]);           

        }

        else{

            super.invokeStaticMethod(a_object, a_methodName, a_arguments);

        }

    }

 

Code for Usage:

Problem is the method does not get inherited by other classes. So it is only callable on Object class.

Object.doLater{                    

 

  println("This will run in the EDT thread");

 

}

 

Using ExpandoMetaClass:

I found out that the ExpandoMetaClass provides the ability for added functionality to be inherited so I tried adding do/do Later with it.

 

Object.metaClass.'static'.doLater << {{SwingUtilities.invokeLater(it);}}  

ExpandoMetaClass.enableGlobally();             

doLater {                        //does not work.. only works for Object.doLater, Surprisingly works for "some string".doLater but not for String.doLater.. WEIRD!

 

  println("This will run in the EDT thread");

}

 

Anyways I have posted about this on the Groovy-user mailing list: How to create your own control structure. Will wait to see if I get a better way of doing this.   

 


Week 9: (03/20 – 03/26)

Spring Break - Wasted on Recovery:(

 


 

Week 7 & 8: (03/06 – 03/19)

 

To do:

  1. Incorporate bind into Scala sample application                   -- hit a road block
  2. Groovy do & do later                                                          -- in Progress
  3. Groovy dur operator                                                            -- in progress
  4. Groovy bind with expressions                                            -- not attempted yet
  5. Scala - dur operator                                                           -- Done with some issues remaining
  6. set background color of JPanel                                          --  not attempted  
  7. Is there a compiler option to check implicit conversions?   -- not found

     

Incorporate bind into Scala sample application

Since the background Image drawing and the current temperature printing etc. were done differently in Scala as compared to JavaFX, I can't figure out how to add bind to these. Sample codes are given below.

 

JavaFX code:

Group{

     ....

     content: bind getConditionImageForCode(todayConditionImages, weatherModel.todayConditionCode)  //No need to call repaint.. It gets taken care of by bind

}

Text{

     ....

     content: bind weatherModel.temperature.toString()

}

 

Scala code:

g2D.drawImage(getConditionImageForCode(todayConditionImages, weatherModel.todayConditionCode), 10, 2, null);  //The image returned from getConditionImageForCode is not assigned

                                                                                                                        // to an object but directly drawn

g2D.drawString(weatherModel.temperature.toString(), 105, 64);

 

In Scala code, method getConditionImageForCode returns an AnimatedImage and the image changes are handled by its animate method which calls repaint for each new image.

 

//code from animate method of AnimatedImage

for (val i <-0 to imgs; animate) {

    dolater{                         

        currentImage = images(i);                           

        weather.repaint();

    }

    Thread.sleep(frameDelay);                                  

} 

JavaFX classes like CompositeNode and Group etc. are specifically designed to work with bind. So apparently just emulating bind will not give us all the power of JavaFX in this area. But on the other hand all these classes could probably be created in Scala or existing classes rigged to work with bind, just like we did for JTextField and other components to get them to play nice with bind. Groovy seems to be doing just that as we will see in the SwingBuilder section coming up:) But I need to figure out what to add in the sample app to show off bind.

 

Groovy -- do, do later, dur operator

The Groovy world, it turns out, has been going in the same direction as our research with their SwingBuilder project. They seem to have implemented animate(something like the dur operator in JavaFX), bind, doOutside (do in JavaFX), doLater and an edt (execute in Event Dispatch Thread) and the code has the same declarative syntax flavor like JavaFX.

 

Links:

Danno Ferrin's Blog: New Swing Features in Groovy 1.5

Danno Ferrin's Blog: bind() and animate(), new and exciting features in SwingBuilder

 

Code snippets taken from above blog:

SwingBuilder's bind
import groovy.swing.SwingBuilder
import java.awt.Insets

swing = new SwingBuilder()
frame = swing.frame {
vbox {
slider(id:'slider', value:5)
button('Big Button?!',
margin: bind(source:slider, sourceProperty:'value', converter:{[it, it, it, it] as Insets}),
)
}
}
SwingBuilder's animate
swing = new SwingBuilder()
frame = swing.frame {
vbox {
slider(value:animate(0..100, id:'anime'))
button('Again! Again!', actionPerformed: {anime.rebind()})
slider(value:animate(0..100, repeat:true, interval:100, duration:1000))
}
}
Compared to this my attempt at dur in Groovy seems just plain sad!
JavaFX syntax: loadingScreenOpacity = [1.0,0.99..0.0] dur 1000;
Groovy syntax: loadingScreenOpacity.bind([1,2,3,4,5].dur(1000));

Groovy Code for dur operator:

 

The metaclass and some of the other features that were not working in the stable release last semester have now been incorporated in the stable release and also work in the updated eclipse plugin,  So I no longer had to download and build groovy source in order to run these features:)

 

ArrayList.metaClass.dur << {Long milliSecs ->

            BoundProp<Integer> internalBP = new BoundProp<Integer>(this);

       

            Closure func = {   

                for (i in 0..delegate.size-1) {

                    internalBP.set(delegate[i]);                  

                    Thread.sleep(milliSecs);   

                }                 

            };

            func.setDelegate(delegate);

            new Thread(func).start();

            return internalBP;

        }

 

Issues:

1. Had to use bind instead of = (cannot overload = operator in Groovy), could not figure out any other way of updating loadingScreenOpacity. The new values in our case are not actually returned but set into a BoundProperty which is bound to loadingScreenOpacity. It is not possible to return a value from the closure and still keep generating new values in the closure (as far as I could figure out).

 

2. The .. operator in Groovy seems to be working differently than what I expected

[1.0,0.99..0.0].dur 1000; //output = [1.0, 0.99], Where does the rest of the expression go? What we wanted [1.0,0.99,0.98,0.97,....,0.0]

[0,1..5].dur 1000; //output = [0, [1,2,3,4,5]], What we wanted:[0,1,2,3,4,5]

 

3. Generics have been updated in Groovy but I am still getting issues in it:

 

class BoundProp<T> extends PropertyChangeSupport implements PropertyChangeListener {

    T value;

   

    def BoundProp(Object source){

       super(source);

            value = new T();        

 

    }

    ...........

    ...........

   

    BoundProp<T> set(T newValue){       

        T oldValue = value;      //value and oldValue are both of type Object even though the BoundProp was created with type Integer

        value = (T)newValue;      //newValue is Integer.. so I had to put in a hack

        firePropertyChange("value", oldValue, newValue);

        this;

    }   

}

"Java's generics implementation incorporates a feature known as "type erasure" which "throws away" generic type information after completing static type checking. This allows Java to easily integrate with legacy "non-generics" libraries. Groovy currently does a little further and throws away generics information "at the source level". Generics information is kept within signatures where appropriate"

From Groovy Generics  

 

4. The dur method right now works for ArrayList only and not all types of collection.

 

5. Methods accepting single parameters can be written without parenthesis in Groovy (working below for bind) but is not working for dur implementation. Seems to be an issue when the method has another method as its parameter.

Cant say loadingScreenOpacity.bind [1,2,3,4,5].dur 1000, have to say loadingScreenOpacity.bind([1,2,3,4,5].dur(1000))

Groovy do/do later

Reference: Getting Stated Guide - Groovy Beans

Though Groovy doesn't support anonymous inner classes, it is possible to define action listeners inline through the means of closures. So instead of writing in Java:

 

      Processor deviceProc = ...

        deviceProc.addControllerListener(new ControllerListener() {

           public void controllerUpdate(ControllerEvent ce) {

              ...

           }

        }

 

        //You can do that in Groovy with a closure:

 

        //Add a closure for a particular method on the listener interface

        deviceProc.controllerUpdate = { ce -> println "I was just called with event $ce" }   

 

For do later I need to call EventQueue.invokeLater and run the closure passed to it, in the run method. Something like:

 

      EventQueue.invokeLater(new Runnable()

          {

              public void  run (){

                  System.out.println("In run method of EDT thread");   

                  func   

              }       

          });

 

So according to the above logic this would translate into something like EventQueue.run = {....}, but this does not work obviously since we need invokeLater. I finally used SwingUtilities for this instead.

 

void dolater(Closure func){                 

     SwingUtilities.invokeLater(func);            

 }

   

  void doInNewThread(Closure func){

       new Thread(func).start();    //closure implements runnable

  }

 

*TO DO* Do, do later now need to be added to Object class (Right now they are just methods in a Tester class).  I also have to move dur operator to the ArrayList class.

 

Scala dur operator:

To implement dur operator in Scala I followed the same approach as Groovy. So the results of the dur method are set to an internal BoundProp which is bound to loadingScreenOpacity variable. The  syntax was  just as bad if not worse than Groovy's.  It does not have a .. operator and you cannot do [1,2,3].dur as it doesn't recognize [1,2,3] syntax. Also we had to use one set of parenthesis.

 

Scala syntax for dur:    

var loadingScreenOpacity = new BoundProp[Int];

var arr = new Array[Int](10);

loadingScreenOpacity bind (arr dur 1000); 

Compare to JavaFX syntax: loadingScreenOpacity = [1.0,0.99..0.0] dur 1000;

Week 6: (02/28 – 03/05)

Hours: 11

 

To do:

  1. How does PropertyChangeSupport's source field become a Unit when extended from  --  Some explanation from the mailing list.
  2. Bind with expressions           --  done
  3. Implicit conversions of BoundProp and Ints to Term   --  Probably not possible for all cases
  4. Scope of Implicit conversion  --  A solution given below
  5. Incorporate bind in animation application  --  not attempted
  6. set background color of JPanel                   --  not attempted 

 

PropertyChangeSupport Issue:

We got rid of the issue by simply re-evaluating the terms. But following is the replies I have gotten from the mailing list:

 

Link to mailing list query:  Another super class constructor query

 

Also, I got this reply from Martin Odersky:

 

========================Email===============================

From: martin odersky <martin.odersky@epfl.ch>

Date: Tue, Mar 4, 2008 at 6:30 AM

Subject: Re: [scala-user] Another super class constructor query

 

1) Parameterless classes consistently get empty parameter lists. That is

 

 new IOException

 

is really the same as new IOException(). Or:

 

 extends Bar

 

is the same as

 

 extends Bar().

 

2) A parameter list gets converted to a single tuple parameter when

this is required. So

 

 extends Bar()

 

would be treated as

 

 extends Bar(())

 

... and that explains the behavior you are seeing. I also think this

goes too far. I'm not quite clear what to disallow, though. I think 1)

needs to stay as it is. As to 2), I suspect code would break if we did

change it.

 

Cheers

 

 -- Martin

========================Email===============================

 

Bind with Expressions:

The following code now works

 

========================CODE===============================

var a = new BoundPropInt;

var b = new BoundPropInt;

var c = new BoundPropInt;

 

//3 is implicitly converted to a term

a bind (3+b) +(c+2);                   //a bind 3+(2+1) also works .. should we dis-allow it?

 

System.out.println("a: " + a); //prints 5

 

b := 5;

System.out.println("a: " + a); //prints 10

 

c := 10;

System.out.println("a: " + a); //prints 20

========================CODE===============================

 

The following are examples of expressions that can be binded currently

 

a bind b                             

a bind b + 3                         a bind 3 + b

a bind b + c                        

a bind b + (c + d)                 a bind 2 + (3 + b)

a bind (b + c) + (d + e)        a bind (3 + b) + (c+2)  etc.

 

Source Code: src - (TestBind with Expressions).zip

 

Implicit conversions

While we are doing implicit conversions from Int to Term to facilitate binding of the form.. Term  bind  Int + Term (e.g. a bind 3 + b) but we cannot declare variables of type Int and handle everything with implicit conversions from Int to Term for the following reason:

 

Implicit conversion code:

implicit def Int2Term(i : Int) = new Num(i);

 

var a = 1;

var b = 2;

var c = 3;

 

a bind b + c;                    //works, calls bind of term but 'a' gets converted to Term on the spot but not forever.

System.out.println("a: " + a);   //calls print of Int and not Term, so prints 1 and not 5..implicit conversion is only called when required e.g. method or field not found

 

Refer to mailing List: Overriding methods and Views

 

So for the time being to use bind, a variable needs to be declared as a BoundPropInt.

 

Scope of Implicit conversion

I have not found a reference on how to limit scope of implicit conversion. This is just something I tried. Not sure if this was what Dr. Horstmann was looking for.  The idea was derived from Categories  in Groovy.

 

We can limit the scope of an implicit conversion by importing only in that scope e.g:

 

========================CODE===============================

a bind (3+b)          //does not have implicit conversion from Int to Term so + operation that takes a BoundPropInt and returns a Term (to be used by bind) not defined.

                      //Compiler complains!

{

  import utils.Term._;

 

  a bind (3+b)        //works

}

 

a bind (3+b)          //does not work

========================CODE===============================

 

 


Week 5: (02/21 – 02/27)

 

To do:

  1. Bind with expressions
  2. set background color of JPanel

 

JavaFX Bind Details:

 

From JavaFX Mailing Lists:

binding a function

question about bind-ing a function

All about binding

Functions and operations

 

 

Issues faced in bin with expressions:

1. For  a bind b + c if b or c changed we get a propertyChangeEvent. How do we extract which object (b or c) fired the propertyChangeEvent when both belong to the same Class so the propertyName is the same. I tried to getSource on the propertyChangeEvent but that returns ().

So the above is currently hard coded to always update value of b with the new value and then calculate the sum to update a.

 


 

 

Week 4: (02/14 – 02/20)

Hours: 10

 

To do:

  1. Animate background
  2. incorporate do and do later in sample application for a better example
  3. Detailed understanding of how function bind works
  4. write up of making Scala and Java work together (calling Java code from within a Scala project)
  5. set background color of JPanel

 

Note for report:

Consider adding dolater and do to a ThreadUtil class as statics rather than directly into Object (to make it more Scalable)

 

1 & 2: Animate background & do later:

Right now the animation works without bind. But the application uses the dolater & do control syntax created.

 

Code:

The Scala Version of the Weather Application: WeatherApplication [Scala Version].zip  *Updated*

Contains a Java Project YWS and the Scala project WeatherApplication. To use the Java code (YWS) in the Scala project I import both projects in Eclipse. Then right click on the Scala project (WeatherApplication) to select Build Path -> Configure Build Path in the projects tab and then add the Java project YWS to required projects on build path. And run.

 

The JavaFX version: available from within NetBeans: WeatherFX

 

3. Understanding bind:

 

Link to "question about bind-ing a function" posted on mailing list

 

From JavaFX mailing list functions and operations:

"Functions are designed to be used to factor bindings into reusable subroutines. Functions automatically track all their dependencies (inputs), not just their formal parameters but any variable or attribute that's referenced in the body. So there's no difference between this:

 

 var a = 2;

 var y = 3;

 var z = bind a + y + 10

 println(z); // prints 15

 y = 10;

 println(z); // prints 22

 

and this:

 

 var a = 2;

 var y = 3;

 function f(x) = a + y + x;

 var z = bind f(10);

 println(z); // prints 15

 y = 10;

 println(z); // prints 22

 

In both cases when I modify "y", the expression that is bound to "z" is incrementally reevaluated and then the new result is implicitly assigned to "z". It's almost as if the body of the function was lifted into the binding that called it. By contrast, Operations and Java methods are sequential processes which are "triggered" by changes to their inputs. When an input changes the whole process is carried out from the beginning. This means that they only depend on their formal parameters. Changes to variables or attributes referenced later in the body will not trigger the Operation to run again. Instead such references are to the "current" value of the variable or attribute at the point that the operation executed (which is the familiar behavior you're used to in Java). As a result if I use an operation instead of a function for the above I get different behavior (namely the behavior you'd expect in Java):

 

 var a = 2;

 var y = 3;

 operation f(x) { return a + y + x; }

 var z = bind f(10);

 println(z); // prints 15

 y = 10;

 println(z); // prints 15

 

Other Links:

Planet JFX: "Operation" vs "Function"

 


 

Week 3: (02/07 – 02/13)

Hours: 8

 

To do:

  1. clip image
  2. set size of JPanel
  3. set background color of JPanel  - no luck yet 
  4. do / do later keywords in Scala
  5. create sample application in Scala - In Progress
  6. animate background

 

Still working on creating the sample application in Scala, since we need that for creating the animation (using bind).

 

do / do later keywords in Scala:

Attempt to add the do later keyword to Scala has resulted in the following syntax:

 

this.dolater {

          //...

      }

 

I used Views and Companion Objects in Scala to add the dolater command.

Basically the dolater is a method in an Extended Object class. It will be available to any class by adding the following import statement:

import packageName.ExtendedObject._;

 

Issues: Cannot call dolater without "this." prefix. Looking into this to see if it is possible to do away with the prefix.

Also added a "do" like functionality using the same technique as above. Problem: do is already a keyword in Scala so will need to come up with a different keyword. Right now I am using a place holder called "dont" stands for "DO in New Thread":)

 

Posted question about the prefix on Scala-User group: Link to query

 

Update:

Changed a few things I learnt from the response I got on the mailing list and now I can call dolater without the "this" prefix:)

 

dolater {

          //...

 }

 

Source Code for do later & do: src[dolater].zip

 


 

 

Week 2: (01/31 – 02/06)

Hours: 7

 

This is what the application looks like currently in Java. No where as good as the original even for the text that is drawn. I wonder why the lines are not as smooth as the original (antialiasing? how to do that?)

no animations in here either:(

 

 

 

do later:

As for the first do later in the code below:

 

  do later {  // why???

        var yws:YWS;     //imported yahooWeatherService as YWS

        do {

            yws = new YWS(weatherCode, false); // second param is for isCelcius flag

            do later {

                var wm = WeatherModel{};

                wm.loadFromYWS(yws);

                weather.weatherModel = wm;

            }

        }

    }

 

removing it did not seem to have any effect. If the purpose was to push the whole block of code into the thread for execution later why not move the "do" outside. Why does the variable declaration part need to be in the event dispatch thread?

 

Update:

Figured out how to do antialiasing.. from http://java.sun.com/mailers/techtips/corejava/2006/tt0923.html

 

Now the application looks slightly better:)

 

 

 

 

Useful Links:

Affine Transform Tutorial: http://www.glyphic.com/transform/

 


 

 

Week 1: (01/24 – 01/30)

 

I was trying to implement the JavaFX's WeatherFX in Java. It uses do later and dur for animation.

 

 

Stuck right now in Graphics purgatory. The outer Frame was easily translated in Java but for each of the 3 weather blocks, they use a CompositeNode object. As expected no documentation exists on this and being new to Swing / Graphics2D I am not sure what would be a good Java alternative for this.

 

List of JavaFX classes for which I need to find a Java alterego:

  • CompositeNode
  • ImageView
  • Linear Gradient

Link to JavaFX API: https://openjfx.dev.java.net/nonav/api/index.html

 

Other than that tried to read anything I could find on the do/do later pair.

 

References for do & do later:

  • openjfx : "The JavaFX do statement allows you to execute a block of JavaFX code in a background thread while allowing the AWT Event Dispatch Thread to continue processing events, thereby preventing the UI from appearing to hang. Currently, this is implemented by using java.awt.EventQueue to pump events while the background thread is executing. Normally, all JavaFX code executes in the AWT Event Dispatch Thread. Only code contained in the body of a do statement is allowed to execute in another thread. Such code must only access Java objects (and those objects must handle their own thread synchronization, if necessary)."

     

  • OnJava: Introduction to JavaFX Script
  • A JavaFX christmas demo
  • Alarming Development: JavaFX: "There is language support for AWT’s threading model. FX operations run in the AWT event thread, except within the “do” construct, which spawns a synchronous activity in a background thread while still servicing AWT events. “do later” spawns asynchronous threads. Such background activity can only use Java objects, not FX objects, which seems a rather coarse constraint."
  • Reactions to JavaFX

"Threading:

1. Do and Do Later, and the whole multi-threaded thing are confusing. Many GUI's utilize call back methods

especially if you are using RMI. There should be a way to indicate that an operation is a call back and should be handled in a thread-safe way.

2. can't explicitly control threads

3. by default everything happens on the AWT event thread"

  • Chaotic Java: "Do / Do Later: Forget about threads. Or at least, forget about the java.lang.Thread class. Want to start a thread of your own, and not worry about creation of a Runnable, termination and the likes? do will do it for you. Just start a do tag, write some code in it (don’t forget to not access any AWT members!), and viola! And if you want to access some AWT members in it (something you would have done using the java.awt.EventQueue.invokeLater method), just open a do later!"

 

Some other readings:

 

Misc Links:

Groovy SwingBuilder and Bindings, a Hole to be Filled.

Chaotic Java: So, why not Groovy, really?

Scala Actors: A Short Tutorial

 


 

Background Work: (01/02 – 01/21)

 

1.  Worked on CS298 Proposal: CS298 - Proposal.pdf

 

2. Read up on Threads in Java:

Some changed have been made in JavaFX Syntax (to support compilation):  Converting to the New Syntax

 

Sample JavaFX application: WeatherFX

The above JavaFX application uses bind, dur and do later etc. so it would be a good sample application to implement in our DSLs.

 

References from CS298 report:

1. Odersky, M. And Zenger, M. 2005. Scalable component abstractions. odersky- scalable.pdf.

2. Henry, K. A crash overview of groovy.

3. Mernik, M., Heering, J., and Sloane, A. M. 2005. When and how to develop domain-specific languages. mernik - develop DSL.pdf

4. van Deursen, A., Klint, P., and Visser, J. 2000. Domain-specific languages: an annotated bibliography. deursen - DSL annotated.pdf

5. Odersky et al. A Tour of the Scala Programming Language. Available from

6. Writing domain specific languages. http://groovy.codehaus.org.

7. JavaFX Community. https://openjfx.dev.java.net/index.html

 

 

Comments (0)

You don't have permission to comment on this page.