Memento Pattern in Actionscript 3 (UNDO/REDO)

Happy new Year everybody!

I’d like to begin 2010 with a design pattern argument.

First design pattern of this year is Memento pattern, that could be very useful if you are working on an AIR desktop application or in a Flex RIA and you want to make an history of user’s actions.
In fact this pattern is used to make undo and redo in an application.

Memento pattern is tightly coupled with originator object and it’s usually composed by 3 different parts:

  • memento
  • caretaker
  • originator

Originator is object that pass data to caretaker and it saved them in a couple of arrays (undoArray and redoArray).
So caretaker is an object that stores a memento snapshot and, if originator needs, pass undo or redo data to this object.

I prepare a sample to understand better what could you use Memento pattern in your applications (“view source” option is activated).
I wrote a Memento class with a Singleton to centralize all users actions,then I create a MementoVO that is a dynamic class to help me store data from each object used by the user, you could use a simple Object instead of a dynamic class to save more memory if you prefer.
Sample is very easy but useful for Memento pattern purpose, in fact you can move windows trough the stage and our “history” class (Memento.as) saves their positions when saveAction method is called by the originator (an instance of CustomWin).

Memento class has 4 essentials methods that are:

  • undo()
  • redo()
  • saveAction(_obj:Object)
  • saveRedoAction(_obj:Object)

I start from the end, saveRedoAction, last method, is used to save the position of a window before I restore its positions, usually Redo action is used only one time, but if you want you could create an Array and work with multiple Redo.

Another important method is saveAction that is called when mouse down event was triggered and it stores in memento class own old position and object itselfs.

First two methods need to undo and redo an user action, it’s easy isn’t it?!

I think that in this year I’ll share lots of those patterns with you to share our knowledge together so feel free to add comment at this post and we could make an interesting and useful conversation, I’m totally sure!

Multitouch with Actionscript 3 and AIR 2.0

AIR 2.0 is out with a BETA version on labs since a couple of weeks ago more or less.
It introduces a lots of new features like UDP protocol, Socket server implementation, access to raw micrhophone data, multitouch and gesture support and so on.

When I see multitouch and gesture support I start to think how many devices are touchscreen based and they are growing a lots in those months, so I start to investigate about that features.
First of all I suggest to read a cool article on devnet made by Christian Cantrell, he goes in deep about this new features and give you a lots of information about Multitouch, TouchEvent and gestures.
It’s so interesting because you can see compatibility of that features with different OS also.

In this post, I’d like to share with you a little sample on how you can create an AIR 2.0 application with Flash Builder and test it with a macbook trackpad.
In fact, you can use macbook trackpad gesture because they are supported on AIR and it’s so interesting, for example, if you want to test an application for new Wacom Bamboo pen & touch and you haven’it.
Wacom Bamboo has a new AS3 SDK for Flex and Flash that allow you to work with multitouch and gesture too, it could be so interesting if you don’t have a multitouch for an expo and you want to buy a cheap solution to give a cool interaction for your possible new clients.
Bamboo has also the availability to create “minis” that are applications dedicated to Wacom Bamboo, but you can read more at Wacom developer website.

So, in this sample we load an external image and we use gesture to try our macbook trackpad:

package {


import flash.ui.Multitouch;
import flash.ui.MultitouchInputMode;
import flash.events.TransformGestureEvent;
import flash.text.TextField;
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.Loader;
import flash.net.URLRequest;
import flash.events.Event;


public class MultiTouchSample {


Multitouch.inputMode = MultitouchInputMode.GESTURE;
private var sq:Sprite;


public function MultiTouchSample() {


sq = new Sprite()
addChild(sq);


this.addEventListener(TransformGestureEvent.GESTURE_ZOOM, scaleObj);
this.addEventListener(TransformGestureEvent.GESTURE_PAN, panObj);
this.addEventListener(TransformGestureEvent.GESTURE_ROTATE, rotObj);


var l:Loader = new Loader();
l.contentLoaderInfo.addEventListener(Event.COMPLETE, addImg);
l.load(new URLRequest("img/sample.jpg"));
}


private function addImg(e:Event):void{
sq.addChild(e.target.content);
sq.scaleY = sq.scaleX = .2;
}


private function rotObj(e:TransformGestureEvent):void{
sq.rotation += e.rotation;
}


private function panObj(e:TransformGestureEvent):void{
sq.x += e.offsetX * 2;
sq.y += e.offsetY * 2;
}


private function scaleObj(e:TransformGestureEvent):void{
sq.scaleX *= e.scaleX;
sq.scaleY *= e.scaleY;
}
}
}

You can see that is so simple work with gesture, a couple of suggestions before starting work with them:

  • remember to verify which gesture are supported on your system, more information you can read on devnet article about multitouch and gesture
  • TransformGestureEvent is event class dedicated to gesture
  • you can use TouchEvent also

