Tuesday, March 25, 2008

Lines and Tigers: Customizing ComboBox

In the Top Drawer application that I posted recently, wanted a custom combobox that showed the line widths as graphical lines, not as text descriptions. Text is a pale substitute for graphics, don't you think? Think how much more boring Hamlet would have been if it had just been a bunch of words. Or Anna Karenina. Or think how exciting and immersive everey episode of Sponge Bob Square Pants is, all because it's drawn in such meticulous detail.

I got part-way to my goal in Top Drawer, with the drop-down list showing lines instead of labels. But the main combobox button still showed a text label, instead, "width 1":

Partial Achievement

Now that I finally finished the exposee on Top Drawer, it's time to revisit the combobox and see if we can spruce it up a bit.

Take I: Default ComboBox with Boring Text Labels

First, let's see the default we'd get if we just coded up a normal ComboBox to handle line widths. In this case, I want to assign a width between 1 and 5 to my lines; I create a ComboBox with a list of objects that have width attributes.

    <mx:ComboBox id="lineWidth" x="10" y="189" width="87"
            editable="false">
        <mx:ArrayCollection>
            <mx:Object width="1" label="width 1"/>
            <mx:Object width="2" label="width 2"/>
            <mx:Object width="3" label="width 3"/>
            <mx:Object width="4" label="width 4"/>
            <mx:Object width="5" label="width 5"/>
        </mx:ArrayCollection>
    </mx:ComboBox>

The width attribute is used as a source in a databinding expression for the ArtCanvas object, where it sets the current stroke width based on the width value of the currently selected item in the ComboBox.

    <comps:ArtCanvas id="canvas" 
            drawingColor="{drawingColorChooser.selectedColor}"
        strokeWidth="{lineWidth.selectedItem.width}"
        left="105" top="10" right="10" bottom="10"/>

This ComboBox does the job, allowing the user to set the width of the lines interactively through the GUI with the small amount of code above to hook it up. But the user experience is not quite what a graphics geek might want:

Default Line Width ComboBox

Take II: Graphics in the Drop-Down

Now we come to the version that I developed in the Top Drawer application; I attacked the drop-down list to make the elements in that list graphical instead of the boring text-based "width x" versions above.

To do this entails the Flex notion of an "item renderer." Item renderers are used by the list-based components, such as ComboBox, allowing applications to specify objects which will perform custom rendering of each item in the list. Specifying the item renderer in MXML is done by simply naming the class that will be used to render the items. In our application, we use the class LineWidthRenderer, which is specified in the same mx:ComboBox tag as above:

    <mx:ComboBox id="lineWidth" x="10" y="189" width="87"
            itemRenderer="components.LineWidthRenderer" editable="false">
        <mx:ArrayCollection>
            <mx:Object width="1" label="width 1"/>
            <mx:Object width="2" label="width 2"/>
            <mx:Object width="3" label="width 3"/>
            <mx:Object width="4" label="width 4"/>
            <mx:Object width="5" label="width 5"/>
        </mx:ArrayCollection>
    </mx:ComboBox>

The code in our LineWidthRenderer class (written in ActionScript3) that handles rendering each item is in the standard setter for the data field; this method will be called by Flex whenever it needs to display a particular item. In our case, we know that each data item will contain a width attribute, so we check the value of that attribute and perform our rendering appropriately:

        override public function set data(value:Object):void
        {
            _data = value;
            renderLine(graphics, 5, 50, _data.width);
        }

        public static function renderLine(graphics:Graphics, 
                x0:int, x1:int, lineWidth:int)
        {
            graphics.clear();
            graphics.lineStyle(lineWidth, 0x000000);
            graphics.moveTo(x0, 10);
            graphics.lineTo(x1, 10);
        }

Here, our data setter is calling the renderLine() method in the same class, which takes a Graphics object, endpoints for the line, and a line width value and draws an appropriate line into the display list of the graphics object. The result is much better than before:

Better Line Width Rendering

Finally, we're rendering our line width choices as actual lines. The user can see visual representations of what they will get in the shapes they draw and can make a better selection between the UI choices. Besides, it just looks cooler.

But it's still not quite good enough; what's with that "width 1" label in the ComboBox's button?

Take III: ComboBox Nerdvana

Not only does the button of the ComboBox display text when the drop-down list is nicely graphical below it; the closed ComboBox displays only that text label. Gone is all of the lovely wide-line artwork that we slaved over for the drop-down list.

The final step, then, is to customize our ComboBox further to provide a graphical representation of the currently selected item in the top-level button.

This turns out to be a simple problem to solve. So simple, in fact, that I felt silly that I didn't solve it before I shipped the initial version of the application. But what would life be like if all our TODOs were impossible? Here's the solution:; we need a subclass of ComboBox with customized rendering for the button.

We create a subclass of ComboBox in ActionScript3, LineWidthComboBox, as follows:

package components
{
import mx.controls.ComboBox;

public class LineWidthComboBox extends ComboBox
{
    override protected function updateDisplayList(
            unscaledWidth:Number, unscaledHeight:Number):void
    {
        LineWidthRenderer.renderLine(graphics, 10, 55, selectedItem.width);
    }
}
}

Not very complex, is it? The subclass exists to override the single method updateDisplayList(), which is where a component creates the rendering for its contents. In this case, we call the same static renderLine() method as we used before in our LineWidthRenderer class to draw a graphical representation of the currently-selected line width into our component. But apparently this isn't enough, since this is what results:

Where'd the Buttoin Go?

The problem is that we're not bothering to render the actual button object of our ComboBox, so the typical button background that we expect is not there. Since we're lazy and don't want to do all of that work in our code, we can ask the superclass to take care of the rendering for this component for us by simply calling the superclass' updateDisplayList() method first, and then performing our custom rendering on top of it:

    override protected function updateDisplayList(
                 unscaledWidth:Number, unscaledHeight:Number):void
    {
        super.updateDisplayList(unscaledWidth, unscaledHeight);
        LineWidthRenderer.renderLine(graphics, 10, 55, selectedItem.width);
    }

This is better, but still not quite what we want:

Label and Line

Now we have our button and a graphical line, but we also have the default text label which our superclass is kindly drawing for us. We want the superclass to draw the button decoration, but we don't want it to draw the text label. How can we fix this?

There are probably several ways to do this, but one easy way is to simply supply a label that won't get drawn.

