Thursday, March 05, 2009

Darren on Flex: Flexins, Drag 'n' Drop Mixin now with Filtering

Recap of Version 0.2

If you quickly go back and play with the demo in my previous blog you'll find that you can't drag anything on the fourth, green quadrant. This is simply because it is not enabled by (the presence of) the mixin. You'll also find that both the Panel and TitleWindow can be dropped on to the nested purple region.

Introducing Drop Filtering

With version 0.3 you can now specify an inclusion filter that restricts what can and can't be dropped on to the corresponding drop-target. Have a play with this demo of version 0.3: You'll notice 2 differences:
  1. The fourth quadrant now accepts the nested purple region, but not the Panel nor the TitleWindow.
  2. The nested purple region now only accepts TitleWindows, but not Panels.
You can review the commit diff at GitHub to see the difference in how the mixin is declared at the code-level.

How It Works... In Brief

The dndFilter property is of type Array. It expects an array of types i.e. the types of thing to include/allow to be dropped e.g. TitleWindow. If the dndFilter property is not specified at all, or is later assigned null, then this is treated as include/allow all types, as in wildcard semantics. That's it really. Visit the DnDMixin's homepage for more details and references to source code.

What's Next

Using the matching of types as the filter criterion might be a bit crude for some. One might want to base the filter criteria on some domain rules or something more dynamic (perhaps determined at runtime) than the types used in the UI, which incidentally do not (necessarily) bare any significance on the interaction that they are being used to support. This kind-of thing can be implemented using a filter function; the user could specify whatever criteria they want, complex or simple. Watch this space!

Tuesday, March 03, 2009

Darren on Flex: Typed Literals, Paving The Way For Truly Embedded DSLs

What are they and what do they have to do with embedded DSLs?

After undertaking several Fit(Library) framework development projects and listening to various speakers on DSLs at SPA2008 (DSLs clearly being the hype for 2008, or at least at that conference), I started thinking about what DSLs exist and what support we have for them and what support we have for new ones. We are all familiar with the concept of primitive types and String literals? Having a Java background, things don't get much simpler than that. Those who are now feeling the urge to say something like, "Language X does not have primitive types, everything is an object..." please, pipe down, it doesn't really matter. The important thing to note is that there are types of variable you can define a value for without using the new operator (switch the keyword, operator, construct to suit your language of choice).

String Literal Abuse...

Strings are used to express eeeevverything... well, almost everything: SQL statements, XML fragments/documents and Regular Expressions. Even regular language expressions are made executable by the infamous eval('<string-embedded-language-expressions>') method, where supported. There maybe more types expressable by strings but we will focus on these for now, but if you know of any other interesting cases, I'd be interested to learn of them.

... Invites String Literal Pain!

The pain suffered as result of abusing string literals often goes unnoticed and can be derived, in part, from the fact that they are commonly used to embed full-blown languages, as in the highlighted cases for SQL and XML. While coding in this manner i.e. string-embedding, a benefit of formal languages becomes less obvious; these languages have their own set of rules i.e. their formal grammar, that apply as a matter of well-formedness. In fact we completely loose the benefit (real, potential or otherwise) of the well-formedness of these formal languages. In other words, the earliest possible point in time that one can determine for sure that some embedded SQL is correct, or in fact wrong, is when your code hits reality i.e. at run-time. For some poor sods (or fools, depending on your p.o.v.), that could be when an livid customer is ranting and raving about some dodgy transaction that takes too long or doesn't yield the... or when some XML document that is spat out chokes some down stream system, which always has teh effect of upsetting a lot of people. Let's consider escaping: How annoying does it get when one arrives (worse, has to write) at a ridiculously long regular expression string, let's say in Java. There are so many meta-characters that are frequently used to control the semantics of a RegExp that are escaped with a '\' (backslash) and thus must be doubly escaped in Java. In particular managing the namespace overlap for Java (symbols and characters) strings and embedded RegExp (escape-sequences), none more troublesome than '\n', which means insert new-line and match new-line, respectively, where the former takes precedence thus breaking the latter. The comprehensibility of escaped backslashes can be argued i.e. you know you are writing Java so you know what '\\\\' means, but what I can almost guarantee is that as the number of escaped-backslashes increases the more likely you are to go boss-eyed, recount them n times and ultimatly write the wrong RegExp before getting it right.