Feel free to leave a comment and thank you to visit this blog.

Flash Platform, automotive and industrial marketplace

During my last 6 months I take part in a couple of projects that are focused on Flash Platform and “unconventional devices”.
It seems strange, I know, but what I mean with the term “unconventional devices” ?

I mean that I use Flash Platform on embedded system with the purpose to create interface of industrial machine and automotive world.
Solutions based on Flex and AIR have great success for final customer, in particular because client has a great GUI with a cool user experience and he doesn’t lost any features with the hardware.
In fact we mix a couple of technologies to create those software like Python and C++.
Those tehcnologies make dirty work for us and via Socket or JSON, depends on traffic data, we make a bridge with Flex or AIR.
Performance are very cool, CPU processors move from 45% to 70%, optimization task take a great part of our time.

It was so interesting try for the first time AIR 1.5 on linux OS, we use Gentoo and Ubuntu too and I think they are very strong OS in particular development like this one.
Many people was really shocked in front of powerful of Flash Platform GUI from others developers to our clients, they can find from GPS integration until to a VOIP module made with Ribbit, from a wizard that guide user to interact with industrial machine to customization of GUI at runtime; everything in the same application that doesn’t run in a computer! Really awesome!

I saw during MAX that others companies are moving first steps trough automotive world but with Flash Lite, I think that an Intel ATOM processor has more potential and it’s so cheap for industrial market, when will be release new ARM processors (I think ARM 9…), that will be more powerful and cheap too, and Flash Player 10.1 or AIR 2.0 will have more opportunity to approach new marketplaces and also gives to many people great and easy user interface to work with.

Today Adobe releases in Adobe Labs Flash Player 10.1 and AIR 2.0 public beta, it’s a first steps to new opportunity for Flash Platform developers, many devices implements Flash Player and in future I think there will be many more.
So I’d like in a future, to find many “unconventional devices” with a Flash GUI because NOW we could make the history with those technologies.

Why AIR is called AIR? my crazy idea

Yesterday morning when I came back from an AS3 course in Venice, when I was in my car (it was too hot!), I started to think why AIR was called AIR (I know I’m totally crazy!).
So, feel free to follow me in this mind trip:

1. There aren’t any kind of Adobe software where in own name there is “Adobe” word, in fact we talk about Adobe Photoshop, Adobe Flash, Adobe AIR, but if you read in long version Adobe AIR you’ll read Adobe Adobe Integrated Runtime… bad sound!

2. AIR is a technology that allow you to bring your web contents and put on user’s desktop to create an “offline software”.
In 1996 Macromedia published a whitepaper where, for the first time, they talked about RIA (Rich Internet Application), so a kind of online software.

So AIR is the opposite of a RIA (one works online the other one mainly offline) and if you reverse the word R I A, you can find A I R!!!

I think that, after called this technology AIR, they think about the real acronym and marketing strategy.

I know, I’m crazy… but it’s funny… isn’t it?! 😀

Modules and DragManager bug in Flex 3

In my last RIA project based on Flex 3, I find a bug working with modules that I’d like to sharing in this blog.

I create a dashboard where 4 custom components, that extend Panel component, load in a ModuleLoader differents sections.
In those sections there are components based on List component and when I run my project I’ve this kind of error:

TypeError: Error #1034: Type Coercion failed: cannot convert mx.managers::DragManagerImpl@21ef6df9 to mx.managers.IDragManager.

Surfing on web I don’t find anything about this kind of problem, finally on JIRA Adobe Flex bugs, I find it!
You can find workaround on JIRA ticket, it’s so easy to solve it, you only create a new instance of DragManager in your Default Application and everything works well.
This bug is created because you have more instance of DragManager in this sample, but DragManager in Flex framework is used like a Singleton so only one instance per time.
Each module has a List component that use DragManager when you have in the same application 2 or more modules you must put in Default Application file a DragManager instance and that’s it!
I think could be useful for anybody in the same situation.

Talking about Flash Catalyst and Adobe AIR in Rome at “Arrivano i guru”

Next week in Rome, starts a new Italian event called Arrivano i guru, where 6 speakers from designers to developers, talking about Adobe technologies and others arguments.
I’ll be speaker there and I choose to talk about Adobe AIR and Flash Catalyst Public Beta, because I think could be so interesting for people that comes to this event understand how to approach this new world and start to work with those technologies.
In fact I think in Italy there are few companies that approach AIR to create real desktop application and an overview about Flash Catalyst give me opportunity to introduce a new way to skinning your RIA or desktop applications and how to save lots of times in a real workflow.