By default, ComboBox looks for a "label" attribute in each item in the list and renders the string associated with that attribute. In our original mxml code for the ComboBox, we supplied items with both a width property (which supplies the information we use to actually determine the stroke width) and a label property, as follows:

        <mx:ArrayCollection>
            <mx:Object width="1" label="width 1"/>
            <mx:Object width="2" label="width 2"/>
            <mx:Object width="3" label="width 3"/>
            <mx:Object width="4" label="width 4"/>
            <mx:Object width="5" label="width 5"/>
        </mx:ArrayCollection>

We could simply remove the label:

        <mx:ArrayCollection>
            <mx:Object width="1"/>
            <mx:Object width="2"/>
            <mx:Object width="3"/>
            <mx:Object width="4"/>
            <mx:Object width="5"/>
        </mx:ArrayCollection>

but then we wouldget the following instead:

Bad Label and Line

The problem this time is that ComboBox is determined to find a text label, or if it doesn't find one it will create one of its own, which is obviously not what we want.

What our button really needs is an empty label; so let's provide it:

        <mx:ArrayCollection>
            <mx:Object width="1" label=""/>
            <mx:Object width="2" label=""/>
            <mx:Object width="3" label=""/>
            <mx:Object width="4" label=""/>
            <mx:Object width="5" label=""/>
        </mx:ArrayCollection>

With this change, we've pointed the ComboBox to label properties that it can use, but when our superclass goes to display the text, nothing will happen - which is just what we want:

Just the Line

Finally, with our custom ComboBox subclass, our reliance on the superclass rendering facilities for the button basics, and our fabulous new empty labels, in addition to our previous use of a custom item renderer for the drop-down list, we have what we set out to achieve: a completely graphical line-width control:

Completely Graphical Line Width Control

Here are the update sources Top Drawer. Stay tuned for more improvements in upcoming posts.

Wednesday, March 19, 2008

Top Drawer, Part III: Taking Shape

Today, we finish our walkthrough of the Top Drawer application.

But first:

Q: Why did the Shape leave the canvas?
A: It had had its fill.

Q: What do they call boxing matches between vector-art objects?
A: Stick-fighting.

Q: Why don't Shape parents allow their kids to watch stick fighting?
A: Too much graphic violence.

Q: How are Shapes kept informed?
A: First, they're given an outline, then they're filled in completely.

Q: Why was the drawing application so tired?
A: For every four lines drawn, it was a complete rect.

Q: What do these jokes have in common with inidividual vectors drawn wth TopDrawer?
A: They're both one-liners with little point.

In Part I, we went over the code for TopDrawer.mxml, which contained the GUI layer for our drawing application. In Part II, we saw the code for ArtCanvas.as, which handles the interaction and most of the logic of the application. Now, in Part III, we will see the code for creating and rendering the actual drawing shapes.

More importantly, in this installment we'll actually finish the series (at least until a later post where I'll go over some design improvements).

To refresh your memory, here's the amazing drawing application again:

Helper Classes

Before I get to the [he]art of this article (the shape classes), I wanted to cover a couple of other small classes to show how they do their thing.

LineWidthRenderer.as

This class is repsonsible for rendering each item in the drop-down menu on the line-width combobox in the main GUI. Instead of the typical text-based combobox, I wanted to have a graphical representation of the lines, like what you see in most drawing applications. An "item renderer" is a class that can be installed on many of the Flex list-based components to render each individual item in those components. It does this by receiving calls to set the data member of the item and producing an appropriate rendering. In our data-setting method, we simply take the information embedded in that data item (which includes the width field, set in TopDrawer.mxml) and create a display list for our LineWidthRenderer class which will draw a line of that width:

        override public function set data(value:Object):void
        {
            _data = value;
            var lineWidth:int = _data.width;
            graphics.clear();
            graphics.lineStyle(lineWidth, 0x000000);
            graphics.moveTo(5, 10);
            graphics.lineTo(45, 10);
        }

[To make this even better, I'd like to enhance the combobox so that the button that's displayed also has a graphical line and not the text label it has now. Look for that improvement in a future installment.]

DrawingShapeIcon.as

DrawingShapeIcon is a simple subclass of Image which has the added functionality of displaying a red highlight border when it is the currently selected drawing mode. We saw in Part I how the DrawingShapeIcon objects get created in TopDrawer.mxml added as event listeners when the drawing mode changes. Now we'll see how the highlight border is implemented.

The drawing mode assigned to each DrawingShapeIcon is set by assigning the mode variable:

        public var mode:int;

The border is a static object (we only need one for the application since all icons can reuse the same one):

        private static var highlightBorder:Shape;

Finally, the modeChanged() method is called when the DrawingModeEvent is propogated. This method creates highlightBorder if it does not yet exist and then adds the border to the instance whose mode matches the new mode that's been set. Note that adding highlightBorder as a child on to one icon will automatically remove it as a child from any other icon; we do not need to bother calling removeChild() for the previously-highlighted icon.

        public function modeChanged(event:DrawingModeEvent):void
        {
            if (!highlightBorder) {
                highlightBorder = new Shape();
                highlightBorder.graphics.lineStyle(5, 0xff0000, .8);
                highlightBorder.graphics.drawRect(0, 0, width, height);
            }
            if (event.mode == mode) {
                addChild(highlightBorder);
            }
        }

ArtShape.as

Now, we're into the meat of this article: the drawing shapes. All of the shapes are subclasses of ArtShape, which provides the public API for shape creation and performs some common functionality that is used by most subclasses. ArtShape is a subclass of the flash class Shape, and ArtCanvas uses capabilities of that class, such as being able to add it as a child of the canvas and being able to detect whether a given point on the canvas hits the object (we saw both of these capabilities exercised in Part II, when we explored ArtCanvas).

Properties

Each shape keeps track of its start and end points, which comprise the points where the mouse first started dragging and the last drag location of the mouse. These are currently only used during object creation, when endPoint may change with every mouse drag. Once a drawing is complete, the rendering of a shape is not changed so we do not actually need these points again. A more complete drawing program might allow these points to be edited after the fact, in which case caching them would be useful.

        protected var startPoint:Point;
        protected var endPoint:Point;

The strokeWidth and color properties are set at construction time and cached for later use when creating the display list for the shape. Note that strokeWidth is only used in the non-filled primitives (a more exact class hierarchy might differ slightly to avoid caching an instance variable at this level that is not used by some subclasses):

        protected var strokeWidth:int;
        protected var color:uint;

The start() and drag() methods are called upon first mouse-down and each drag operation, respectively. The start() method merely caches the current start and end points, whereas the drag() operation, in addition to setting a new end value, also calls renderShape(), which is where all subclasses (except Scribble, which we will see later) create the display list which renders the shape:

        public function start(value:Point):void
        {
            startPoint = value;
            endPoint = value;
        }
 
        public function drag(value:Point):void
        {
            endPoint = value;
            renderShape();
        }