Ruby's Enhanced String Notation

Just as an aside, while we are discussing the use of strings, Ruby is quite extraordinary w.r.t. to how one instantiates strings. I have read that Ruby in someways is designed to mimic the Linux shell e.g. in its creation of strings: ' (single-quote) strings are different to " (double-quote) strings. Like in the Linux shell, using the double-quote notation expands referenced varibles; one can inject values from locally (lexically) scoped variables in the literal string value using Ruby's # and {} notation when embebbed in double-quoted strings. For example:
a = 2
puts "the variable a = #{a}"
This yields The variable a = 2.
# ...
puts 'the variable a = #{a}'
And this yields The variable a = \#{a}. There will be plenty programmers out there that are familiar with C's printf()-family of procedures, where it has features in many post-C languages. String.printf() was introduced in Java 5, leveraging the introduction of varargs. I was once on a Python project too and grew extremely fond of the overloaded % String operator; coming from Java, I was quite blown away by that back then.

Using Strings Responsibly Might Mean Not Using Them At All

So it seems that some language authors have felt the pain and reacted appropriatly by introducing real types for these things that might otherwise be embedded in strings. Here are a few cases that I know about; if I've missed any, which I am sure I have, please let me know.

RegExp - JavaScript, ActionScript, Ruby, Python

The common syntax for these languages, with the exception of Python, is to use the '/' (forward-slash) as the RegExp delimiter, in exactly the same way single-quotes or double-quotes are used to delimit strings. Foe example:
/regular expression/
JavaScript and ActionScript behave almost the same (in my experience, correct me if I am wrong) which suggests to me this maybe a feature ECMAScript; I am not clued up on ECMAScript directly, so I can only speculate. By 'behave' I mean in reference to the flags you can specify to alter the way the RegExp processes the target string. For example:
/regular expression/gimsx;

XML Notation - ActionScript

ActionScript overloads the < and > operators to be used as XML delimiters(obvious choice, no?).
var tagname:String = "item"; 
var attributename:String = "id"; 
var attributevalue:String = "5"; 
var content:String = "Chicken"; 
var x:XML = <{tagname} {attributename}={attributevalue}>{content}</{tagname}>; 
trace(x.toXMLString())
    // Output: Chicken
This was borrowed from the Flex 3 Developer Guide. As you can see, you can reference variables inline to construct any part of the XML fragment.

Binary & Bit Notation - Erlang

Erlang has the tidiest notation for bits and bytes I've ever seen... excuse me if this a blatant show of ignorance:
Binary = <<98,105,110,97,114,121>>.
Each comma-separated value represents a byte and so must fall in the inclusive range 0-255. This example shows a 6-byte binary.
Binary = <<"binary">>.
This happens to be valid Erlang as the patterns match. This second example shows a 6-byte binary represented as a string (ironically) as all byte values represent printable ASCII character codes. The first example is matched as the values specified are the corresponding ASCII character codes for binary. I believe Erlang will prefer to display the string form when possible.
B = 98.
I = 105.
N = 110.
A = 97.
R = 114.
Y = 121.
Binary = <<B,I,N,A,R,Y>>.
Erlang also allows you to reference variables/constants/terms (whatever they are called in Erlang) inline as well. The bit notation is only a minor variation on this theme.
MangledBinary = <<B:4,I:4,N:4,A:4,R:4,Y:4>>.
The :4 says to take the 4 least significant bits, in this case chopping each byte in half, which incidentally still yields a printable binary, but now only 3-bytes long (<<")รก)">>)

So The Part Relevant to DSLs

LINQ-to-SQL - C#

C#'s LINQ-to-SQL, coupled with LINQ Expression (comprehension) syntax, is the closest thing I've seen to an embedded DSL that is strongly typed. That is, you can express a literal and assign it inline to a specialized type, relevant to its domain of use.
enum Food { Fruit, Veg }

var fruitAndVeg = {
    new { Type=Fruit, Name="Apple" },
    new { Type=Fruit, Name="Banana" },
    new { Type=Fruit, Name="Cherry" },
    new { Type=Veg, Name="Artichoke" },
    new { Type=Veg, Name="Asparagus" },
    new { Type=Veg, Name="Broccoli" },
    new { Type=Veg, Name="Carrot" }
};