In the same event you can find others session about Digital Imaging, Advanced technique with Indesign or Photoshop and SEO also.
I think could be very interesting for a lots of Italian people, so feel free to leave a comment here if you’d like to receive more information about this event.

For more information or registration take a look at official site event.
See you there guys.

Flash Builder Beta is out… my first tests

Finally is OUT! New Flash Builder version is out in labs.adobe.com

I spent all the evening to try new features, so I think that could be useful talking about that in my blog.
The new features that I like so much are:

  • States / Library / Modules: States are totally changed in a new version that make easier write in MXML, I love so much includeIn and excludeFrom attribute to decide in which state you can put or remove a particular component.
    If you want you can work also with group and add in the same group N states.
    Library is a new object that works like Flash library, so you can create a Definition (like a Symbol) and reuse it during your application, make attention because you are working with Element and not Child!
    States and Library increase a lots application KB so I prefer work with Modules that load in runtime mode. They have a new particular argument when you try to load it that is ByteArray (more information on Migration Guide on labs).
  • Automatic getter / setter / event handler: YESSS! I switch to FDT in last month because I increase my productivity to write AS3 code, now with Flash Builder you’ve a couple of actions to create getter, setter and event handler, that’s so cool!
  • New Drawing API: we have a lots of new interesting MXML tag to define a shape like a square or a rectangle, but the most interesting is Paths that allow you to create particular lines and shape with bezier curve via code
  • Advanced CSS selectors: another interesting feature is the new way to refer a component via CSS, in fact you can interact with MXML structure (all buttons in an hbox must be red and all buttons in a vbox must be black).
    Very easy and cool!
  • Flex Theme: that’s one of my favorite features, in fact with Flash Builder you can create custom Flex Theme and skin your application in a second! You can find more information about Theme in Ted Patrick blog.
  • DateGroup: Instead of using Repeater to repeat a particular object, now we have DataGroup that defines a dataprovider and how to render it via an ItemRender or an ItemRenderFunction.
  • Switch a Flex project to AIR: finally if your client doesn’t know what he wants, you can swtich a Flex app into an AIR desktop application directly from context menu of Package Explorer (new name of  Flex Navigator panel).

Remember to read Migration guide, it’s so interesting! Stay tuned for next Flash Builder and Catalyst tests!
Another great resource that is now live to see Flex 4 features is Tour de Flex that you can view directly from Adobe web site.

Bye bye

First impressions about Flash Catalyst

Yesterday I was in Milan at From A to Web and I saw Serge Jespers session about RIA workflow with Flash Catalyst and Flash Builder.

In 30 minutes he made a real Flex application that interact with Coldfusion to retrieve data from a database and he started from a normal and static AI file… that’s totally AMAZING!
Flash Catalyst will be a great software that will help us to create desktop applications and rich internet application, in particular could be very interesting to create animations and user interaction on own GUI.

When Serge showed Flash Builder he interacted with a CF script (you can work with WS, XML and other back end tecnologies also) trough a panel and in few steps he was connected to data source… COOL!
I’m so excited, Flash Catalyst will change RIA and desktop apps workflow definitely! I’m sure about that… BUT…

I’d like to investigate more about Flash Catalyst when Adobe decides to release public BETA on Labs, but I asked a couple of questions to Serge during his session to understand better the power of this new software.
For me the first problem is that FC doesn’t work with Flex Modules but only with States and in big projects it could be a problem.
Yes, you can copy MXML code and  paste on a Module, but it could be more easy to choose if you want to work with states or modules or better, export your GUI like module and not only custom component.
Another thing that I’m scared is that FC is very easy to use, open new way of business and make your daily work more fast, so designers and developers that approach for first time RIA and Desktop apps could start to release tons and tons of “bad apps” like Flash in 90s… I hope that Adobe will teach around the world with free training courses, not only with one day events, or will begin a new HORROR ERA for RIA and Desktop apps.

That’s my 2 cents, if you’d like to talk about FC on this blog, feel free to leave a comment.

@PyCon with Flex and AIR

Here we are! My first conference of the year is PyCon 3 in Florence from 8th to 10th May.
This is THE PYTHON conference in Italy, there will be very cool and strong developers of the Python world from all over the world.

In this edition I propose a session about Python, Flex and AIR on how to integrate those technologies all together.
I think could be very interesting for Pyhton developers approach this RIA world and find a new way to create an amazing GUI with Flex and AIR.
It will be my first time there and I start to study Python only on January, so I’m very happy to take part on this event.

If you’d like to come, please feel free to tell me and add a comment on this post!
See you there guys.

UPDATE
I make a post about PyCon 3, in few days I’ll put conference photos on my Flickr account, stay tuned!

Create PDF in runtime with Actionscript 3 (AlivePDF, Zinc or AIR, Flex or Flash)