The addPoint() method is called on mouse-up. Once again, the new endPoint is cached and renderShape() is called. We also return a value that indicates whether this shape is complete. The reason for this is that a possible future feature would allow drawing of complex primitives such as curves, which might take several mouse clicks/drags to create a single shape, instead of the single drag operation that the current shapes take. This return value would tell ArtCanvas whether to record the shape as finished or to continue in a mode of adding information to the current shape. It's not a part of the current application, but I added this little bit of infrastructure in case I added it later.

        public function addPoint(value:Point):Boolean
        {
            endPoint = value;
            renderShape();
            return true;
        }

The validShape() method is called by ArtCanvas after the shape is complete to determine whether this shape should actually be added to the list of shapes on the canvas or whether it should be deleted. The simple check in ArtShape simply checks whether the start and end points are the same. Subclasses may choose to have more complex check (which is the case in the Scribble shape).

        public function validShape():Boolean
        {
            if (endPoint.equals(startPoint))
            {
                return false;
            }
            return true;
        }

renderShape() is called during object creation to create a rendering of the shape. Most subclasses (except Scribble) override this method and create a display list appropriately.

        protected function renderShape():void {}

getSelectionShape() is called by ArtCanvas to retrieve a new shape that will be used to show that a given ArtShape is selected. It is common to show filled-rectangle handles on the corners of the bounding box of a shape, so that's what this superclass implements. Some subclasses (such as Line) may choose to override this method and return a different selection shape.

        public function getSelectionShape():Shape
        {
            var shape:Shape = new Shape();
            var bounds:Rectangle = getBounds(parent);
            shape.graphics.beginFill(0);
            shape.graphics.drawRect(
                    bounds.left - HANDLE_SIZE_HALF, 
                    bounds.top - HANDLE_SIZE_HALF,
                    HANDLE_SIZE, HANDLE_SIZE);
            shape.graphics.drawRect(
                    bounds.left - HANDLE_SIZE_HALF, 
                    bounds.bottom - HANDLE_SIZE_HALF,
                    HANDLE_SIZE, HANDLE_SIZE);
            shape.graphics.drawRect(
                    bounds.right - HANDLE_SIZE_HALF, 
                    bounds.bottom - HANDLE_SIZE_HALF,
                    HANDLE_SIZE, HANDLE_SIZE);
            shape.graphics.drawRect(
                    bounds.right - HANDLE_SIZE_HALF, 
                    bounds.top - HANDLE_SIZE_HALF,
                    HANDLE_SIZE, HANDLE_SIZE);
            shape.graphics.endFill();
            return shape;
        }

Now, let's take a look at the ways that some of the subclasses build upon the capabilities of ArtShape.

ArtShape Subclasses

In Line.as, we override both the renderShape() method and the getSelectionShape() method. getSelectionShape() is not terribly interesting; it simply draws two filled rectangles at the endpoints of the line. But renderShape() is where we build the display list to render the line with the current endpoints:

        override protected function renderShape():void
        {
            graphics.clear();
            graphics.lineStyle(strokeWidth, color);
            graphics.moveTo(startPoint.x, startPoint.y);
            graphics.lineTo(endPoint.x, endPoint.y);
        }

Ellipse is even simpler, since it does not override getSelectionShape() (it uses the ArtShape implementation to draw the selection handles on the bounding box corners). It has one additional item in the constructor, to determine whether the ellipse is filled or not:

        public function Ellipse(width:int, color:uint, filled:Boolean)
        {
            super(width, color);
            this.filled = filled;
        }

Ellipse (and the other filled shape subclass, Rect) uses this filled variable to determine whether to fill or stroke the shape in the renderShape() method:

        override protected function renderShape():void
        {
            graphics.clear();
            if (filled) {
                graphics.beginFill(color);
            } else {
                graphics.lineStyle(strokeWidth, color);
            }
            graphics.drawEllipse(startPoint.x, startPoint.y,
                    endPoint.x - startPoint.x, endPoint.y - startPoint.y);
        }

Most of the shapes are similarly simple, depending on ArtShape for most functionality. The exception, as you might have guessed from the plethora of parenthetical mentions of it above, is Scribble.

Scribble.as

This shape is different than the others because it does not simply draw itself between the start and end points of the mouse drag, but rather adds a new line segment for every new mouse position during the drag.To do this, it creates the display list dynamically, starting it at mouse-down and adding to it during every drag operation. This means that there is more happening during the actual point-adding methods, but that renderShape() is noop'd (because the display list has already been created).

Here is the start() method, where we begin the display list based on the first mouse location:

        override public function start(value:Point):void
        {
            points.addItem(value);
            graphics.lineStyle(strokeWidth, color);
            graphics.moveTo(value.x, value.y);
        }

Note that we also cache, here and in the other dragging methods, the intermediate points in our internal points object; this is for later use in detecting whether a shape is valid. It would also be useful if we allowed advanced editing of the individual points of a Scribble object. But that's a feature for another day...

Subsequent calls to drag() and the final addPoint() method add lines to the display list, which are drawn from the previous point in the display list (either the first moveTo() point for a new line or the point in the last lineTo() operation):

        override public function drag(value:Point):void
        {
            points.addItem(value);
            graphics.lineTo(value.x, value.y);
        }

Scribble's other tweak on ArtShape is an override of validShape(). It's not good enough to detect whether the start and end points are coincident, as ArtShape does; we need to walk the entire list of our cached points in a Scribble to see whether they are all the same:

        override public function validShape():Boolean
        {
            var firstPoint:Point = Point(points.getItemAt(0));
            for (var i:int = 1; i < points.length; ++i)
            {
                if (!firstPoint.equals(Point(points.getItemAt(i)))) {
                    return true;
                }
            }
            return false;
        }

Finally!