from food in fruitAndVeg
where food.Type == Veg
where food.Name.StartsWith ("A")
select food.Name
This yields Artichoke and Asparagus. While this is not SQL-92 (nor does it actually link to SQL [read: database, although it can]), you can clearly see the resemblance and can therefore immediately identify the comprehension syntax as a query language.

Make the Tools Do The Work!

For those that appreciate type-safety (i.e. those that use [and like] strongly-type languages), compile-time support for these typed literals would come as standard. Typed literals would also permit enhanced IDE support: literal validation; syntax highlighting; code completion (if appropriate). These are not ideas of my own, rather a very brief account of my experience with Visual Studio and LINQ with its comprehension syntax. The problem is the implementation for this is quite involved and limited to querying IEnumerable type things. AFAIK, there is no general mechanism for providing such a feature, a feature which essentially allows you to extend the syntax of you embedding language e.g. C#. Many text editors provide a mechanism to specify information about your language, so that it can usefully provide syntax highlighting. However what we are getting at with typed literals goes beyond this and really needs to extend the compiler and/or the IDE; I envisage some sort of plugin, that either or both compiler and IDE can understand, which has some sort of Type -> Expression syntax mapping. But once we've done all this, how far away would we be from the effort to do all this using Bison, Flex, JavaCC, YACC or whatever other parser/compile-generator? I'm willing to bet it would be a similar effort, but what we gain by embedding/inlining, aside form the features and support that the IDE would typically provide, is:
  • The opportunity for value injection, as per Ruby strings and ActionScript XML fragments.
  • The opportunity to simplify tasks that are typically more painful or less compact in the main language e.g. C# and LINQ.
  • The oppurtunity to do all the above where you need it, in the code i.e. not in some external file, thus incurring no maintenance penalty.
Well, that's about all I have to say/muse on the subject. With closures and dynamic constructs becoming more popular, I wait to see what other developments materialise next in the language space. Cheers.

Wednesday, February 25, 2009

Darren on Flex: Flexins, Drag 'n' Drop Mixin

I present to you the Drag'n'Drop Mixin

I've managed to embed an instance of my Drag'n'Drop showcase app here, but I cannot seem to influence the size of it. I recommend you visit the mixin's demo page here For those of you who are not interested in my posturing and story-telling, you can review the source for this application here at GitHub.

So how does it work?

You simply include <dnd:DnDMixin /> as a child of any container type and this enables that container as a drop target and any child as a drag source. It's as simple as that.

That's how you use it... How does it work?

Ok, here's an excerpt from the project's README file:
These mixins are designed to be used in MXML, leveraging components' event-driven life-cylce. They should be used as 'drop-ins', similar to usage model for inline item-renderers.
In addition to this, I exploit the Container.rawChildren property, due to the fact that this mixin is a content-less UI component and should not interfere with content-full UI components. When an application is loaded all declared UI components are processed through an event-driven life-cycle. The life-cycle events the dnd-mixin is interested in are:
FlexEvent.ADD:
Registration happens in the constructor, the earliest possible opportunity at the object level. More significantly, registration occurs before this (typically, one time) event is dispatched. The handler for this event deregisters from this same event, removes the dnd-mixin from the container and then adds it back but to the rawChildren. The handler then registers interest in the DragEvent.DRAG_ENTER, DragEvent.DRAG_OVER, DragEvent.DRAG_EXIT and DragEvent.DRAG_DROP events. The corresponding handlers implement the necessary mechanics to provide drag'n'drop functionality; I refer you to the source code as it's pretty straight forward and not that interesting, especially if you've implemented D'n'D yourself before. The handler also registers interest in the following events:
ChildExistenceChangedEvent.CHILD_ADD:
Through this event the dnd-mixin is notified whenever a component is added to the parent container. The addition of a child as far as the dnd-mixin is concerned, indicates a successful drag'n'drop operation to this parent container. Thus this event signals this dnd-mixin instance to take control of the D'n'D processing for this child component (to which a reference can be obtained from the event object). This handler registers interest in the following events on each managed child component:
MouseEvent.MOUSE_MOVE:
The registered handler simply detects the drag gesture (initiation) and delegates the operation to the DragManager.
DragEvent.DRAG_COMPLETE:
The registered handler basically just adds the dragged component to the new container, which implicitly removes it from its current/previous parent. Doing so dispatches the ChildExistenceChangedEvents, as explained here.
ChildExistenceChangedEvent.CHILD_REMOVE:
Similar to CHILD_ADD, this CHILD_REMOVE event notifies the dnd-mixin whenever a component is removed from the parent container. The removal of a child likewise indicates a successful drag'n'drop operation away from this parent container. Hence this event signals this dnd-mixin instance to relinquish control for D'n'D processing. This is explicit and is implemented through deregistering interest in the MouseEvent.MOUSE_MOVE and DragEvent.DRAG_COMPLETE events.
And that's all there is to it. Try it out above or here. As you'll see there is nothing spectacular about the end result; it's functional. The benefit is the improved readability in your code gained from the clean separation, reduced duplication and declarative style the mixins adopt. While I declare this dnd-mixin is fully functional I don't presume it will suit the needs of all drag'n'drop use cases. I have also observed a bug in the rendering of dragged items that were previously clipped by the parent's right edge. I think I recall a colleague encountering this problem (and solving it) so I'll ask her about it at the next available chance.