This morning I’ve a new target, create PDF in runtime with Actionscript 3.
Very cool project to accomplished this mission is AlivePDF, an opensource AS3 library that you can download from Google Code.
AlivePDF allow you to generate PDF in runtime with Actionscript 3 and you can add pages, draw in each pages or add images, it’s very powerful library.

In this sample I use Actionscript 3 (with FDT) and Multidmedia Zinc 3, but you can use Flex or Flash and AIR to make this sample.
So first of all I create a simple class that allow you to create a PDF file with multiple pages and to add content in each pages.
This is the code:

package org.mart3.pdfGeneration {
    import flash.events.Event;    
    import flash.utils.ByteArray;    
    
    import org.alivepdf.images.ImageFormat;    
    import org.alivepdf.saving.Method;    
    
    import flash.display.Loader;    
    import flash.events.IEventDispatcher;    
    import flash.events.EventDispatcher;
    
    import org.alivepdf.pdf.PDF;
    import org.alivepdf.layout.Orientation;
    import org.alivepdf.layout.Size;
    import org.alivepdf.layout.Unit;
    import org.alivepdf.display.Display;
    
    /**
     * @author lm
     */
    public class CreatePDF extends EventDispatcher {
        
        private var pdf:PDF;
        public var pdfBA:ByteArray;
        
        public function CreatePDF(target : IEventDispatcher = null) {
            super(target);
            
            pdf = new PDF(Orientation.LANDSCAPE, Unit.MM, Size.A4);
            pdf.setDisplayMode(Display.FULL_PAGE);
        }
        
        public function set totalPages(num:int):void{
                
            for(var i:int = 0; i < num; i++){
            
                pdf.addPage();    
                
            }
    
        }
         public function setData(_l : Loader, _numPage:int) : void {
            
            pdf.gotoPage(_numPage);
            pdf.addImage(_l, 15, 15, 0, 0, ImageFormat.JPG, 100);
        }
        
        public function savePDF():void{
            pdfBA = new ByteArray();
            pdfBA = pdf.save(Method.LOCAL);
            
            var evt : Event = new Event("baReadyEvent");
            dispatchEvent(evt);
        }
    }
}

Obviously if you want, you can create a custom event that pass to the document class the ByteArray but this is a quick sample to show how you can create PDF in runtime!

One of the amazing things that you should do with AlivePDF, it’s that you can decide to save PDF locally or on web! Read documentation because it’s very interesting what you can do with this library!

Ok now, go to document class where we use MDM swc that you can find when install Zinc on your computer (you can find 2 differents SWC, one for Flash and the other one for Flex. Remeber also that Flash SWC works with Flash CS4 also, not only with Flash CS3!).
In this class we do those simple steps:

  • create a PDF object using CreatePDF object
  • set our PDF document
  • pass an external image loaded with Loader object
  • save PDF bytearray with Zinc FileSystem class
package org.mart3.pdfGeneration {

    import flash.display.MovieClip;    
    import flash.net.URLRequest;    
    import flash.display.Loader;    
    import flash.display.Sprite;
    import flash.events.Event;
    import flash.events.MouseEvent;

    import mdm.*;

    import org.mart3.pdfGeneration.*;

    /**
     * @author lm
     */
    public class Main extends Sprite {
    
        private var pdfObj:CreatePDF;
        private var l : Loader;
    
        public function Main() {
            
            mdm.Application.init(this);            
            
            pdfObj = new CreatePDF();
            pdfObj.totalPages = 2;
            pdfObj.addEventListener("baReadyEvent", saveLocalPDF);
            
            l =  new Loader();
            l.name = "myImg";
            
            l.contentLoaderInfo.addEventListener(Event.COMPLETE, showImage);
            l.load(new URLRequest(mdm.Application.path+"assets/bg.jpg"));
        }
        
        private function saveLocalPDF(e:Event) : void {
        
            mdm.FileSystem.BinaryFile.setDataBA(pdfObj.pdfBA);
            mdm.FileSystem.BinaryFile.writeDataBA(mdm.System.Paths.desktop+"generate.pdf");
    
        }

        private function showImage(event : Event) : void {
            
            l.scaleX = l.scaleY = .4;
            var mc : MovieClip = new MovieClip();
            mc.buttonMode = true;
            mc.addEventListener(MouseEvent.CLICK, savePDF);
            mc.addChild(l);
            this.addChild(mc);
        }
        
        private function savePDF(event : MouseEvent) : void {
            event.currentTarget.alpha = .5;
            pdfObj.setData(l, 1);
            pdfObj.savePDF();

            
        }
    }
}

You can also download source files from their hosting service and test it on your computer.
Feel free to give me any comments about AlivePDF, it’s very interesting to know what you think about this AS3 library.