That's it. The whole application. We saw bits of nearly every class in the source base, only skipping those too simple to be interesting or where the functionality was similar to code already shown. But I encourage you to download the source tree, look at all of the files, build it, run it, and play with it. And if you discover any problems, let me know; I'll fix them and update the project. (This doesn't include major feature updates; I purposely kept the project small so that I could easily show various features of Flex, Flash, ActionScript3, and MXML. Sure, I'd love to write a 3D modeling tool, but that's not happening in TopDrawer).

A future installment will address some of the design aspects that I called out along the way. The current code is not bad, but there are definitely some improvements that could make the code and application just a tad nicer.

I look forward to writing more of these kinds of articles. I still have a big learning curve ahead of me with the full stack of Flash, Flex, and AIR, and I'll be writing applications to teach myself how things work. And I'll be posting that code here so that you can learn right along with me.


Friday, March 14, 2008

Top Drawer, Part II

Q: Why do graphics geeks write vector art applications? A: We're just drawn to it.

Q: Why couldn't the blank canvas get a date? A: He didn't have any good lines.

Q: Why did the rectangle go to the hospital? A: Because it had a stroke.

Q: Why is TopDrawer sluggish when the canvas is empty? A: Because it's out of Shapes.

Welcome to the second installment of TopDrawer, a series in which I describe how a simple vector-drawing application was implemented in Flex.

Here's the application again, in case you missed it last time:

In Part I, we went through the GUI layer of the application, stepping through most of the code in TopDrawer.mxml. This, time, we'll take a look at the ActionScript3 class ArtCanvas.as, which is where most of the application logic for TopDrawer is found, including the mouse input that handles creating and editing the shapes on the canvas.

ArtCanvas.as

The source code for this file can be found here; you may find it helpful to download it and view it in a separate window, as I'll only be showing snippets from the file below as we walk through it.

ArtCanvas is a custom component, a subclass of UIComponent, which is the base class of all Flex components (and the class which you might usually want to subclass for custom components of your own if you don't need any of the specific capabilities of the existing subclasses). The ArtCanvas component is the visual area in which the shapes are drawn and edited. It handles both the display of the objects (through other classes that we'll see later) as well as the mouse and keyboard events that drive the creation and manipulation of the shapes.

Architecture

Functionality

The functionality of ArtCanvas is fairly simple:

  • Properties: The properties of ArtCanvas determine the type of shape being drawn, the properties of that shape, and the gridSnap properties that affect how drawing occurs.
  • Creation: Through handling mouse events, ArtCanvas creates shapes as the user drags the mouse around on the canvas.
  • Selection: Mouse events also result in selecting and deselecting objects for editing.
  • Editing: This is perhaps an optimistic term for what the user can do with the shapes in this very simplistic application, but selected shapes can be either moved (through mouse dragging) or deleted (through keyboard events or clicking on the Clear button).
  • Rendering: The canvas has a simple white background that ArtCanvas creates with a small display list. All other rendering (of the shapes on the canvas) is handled by the shape objects themselves.

Standard Overrides

A custom component like ArtCanvas that subclasses directly from UIComponent will typically override the following four methods:

        override protected function createChildren():void   
        override protected function commitProperties():void
        override protected function measure():void
        override protected function updateDisplayList(unscaledWidth:Number,
                unscaledHeight:Number):void

These methods are all called during specific phases during the lifecycle of any component and are the appropriate places to perform certain operations for the component:

  • createChildren(): This method is called during the creation phase of the component. If the component is a container for other child components, this is a good place to create them. Note, however, that if children of this component are created dynamically, or otherwise not a permanent feature of this component, then it is not required to create them here. For example, in our case the drawing shapes will be children of the canvas, but none yet exist when the canvas is created, so there is no need to create any children at this stage. So ArtCanvas does not bother to override this method.
  • commitProperties(): This method is called prior to updating the rendering of this component during a frame, if any properties have changed. Imagine a component with several properties, some of which might cause a significant amount of work to update the state of the component. In this case, it might be advantageous to update the state of a component all at once, based on the cumulative effect of all property changes since the last frame. In the case of our simple canvas component there is no need for this, so once again we get away with not needing to override this method.
  • measure(): This method is called prior to rendering the component during a frame if anything has changed that may affect the size of your component, to make sure that Flex knows the preferred size of your component. Some components may base their display size on some internal state, such as the amount of text within a button, or the size of an image, or other factors which the Flex rendering system may not know how to calculate for you. In these cases, your component needs to set some internal UIComponent sizing values. Yet again, we have work here for ArtCanvas; the size of the canvas is completely defined by the container of the canvas (which Flex controls), so we have no preferred size to communicate to Flex and do not need to override this method.
  • updateDisplayList(): This method is called prior to rendering the component during a frame, when the component needs to change the way it is being drawn. Note that because Flash uses a display list to render objects, this method will only be called when the rendering of an object needs to be updated. During normal frame processing, Flash already knows how to draw the component. We actually do have some custom rendering for our component, so we did not escape this time and we do override this method and draw our component accordingly. We'll see this simple code below.

Event Handling

Objects can choose to listen to events that occur in the system, such as mouse and keyboard events on components. For any events that they want to handle, they call addEventListener() and point to a function that will be called when any of those events occur. In the case of ArtCanvas, we handle both mouse events (on the canvas itselft) and keyboard events (in the overall application window). For any event, we can get information from the Event object to find out what we need: x/y information for mouse events, keyboard characters typed for keyboard events, and so on.

The Code

Now that we understand what ArtCanvas is trying to do, let's step through the interesting parts of the code of ArtCanvas.

We Got Style

There are a couple of styles used by ArtCanvas, which are declared outside of the class:

    [Style(name="gridSize", type="int", format="int", inherit="no")]
    [Style(name="gridSnap", type="Boolean", format="Boolean", inherit="no")]

These styles control an invisible grid on the canvas that the cursor will "snap" to during drawing. This feature can be useful for making more exact drawings where objects need to line up and typical mouse movement precision makes that difficult. These metadata tags ("[Style...]") communicate to Flex that this class can be styled in MXML to affect these properties. Now, developers can use CSS style tags to change the values of these grid properties, as we saw previously in the code for TopDrawer.mxml.

We retrieve the values for these properties dynamically as we track the mouse:

        private function getGridSize():int
        {
            return (getStyle("gridSize") == undefined) ? 10 : getStyle("gridSize");
        }   

        private function getGridSnap():Boolean
        {
            return (getStyle("gridSnap") == undefined) ? false : getStyle("gridSnap");
        } 

And we use these values when we call snapPoint(), which is responsible for returning the nearest point on the snap grid to a given (x, y) location (which will typically just be the current mouse location). I won't bother putting the code to snapPoint() here, since it's pretty simple; just trust me that it does what I said, and check out the code in the file for the details.

A: Is it difficult aligning objects in TopDrawer? A: No, it's a snap

Events

We create a custom event in ArtCanvas, and use the following metadata to communicate this to Flex:

        [Event(name="drawingModeChange", type="events.DrawingModeEvent")]

When the internal variable currentShapeMode changes, we will dispatch the drawingModeChange event so that listeners (which are declared in TopDrawer.mxml, as we saw last time) are aware of the change.

Properties

Now, let's see the instance variables that will be used for the canvas:

        // The drawing shapes on the canvas
        private var shapes:ArrayCollection = new ArrayCollection();

        // Point at which a shape starts being drawn - used to track
        // delta movement in mouse drag operations
        private var startPoint:Point;

        // Current shape drawing mode
        private var _currentShapeMode:int = LINE;
   
        // Current shape being drawn
        private var currentShape:ArtShape;
   
        // Currently selected shape. If null, no shape is selected.
        private var selectedShape:ArtShape;
   
        // Shape which renders selection handles for currently selected shape
        private var selectionShape:Shape;
   
        // Color with which following primitives will be created and drawn
        private var _drawingColor:uint;
   
        // Stroke width for future line-drawn primitives
        private var _strokeWidth:int;

Some of these are used to track internal state, such as the startPoint of the current ArtShape. Others are values that are controlled through the GUI, such as the drawingColor, which can be changed by the user via the ColorPicker component. It is helpful, at least if you're just learning ActionScript3, to see the pattern for these externally-modifiable properties in the language. Let's look at currentShapeMode as an example.

Note that our class variable for _currentShapeMode is private. But we want this variable to be settable from outside the class. In addition,we would like to dispatch our custom event drawingModeChanged when this variable changes. A typical pattern in other languages is to have a parallel "setter" method, such as setDrawingColor(), that can be called to affect the value of _currentShapeMode. A similar setter is created in ActionScript3 by the following code:

        public function set currentShapeMode(value:int):void
        {
            _currentShapeMode = value;
            dispatchEvent(new DrawingModeEvent(value));
        }

Note the syntax here; the method is not actually called "setCurrentShapeMode()", but instead uses the keyword "set" to indicate that it is a setter for the class variable currentShapeMode. The cool thing about this approach is that external users of this variable simply reference currentShapeMode directly, instead of calling a method, like this:

        canvas.currentShapeMode = somemode;

For example, the DrawingShapeIcon component defined in TopDrawer.mxml that handles setting the drawing mode to LINE does this by the following click handler:

        click="canvas.currentShapeMode = ArtCanvas.LINE;"

This approach has the terseness of setting a field from the caller's standpoint, but actually calls your set method, where you can perform more than a simple assignment of the variable. In this case, we need to both set the value of the variable and dispatch an event; we do both of these in our setter.

Shapes

Finally, we're onto the heart of this class, and the entire application: creating and manipulating shapes. This is done mainly through mouse handling; mouse clicks allow selection and mouse drags enable either creation (if nothing is selected) or movement of a selected shape.

Since we will need to handle mouse events, we need to inform Flex that we want to listen for these events. We do this in our constructor:

        public function ArtCanvas()
        {
            super();
            addEventListener(MouseEvent.MOUSE_DOWN, handleMouseDown);
            addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
        } 

Of course, these events will only give us move up/down information. In order to handle mouse drag events we also need to track mouse movement. But since we only care about mouse movement while the mouse button is down (that is, mouse drags, not just mouse moves), we will only add a listener for mouse movement when there is a mouse down event. We'll see how that is done that later in the handleMouseDown() method.

First, a utility method. There are two different places where an object may be selected: when an existing shape is clicked on by the user and when the user finishes creating a shape. To avoid duplicating the code, there is a selectShape() method. This method registers that a shape is selected, creates a new selectionShape, which is basically a set of selection handles (filled rectangles), the position of which is determined by the shape being selected, and adds the selectionShape to the children of the canvas so that it is displayed appropriately:

        private function selectShape(shape:ArtShape):void
        {
            selectedShape = shape;
            selectionShape = selectedShape.getSelectionShape();
            addChild(selectionShape);
        }

Here is our handler for mouse down events. startPoint gets the point where the mouse was clicked on the canvas or, if grid snapping is enabled, the nearest point on the grid:

        private function handleMouseDown(event:MouseEvent):void
        {
            startPoint = snapPoint(event.localX, event.localY);

Next, we get the global mouse location relative to the Flex window (otherwise known as the Flash "stage"), which we will use in testing for object selection. Note that we do not use a grid-snapped point for selection because we want to test against the actual pixels of a shape, and many or most of those pixels will actually not be on the grid (picture a diagonal line, for example, most of whose pixels lie between, not on, grid points):

            var selectPoint:Point = localToGlobal(new Point(event.localX, event.localY));

Next, we see whether there is already a currently-selected shape. If so, we see whether we hit that shape with this mouse-down operation. If not, we deselect the shape (which includes removing the transient selectionShape from the children displayed by the canvas):

            if (selectedShape) {
                if (!selectedShape.hitTestPoint(selectPoint.x, selectPoint.y, true)) {
                    removeChild(selectionShape);
                    selectedShape = null;
                }
            }

If there is no shape selected (or if we deselected a previously selected shape because the current mouse location missed it), then see whether we should select a shape, based on the global mouse position. Note that the true parameter in the hitTestPoint() call tells the method to base hits only on actual shape pixels not the simple bounding box of the shape:

            if (!selectedShape) {
                for each (var shape:ArtShape in shapes)
                {
                    if (shape.hitTestPoint(selectPoint.x, selectPoint.y, true))
                    {
                        selectShape(shape);
                        break;
                    }
                }
            }

If we still do not have a selected shape, then the mouse truly didn't hit any of the existing shapes. So it's time to create a new a new shape. This is done by instantiating one of the handful of specific Shape subclasses, according to the currentShapeMode variable (the value of which is determined by which icon the user selected in the TopDrawer.mxml UI), sending in this initial point to the new shape, and adding that shape to the display list of the canvas:

            if (!selectedShape) {
                switch (currentShapeMode) {
                    case LINE:
                        currentShape = new Line(strokeWidth, drawingColor);
                        break;
                    case ELLIPSE:
                        currentShape = new Ellipse(strokeWidth, drawingColor, false);
                        break;
                    // and so on: other cases deleted for brevity
                }
                currentShape.start(startPoint);
                addChild(currentShape);
            }

Finally, we now need to track further mouse-move events, which will be used to either move a selected shape or continue creating the new one:

            addEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);
        }