What's next?

Drag source filtering. This will support the use case if you want to allow some types of things to be dropped, but not others. The implementation for this is actually complete (see here); a blog will follow soon. If you want to use it, you know where the source/binaries are. Enjoy

Monday, February 16, 2009

How To: Use Google Code as a Maven Repository

While working on my new Flexins Project and blogging accordingly, I decided to explore using Maven and Flex-Mojos to build the libraries and showcase applications. I have a local install of Nexus, where I hide away most of the complexity that would otherwise be in my settings.xml files. I typically deploy to this repo for my own benefit where I might chose to make it public in the future so I can work on stuff (drag in deps) from anywhere. However, it is not a viable option if my or your aim is to truly make one's binaries publicly available (saving the curious the trouble of a compiling source). Some how I stumbled on to Don Brown's Weblog, where he talks about turning a Google Code project, that is the site itself with its SVN, into a Maven repository. I have not yet done this myself, but the details are here. Cheers

How To: Demo Flex Apps On Blogger or Google Sites

While working on my new Flexins Project and blogging accordingly, I discovered that you can embed you Flex application into your page quite easily. Here are the rawest of raw instructions on how to do it.
Flex on Blogger
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
    id="Main" width="100%" height="100%"
    codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
    <param name="movie" value="https://sites.google.com/site/flexinsproject/flexins-catalog/dndmixin/dnd-mixin-demo-0.2.swf?attredirects=0" />
    <param name="quality" value="high" />
    <param name="bgcolor" value="#869ca7" />
    <param name="allowScriptAccess" value="sameDomain" />
    <embed src="https://sites.google.com/site/flexinsproject/flexins-catalog/dndmixin/dnd-mixin-demo-0.2.swf?attredirects=0" quality="high" bgcolor="#869ca7"
        width="100%" height="100%" name="Main" align="middle"
        play="true"
        loop="false"
        quality="high"
        allowScriptAccess="sameDomain"
        type="application/x-shockwave-flash"
        pluginspage="http://www.adobe.com/go/getflashplayer">
    </embed>