As long as the mouse button is held down, we will receive mouse movement events, which will be handled as drag operations. If there is no currently selected object, then each drag operation sends another point into the in-creation shape. Otherwise, each drag moves the currently selected object (and its selectionShape) according to how much the mouse moved since the last mouse event:

        private function handleMouseMove(event:MouseEvent):void
        {
            var location:Point = snapPoint(event.localX, event.localY);
            if (!selectedShape) {
                currentShape.drag(location);
            } else {
                var deltaX:int = location.x - startPoint.x;
                var deltaY:int = location.y - startPoint.y;
                selectedShape.x += deltaX;
                selectedShape.y += deltaY;
                selectionShape.x += deltaX;
                selectionShape.y += deltaY;
                startPoint = location;
            }
        }

When the mouse button is released, we will receive that event in our handleMouseUp() method. In this method, we will only process position information for objects being created (selected objects being moved do not need a final operation to complete; they will be handled just by the previous drag events). We add the final point to the created shape, then test whether it is valid; this prevents spurious null objects where the first/last/intermediate points are all the same. If the shape is valid, we select it and add it to the current list of shapes for the canvas. Finally, we remove our mouse movement listener since we only care about movement for dragging between mouse up and down events:

        private function handleMouseUp(event:MouseEvent):void
        {
            if (!selectedShape) {
                if (currentShape.addPoint(snapPoint(event.localX, event.localY))) {
                    if (currentShape.validShape()) {
                        shapes.addItem(currentShape);
                        selectShape(currentShape);
                    } else {
                        removeChild(currentShape);
                    }
                    // done creating current shape
                    currentShape = null;
                }
            }
            removeEventListener(MouseEvent.MOUSE_MOVE, handleMouseMove);           
        }

There is one more event that we track, which is the key-down event from the keyboard. We do this just to allow easy deletion of the currently-selected object. Our handler simply deletes the current object from the list of shapes, removes it from the children of the canvas (which removes it from the objects being displayed by Flex), and removes the current selectionShape as well:

        public function handleKeyDown(event:KeyboardEvent):void
        {
            if (event.keyCode == Keyboard.DELETE) {
                if (selectedShape) {
                    var itemIndex:int = shapes.getItemIndex(selectedShape);
                    if (itemIndex >= 0)
                    {
                        shapes.removeItemAt(itemIndex);
                        removeChild(selectedShape);
                        selectedShape = null;
                        removeChild(selectionShape);
                        selectionShape = null;
                    }
                }
            }
        }

Similarly, clicking on the "clear" button in the UI will cause all objects in the list to be deleted by a call to the clear() method:

        public function clear():void
        {
            for each (var shape:Shape in shapes) {
                removeChild(shape);
            }
            shapes.removeAll();
            if (selectedShape) {
                selectedShape = null;
                removeChild(selectionShape);
            }
        }

Display

There's one final method that is interesting to look at: updateDisplayList(). We saw this method earlier in our discussion of the typical four overrides from UIComponent, where this is the only method that we actually need to override in ArtCanvas. In our case, all we have to do here is draw our canvas to look like what we want. Here, we set the fill to be solid white and fill a rectangle the size of our component:

        override protected function updateDisplayList(unscaledWidth:Number,
                unscaledHeight:Number):void
        {
            super.updateDisplayList(unscaledWidth, unscaledHeight);
            graphics.clear();
            graphics.beginFill(0xffffff, 1);
            graphics.drawRect(0, 0, unscaledWidth, unscaledHeight);
        }

Note that all of the interesting rendering, that of the shapes that have been and are being created, is handled by the shapes themselves; when they are added as children of ArtCanvas, Flex automatically works with those shapes directly to get their display lists. So all we need to do here was handle the rendering for the canvas itself.

goto end;

That's it for ArtCanvas, which has most of the logic in the entire TopDrawer application. I'm tempted to put the rest of the code here, but I'd like to keep each blog somewhat shorter than way too long, so I'll defer it to my next entry. In that next TopDrawer article (ooooh, I can feel the suspense building...), I'll go over the code in the Shape classes and other minor classes. I'll also post the full source tree so that you can build and play with it yourself.

Wednesday, March 12, 2008

Filthy Flex Teaser

I spent last week at the Java Posse Roundup conference, where I gave a 5-minute "lighting talk" entitled "Filthy Rich [Flex] Clients." The video is posted on YouTube, along with other videos of lighting talks from the conference, but I'll embed it here as well:
The quality isn't really up to the task of showing how the code actually works (I'll blithely blame the video quality, and hope that the problem is not with the speaker). But I thought I'd post the video as a teaser for future articles. These demos are nice byte-sized techniques that you can use in Flex and Flash to get some nice graphical effects for rich applications.

Monday, March 3, 2008

Finally, Some Code! (Top Drawer, Part I)

As part of my learning the Flex platform, I plan to write some sample Flex applications to see how various things work in the system. In particular, I want to play around with MXML, ActionScript3, Flex components, Flash APIs, and general UI and graphics functionality in the platform. And I definitely want to play around with filter effects, states, and transitions, of course; I find them very moving.

To begin with, I wrote a simple vector drawing application. There's not enough of them out there, right? I remember a decent one on the original Macintosh in the mid 80's, but who's got one of those machines lying around these days? It's way easier to write a new version in Flex than to search around EBay for an old Mac and then find some place to store the thing when you're not using the drawing application.

TopDrawer: The Application

Here's the application, hopefully running here inline in your browser window.