</object>
UPDATE, 27.02.2009: It seems Blogger ignores the <object>...</object> tags, so the nested <embed>...</embed> is sufficient. While I would not normally recommend removing robustness... parts of the <object>...</object> code was showing in my blog, so I got rid of it altogether. Also make sure the remaining <embed>...</embed> is format correctly i.e. no erroneous newlines; this was causing some of the parameters e.g. width and height, to be ignored.
Flex on Google Sites
<Module>
    <ModulePrefs title="__UP_title__"
    width="600"
    height="450"
    scrolling="true"
    author="Darren Bishop"
    author_email="dbishop81@gmail.com"
    description="GG to help embed Flex applications into Blogger or Google Sites">
        <Require feature="flash" />
    </ModulePrefs>
    <UserPref name="title" display_name="Title" default_value="Flex Application Embedder" />
    <UserPref name="swf_url" display_name="SW URL" />
    <Content type="html">
    <![CDATA[
    <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
        id="Main" width="100%" height="100%"
        codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
        <param name="movie" value="__UP_swf_url__" />
        <param name="quality" value="high" />
        <param name="bgcolor" value="#869ca7" />
        <param name="allowScriptAccess" value="sameDomain" />
        <embed src="__UP_swf_url__" quality="high" bgcolor="#869ca7"
            width="100%" height="100%" name="Main" align="middle"
            play="true"
            loop="false"
            quality="high"
            allowScriptAccess="sameDomain"
            type="application/x-shockwave-flash"
            pluginspage="http://www.adobe.com/go/getflashplayer">
        </embed>
    </object>
    ]]>
    </Content>
</Module>
Wordpress
Sorry, you are on your own. Somehow, I don't think it would be that hard to do. If you can't figure it out, feel free to ask for help. Cheers

Darren on Flex: Flexins Project Launch

I am proud to announce the launch of the Flexins Project!

This project is the result of some work I started several months ago. I started looking into ways to leverage Flex's declarative MXML to add extra behaviour to applications (or parts therein), using mixins. The project's homepage is over at Flexins Project @ Google Sites. It's in flux at the moment as I'm still getting my bearings in administering the site; please bare with me on that one. The source code is hosted at Flexins Project @ Github. I decided to give Git a spin on this project as it appears to be the emerging SCM of choice for open/public projects.

So what's it all about?

We are all familiar with includes, which work for both .as and .mxml files. This supports the code-behind style, which is a very useful separation mechanism when dealing with complex UI logic or copious event handler code. However, as a mechanism it is pretty stupid, relying only on assumption that internal dependencies (e.g. property existence) are satisfied. Of course, one can declare interfaces in .mxml and implement them in .as code-behind; I suppose this is the standard approach. The syntactical interface declaration (think: compiler) here also serves to declare (the availability of) any relevant behaviour (think: application feature) [Mixins are not necessarily or typically used this way, to add application features, but it is nonetheless the theme for my initial work]. However, firstly, the interface has to be defined and secondly the include is a waste full source include [Ok, it's debatable the real impact of this on binary size and performance blah blah blah... but from a idealist pov... it's not ideal]. I have found with this new approach to implementing mixins, you can achieve complete separation of responsibility e.g. keeping whatever it is your components are primarily supposed to do, from the behaviour implementation of the mixin. The state required for the mixin to function can be managed internally, negating the need for any interface definitions, declarations or implementations. And because the mixin is not used via a source include, there is only one compiled instance of the code in the binary. Application of the mixin is achieved through normal object-instantiation, not source inclusion everywhere the mixin behaviour is required. Another advantage of this new approach is that you do not need access to any source code; you do not need to re-write or extend some existing class in order to bolt on your desired behaviour. I will blog soon on how all this can be achieved. For now, have a look at an example of what the end result looks like; check out my Drag'n'Drop Mixin showcase. Cheers, q(^_^)p

Friday, February 13, 2009

Darren on Flex: Does Flex Have Serial Version Ids?

... And if it does, why don't they use them?

I came across this weird bug (see below) ages ago, that is ~6-8months, when trying to implement some custom drag'n'drop behaviour in a modular application. I had no flipping clue what it was going on about, threw my hands up in disgust and frustration and just shelved the whole thing (actually had to go earn my pay). I just recently came back to the drag'n'drop thing, developing in a singular app style. On completing what I set out to achieve (well, making satisfactory progress, [blog to follow]), I decided to revisit this bug. I found a work-around on Adobe's JIRA site but was confused by all the chatter. I Googled a bit more and found Greg Jessup's blog, where he posted the workaround some months earlier. With Greg's clear post, it was easy for me to rationalise this bug, such that I no-longer believe it is a bug... or rather not the WTF-kind. I categorize it now as a matter of some runtime-binary-compatibility issue, serializationy thingy. Hence why loading the classes in the Application (thus sharing the binary amongst the modules) solves the problem. I believe in the Java world, this is the kind of thing a serial-version-id is used to guard against, no? Anyway, cheers Greg.