(Apologies if it doesn't work for you; I think I've used some very basic tags to embed it in the page, and it may not work correctly if you aren't running the right version of the Flash player (version 9) that it requires.)

The cool thing about the application (apart from the amazingly beautiful UI, of course. Check out that gradient!) is that the basic GUI and the functionality of creating some simple shapes from mouse gestures was actually up and running within about an hour of my first attack on it. That seemed pretty good, for someone like me that's very new to the platform. Basic UI elements, simple mouse-handling, and simple manipulation of Flash Shape objects was quite straightforward. Finishing up the application to its current state too a bit longer, of course, as I made the UI more complex, added features, allowed selection and editing, and other nifty features. But I was heartened by my initial productivity on the application. My experience so far, albeit quite limited, is that Flex allows you to get up and running with a decent looking UI in pretty short order.

TopDrawer is pretty much like what you'd expect from a vector drawing application, although arguably a bit skimpy on features (like no Open/Save, for example, and only 6 drawing primitives, and limited editing capability, and, well, pretty big limitations overall). You select a drawing primitive from the panel, click and drag on the canvas to create it, select an object by clicking on it, and move it around with the mouse. There are some drawing attributes that you can change, such as the current color and stroke width. You can also change canvas attributes like whether drawing snaps to a grid, and what size the grid has.

Underneath, TopDrawer consists of a Flex Application component to hold the main GUI, a custom component for the canvas (a subclass of UIComponent), subclasses of Shape for the various geometric primitives, and various small helper classes. There are some particular aspects of the Flex stack that I wanted to learn more about, like custom components, styles, and events, so I made efforts to integrate some of those elements into the application.

A reasonable way to approach a blog like this where an application is discussed is to perfect the application first, and then present the finished code. This shows the correct way to go about this type of application and avoids any embarrassment over code that the author would later regret.

But where's the fun in that?

I figure the whole point of my writing this blog, especially at this point in my career at Adobe when I'm completely new to the Flex development platform, is that I can try to teach while I learn. Like if your Biology teacher didn't show up for class one day and one of the students got up and winged it instead. (Okay, hopefully I'll do a tad better than that, or at least better than I would trying to teach Biology). Because I think it's instructive to see not only what the finished code should be like, but why it's better than some other approaches that seemed like a good idea at the time.

So what I want to do instead is to show the application as I initially wrote it; not a finished product, but one which I was reasonably happy with for a first attack at the problem. I'll go over the various aspects of the code and application so that you can see how things fit together and make the application work. Hopefully, along the way, folks new to Flex, Flash, and ActionScript will learn a bit about coding in this new environment.

Then when I'm done, I'll make some changes to it and show why the changes make the code and the application better.

In case you're thinking “why should I spend the time looking at the wrong code?” I'll tip my hand and say that the initial version of the application is not actually bad; there's a lot in it that is perfectly valid for a Flex application. It's just that the later version of the application is better in some respects. So hopefully there is plenty to learn from both. When I reach a piece of code that will be improved upon later, [I'll note it like this] so that you can view it with the right degree of skepticism and an appropriately cocked eyebrow.

One more note: an entire walkthrough of the application, even this relatively small application, would take too much space for a single blog entry. So I'll stretch it over the next few entries, going over one or more files in each one. When I'm done, I'll post the entire source tree (what, you think I want to post it now and risk you skipping off before the stunning conclusion?)

Architecture

Before I dive into an actual code walkthrough, I wanted to explain how things work together at a high level.

The main application is driven from the file TopDrawer.mxml (which I'll be going over in this article, below). This file sets up the main GUI of the application, including the drawing canvas (our custom component, ArtCanvas), the drawing primitive palette (instances of a custom component that displays an icon, DrawingShapeIcon), and the drawing attribute selection items (a color chooser, a combobox for the line width, and a checkbox/textfield for the grid snap).

Most of the interaction of the application is handled in ArtCanvas.as, which tracks mouse drags and performs object creation/movement appropriately. Objects are created with subclasses of the Flash Shape object, which store the rendering operations necessary for each shape.

That's pretty much it (I told you it was a simple application). There are some other classes and pieces of functionality that I'll discuss in the context of the code walkthrough.

The Code

TopDrawer.mxml

You can view or download the full source for this file here; I'd suggest you bring up the file in a different window so that you can see the snippets I'll go over below in the larger context of the entire file.

This file sets up the main Application window. The logic in this file is mostly declarative, setting up the look of the GUI and hooking up events statically in MXML, although there is some dynamic logic specified in the file as well.

Let's take a look at the code:

    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
           layout="absolute"  xmlns:comps="components.*"
           creationComplete="windowCreated();"
           keyDown="canvas.handleKeyDown(event)"> 
Some interesting thing to note here include:
  • Xmlns:comps=”components.*”: This is an xml-ism that says “I have some custom components in my own package that I will be referring to in here”. Everything prefaced by “mx” (such as the Application component itself) is a core Flex component. Components prefaced with ‘comps” (such as ArtCanvas, which we'll see soon) are my subclasses.
  • creationComplete=”windowCreated();”: This hooks out the creationComplete event on the window and asks Flex to call the windowCreated() function, where we'll run some additional tasks that are appropriate to perform at that time.
  • keyDown=”canvas.handleKeyDown(event)”: This hooks out the keyDown event on the application and calls a handler function to process the event. This is done in order to process delete-key events to remove the currently-selected object. As we'll see later, there's a better way to do this.
      <mx:Style>
           <!-- initial values for the snap grid - these can be changed in the GUI -->
           ArtCanvas {
             gridSize: 20;
             gridSnap: false;
           }
      </mx:Style> 

I declared a couple of custom styles in the ArtCanvas class, just for the heck of it (no, really: my goal in writing this application was to learn about various Flex capabilities). This section sets those styles, which control whether drawing is ‘snapped' to an invisible grid of the specified size, to some default values. Note that these values are also settable in the GUI itself (probably not the most obvious use of Styles ever created, but it was an excuse to play with Styles…).

      <mx:Script>
           <![CDATA[
             /**
              * Some  things need to happen at window creation time, such as adding
              * listeners  for a custom event to change the drawing mode
              */
             private function windowCreated():void
             {
                   trace("windowCreated");
                   // setFocus()  allows key events (like hitting the delete key) to be
                   // processed  automatically, without having to click in a component first
                   setFocus();
                   // These event  listeners are set up to be called when the canvas mode
                   // changes.  This allows all drawing-mode icons to highlight/de-highlight
                   // themselves  appropriately when the mode changes.
                   canvas.addEventListener("drawingModeChange",  lineIcon.modeChanged);
                   canvas.addEventListener("drawingModeChange",  scribbleIcon.modeChanged);
                   canvas.addEventListener("drawingModeChange",  rectangleIcon.modeChanged);
                   canvas.addEventListener("drawingModeChange",  rectangleFilledIcon.modeChanged);
                   canvas.addEventListener("drawingModeChange",  ellipseIcon.modeChanged);
                   canvas.addEventListener("drawingModeChange", ellipseFilledIcon.modeChanged);
                   // Setting the  initial mode here, after window creation, allows the appropriate
                   // mode icon  to be highlighted through the event listener mechanism above
                   canvas.currentShapeMode  = ArtCanvas.LINE;
             }
           ]]>
         </mx:Script> 

The Script/CDATA tags are the way that MXML files set apart a section of ActionScript code. You can write the code in a separate file and then simply include that file here, but it's sometimes convenient to write small functions in the same file.

In this case, I wrote a handler for the creationComplete event on the application window, and use that opportunity to set some properties. First, I call setFocus(), which sets input focus to the application window to begin with. This works in conjunction with the keyDown handler that I set up earlier so that delete-key events can automatically be processed. Without the setFocus() call, the window would not have input focus and the keyDown even would not be received.

[This setFocus() approach is not the best way to go about what I want. We'll find a better approach later]

There are then several calls to add eventListeners to the drawing primitive icons. This is done so that when the drawing mode is changed, which is propagated through the custom event drawingModeChange, all icons get the message and highlight or de-highlight themselves appropriately.

[Although this message-sending approach is better than simply having the icons peek into the inner workings of each other and the drawing canvas, it still creates a coupling between the canvas state and the icon state. We'll see a better way to handle this later.]

Finally, now that our event listeners are set up, we set the value of the canvas' current drawing mode, currentShapeMode, which will cause the events to get sent around and the appropriate icon to get highlighted in the palette.

That's all of the ActionScript code in the application file; now back to the GUI. First, we see the creation of our drawing canvas here:

      <comps:ArtCanvas id="canvas"  drawingColor="{drawingColorChooser.selectedColor}"
           strokeWidth="{lineWidth.selectedItem.width}"
           left="105"  top="10" right="10" bottom="10"/> 

This tag creates our custom component, ArtCanvas, and sets some initial properties on it. Note that we're setting the dimension properties directly because the toplevel window, our Application component, has an absolute layout. This would look different if we were using a layout manager here. Also, note that the basic GUI was created in the FlexBuilder3 design tool (a nifty WYSIWYG GUI builder), so the hard-coded values here actually came from that tool, based on where I placed things with the mouse.

The other interesting thing to note here is that we are creating a binding between the canvas' drawingColor and strokeWidth variables with the appropriate GUI items that control those values. So when the user changes the values in the color chooser or the line-width combobox, those values will automatically be changed in the canvas. Databinding rocks; no more setting up listeners to detect these changes and then doing boilerplate property setting appropriately.

[While the databinding aspect of this of this is very cool, this approach does set up a coupling between the canvas itself with the other GUI components. We'll see a better approach later]

    <mx:HBox x="10" y="10" width="87" height="108" horizontalAlign="center">
        <mx:VBox height="100%">
            <comps:DrawingShapeIcon id="lineIcon"
                source="@Embed(source='assets/icons/line.png')"
                mode="{ArtCanvas.LINE}"
                click="canvas.currentShapeMode = ArtCanvas.LINE;"
                width="32" height="32"/>

This next section sets up the palette of drawing modes. The first two tags are simple container/layout objects, where HBox lays out its children horizontally and VBox lays out its children vertically. The overall palette consists of the one HBox with 2 VBox children, where each VBox has three palette item. Each palette item is managed by a custom Image subclass, DrawingShapeIcon. All of the icons are set up similarly; I'll just go through this single “lineIcon” and assume that you get the idea.

We set up an id for each icon, which we refer to elsewhere when we set up the event listeners; in this case, the id is lineIcon. The source item is the image file that will be displayed in this Image subclass. Note that I chose to embed the icon image here. The Flex Image component allows you to either dynamically fetch the image at runtime, which allows you to deploy a smaller SWF file, or to embed the image in the SWF file, which enables faster loading of the image. In this case, the icon images are quite small, so I opted for embedding since the footprint was negligible.

The mode value is a property of DrawingShapeIcon and determines the drawing mode that will be selected when the user clicks on that icon. Note that mode is databound to the constant value LINE in ArtCanvas.

[This data-binding of constant values is the most obvious and terse way of initializing the mode value in mxml. But it's not the most efficient; we'll see a better approach later]

Speaking of clicking, we hook out the click event to perform a single line of ActionScript code which sets the value of the shape mode on the canvas. You can see from this that execution of ActionScript code is not relegated to <mx:Script> sections or entire other ActionScript files and classes; you can call ActionScript code directly in event handlers if you need to. Typically, you would only do this for very brief amounts of code, otherwise things could get unreadable pretty quickly.

      <mx:ColorPicker id="drawingColorChooser" x="10" y="126"  width="87" height="33"/> 

Next up is a simple color-chooser component. Note that we don't specify anything meaningful in this mxml code apart from the id and placement, but that an earlier component in GUI used the id of this item to data-bind between the currently chosen color and the current drawing color on the canvas.

    <mx:ComboBox id="lineWidth" x="10" y="167"  width="87"
            itemRenderer="components.LineWidthRenderer"  editable="false">
        <mx:ArrayCollection>
            <mx:Object width="1"  label="width 1"/>
            <mx:Object width="2"  label="width 2"/>
            <mx:Object width="3"  label="width 3"/>
            <mx:Object width="4"  label="width 4"/>
            <mx:Object width="5"  label="width 5"/>
        </mx:ArrayCollection>
    </mx:ComboBox> 

The ComboBox component allows a WYSIWIG way of setting the stroke width. Instead of just specifying the width with some numeric value, you can see the line width in the popup item directly and choose the appropriate one.

There are a couple of interesting things about the attributes for this component. One thing is the itemRenderer attribute; this specifies a custom component which will be called whenever the combobox needs to render one of the items in the popup. We'll see the code later, but this component basically gets the data value for the item (the width and label values above) and draws a line appropriately.

The other interesting thing about this component is the ArrayCollection item; this item is used as the "dataProvider" for ComboBox. It basically populates the popup menu with the Objects listed inside the ArrayCollection. These items are used later to determine how to render any particular item in the popup (by the itemRenderer, discussed above).

[Although this line-width component does most of what I wanted, you'll notice that the default display of the combobox (when the user is not clicking on it) displays a text-only representation of the value of the currently-selected item (which takes the value of the label field from the dataProvider). We'll see if we can get a more interesting graphical display of the selected item in a later attempt.]

    <mx:CheckBox id="snapCheckbox" x="10" y="197"  label="snap"
            change="{canvas.setStyle('gridSnap',  snapCheckbox.selected)}"
            selected="{canvas.getStyle('gridSnap')}"/>
        <mx:TextInput id="gridSizeField" x="70" y="197"  width="27"
               enabled="{snapCheckbox.selected}"
               text="{canvas.getStyle('gridSize')}"
               change="{canvas.setStyle('gridSize', gridSizeField.text)}"/> 

Lastly, we see the two items that control the grid styles. The CheckBox controls whether the snapping grid is active and the TextInput field controls the size of the grid.

Because the grid parameters were specified by Styles, versus properties, the code to change them is a bit more verbose than it would be otherwise. So, for example, when the checkbox component issues a change event, we need to send a new style value to the drawing canvas. Similarly, to have the checkbox reflect the value of the current selection value, we need to get the current style (which we then databind to, to automatically reflect changes in the style).

The text field is similar to the checkbox in its use of styles to send the values back and forth to the canvas. One interesting point is that the text field's enabled property is databound to the value of the snapCheckbox item's selected field. So the text field will only be editable if gridSnap is actually true; otherwise, the field is disabled and appears grayed-out to the user. It's a nice bit of UI completeness which really should be there in a real app, but tends to be tedious to wire up and therefore not necessarily implemented as a first-order item.

To Be Continued...

We're obviously not done; I've only shown the MXML code for the application window GUI. I also want to walk through the code for ArtCanvas, which handles the mouse interaction to create and edit the shapes, and some of the other ActionScript classes that store and render the shapes. Walking through these other files will show us more about ActionScript, Flex, and Flash programming than we have seen so far.

So look soon for the next in the series; it'll be absolutely Top Drawer.