Tag Archives: Flex Hacks

Hacking Flex 4.5 splash screen, put some animation on it

3
Filed under Flex, Flex Hacks, Flex Mobile

Got some free time this afternoon at company to investigate a further on splash screen at Flex 4.5 SDK.

By far is the must do feature on SDK for any Flex developer out there who doesn’t want to run out from mobile development with SDK, you have three properties to set up (splashScreenScaleMode=”" splashScreenMinimumDisplayTime=”" splashScreenImage=”") , and voilá, you have a great app introduction for any device with android.
Adobe Flex Team is working pretty well on mobile development, but sometimes I love to hack, and this hack anyone who are engage with mobile development with Flex can do, doesn’t involve any advanced code or class hacking, but it could get complicated if Adobe AIR 2.6 currently on my device doesn’t allow me because had the same behavior if I deep dive into SystemManager or simple embeding.

If read the documentation on behalf this topic, they teach you to only use static images, like jpg, png, of even animated gif if you which, but maybe someone spark this idea and have better ways, but my current target is swf support.

No matter what were the decisions, but the same documentation could let others know that they can embed simple SWF with no actionscript 3.0 at all to animate the splashscreen.

The fact of this hack is simple, the property splashScreenImage does support swf also, because it’s a generic Object at SystemManager Class.
If you open the Application class you will see:

   public function get splashScreenImage():Class
    {
        // When set through mxml, the compiler uses the value in the generated loader class.
        return systemManager.info()["splashScreenImage"];
    }
 
    /**
     *  @private
     */
    public function set splashScreenImage(value:Class):void
    {
        systemManager.info()["splashScreenImage"] = value;
    }

As you see, supports Class, which lets you support swf,and is registered in systemManager invoked by info() method.

The only circustence that Flex Team didn’t mentioned that I guess, was the fact AIR fps runs 15fps and by default the Flex SDk runs at 24, I believe when AIR 2.7 hit the Android Market, they will update the documentation, because applications will get like 45fps even more on iphone/ipad.
Why, because it’s chunk a little in the very first beginning of swf animated. than you need to calculate a little better timing. Or listeting the FlexEvent.COMPLETE from preloader to start the animation.

Guess what, splash Screen is just a Flex 4.5 preloader property, they also added that feature for Desktop version.

Here’s my little hack that can help you a little bit, my animation is simple swf of 3secs with average time 4000msecs on the definition for Splashscreen.

<?xml version="1.0" encoding="utf-8"?>
<s:ViewNavigatorApplication  splashScreenScaleMode=""
							splashScreenMinimumDisplayTime="4000" 
							splashScreenImage="@Embed('assets/splash2.swf')" xmlns:fx="http://ns.adobe.com/mxml/2009" 
							xmlns:s="library://ns.adobe.com/flex/spark" firstView="views.SplashHackHomeView">

#9 Flex Hack – Filtering a data collection without filterFunction

1
Filed under Flex, Flex Hacks

This hack is about filtering data collection into control.
Some weeks ago a user of Flex-Brazil list asked how to apply filter directly on datagrid which gets the same data source. There are a great and very useful hack to apply filter function directly to data source not in the control, you can stop by here.
Okay, once you know that everything in Flash Player is Object and every object has own properties, it’s so easy to manipulate those objects, let’s take a look.

Level: Beginner.

So, what I used is just a little utility method to filter objects before apply to the control, it works with many cases, like XMLList, XMLListCollection, Array, and many UI controls that handle with data.

Here’s the method utility to make the magic:

		public function applyFilter(rule:String,col:ArrayCollection):ArrayCollection
		{
			var newArr:ArrayCollection= new ArrayCollection();
			if(col !=null){
				for each(var obj:Object in col){
					if(obj.level == rule){
						newArr.addItem(obj);
					}
				}
			}
			return newArr;
		}

I create a simple loosely temp array collection to catch all data that fits on the rule, the obj.level where level is the property I want to watch.
Doing that you will just need to some event-drive model to the collection itself and control logic workflow. The all things are very known from you.

Here’s the full code sample for this Hack.

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
 
<mx:Script>
	<![CDATA[
		import flash.sampler.NewObjectSample;
		import mx.events.CollectionEvent;
 		import mx.collections.ArrayCollection;
 
		public function applyFilter(rule:String,col:ArrayCollection):ArrayCollection
		{
			var newArr:ArrayCollection= new ArrayCollection();
			if(col !=null){
				for each (var obj:Object in col){
					if(obj.level == rule){
						newArr.addItem(obj);
					}
				}
			}
			return newArr;
		}
		[Bindable]private var o:Object;
		private var change:Boolean = false;
		private function addGuru():void
		{
			if(guruname.text.length>0){
				o = new Object();
				o.name = guruname.text;
				o.level = gurulevel.selectedLabel;
				someflexgurusCollection.addItem(o);
				change =true;
				someflexgurusCollection.dispatchEvent(new CollectionEvent(CollectionEvent.COLLECTION_CHANGE));
			}
 
		}
 
		private function updateProviders(event:CollectionEvent):void
		{
			if(change){
			dvDG.dataProvider = applyFilter('Dark Vader',someflexgurusCollection);
			cwDG.dataProvider = applyFilter('Cowboy',someflexgurusCollection);
			jdDG.dataProvider = applyFilter('Jedi',someflexgurusCollection);
			nbDG.dataProvider = applyFilter('Newbie',someflexgurusCollection);
			}
		}
	]]>
</mx:Script>
<mx:ArrayCollection collectionChange="updateProviders(event)" id="someflexgurusCollection">
		<mx:Object name="Rich Tretola" level="Jedi"/>
		<mx:Object name="Matt Chotin" level="Dark Vader"/>
		<mx:Object name="Ted Patrick" level="Jedi"/>
		<mx:Object name="Mark MidNight" level="Dark Vader"/>
		<mx:Object name="Jesse Warden" level="Dark Vader"/>
		<mx:Object name="James Ward" level="Cowboy"/>
		<mx:Object name="Joe Lott" level="Jedi"/>
		<mx:Object name="Marco Casario" level="Cowboy"/>
		<mx:Object name="Abdul Qabiz" level="Jedi"/>
		<mx:Object name="Igor Costa" level="Newbie"/>
</mx:ArrayCollection>
 
	<mx:Button x="10" y="126" label="Add" click="addGuru()"/>
	<mx:DataGrid id="dvDG" x="292" y="48" dataProvider="{applyFilter('Dark Vader',someflexgurusCollection)}">
		<mx:columns>
			<mx:DataGridColumn headerText="Guru Name" dataField="name"/>
			<mx:DataGridColumn headerText="Guru Level" dataField="level"/>
		</mx:columns>
	</mx:DataGrid>
	<mx:DataGrid id="cwDG" x="292" y="240" dataProvider="{applyFilter('Cowboy',someflexgurusCollection)}">
		<mx:columns>
			<mx:DataGridColumn headerText="Guru Name" dataField="name"/>
			<mx:DataGridColumn headerText="Guru Level" dataField="level"/>
		</mx:columns>
	</mx:DataGrid>
	<mx:DataGrid id="jdDG" dataProvider="{applyFilter('Jedi',someflexgurusCollection)}" x="502" y="48">
		<mx:columns>
			<mx:DataGridColumn headerText="Guru Name" dataField="name"/>
			<mx:DataGridColumn headerText="Guru Level" dataField="level"/>
		</mx:columns>
	</mx:DataGrid>
	<mx:DataGrid id="nbDG" dataProvider="{applyFilter('Newbie',someflexgurusCollection)}" x="502" y="240">
		<mx:columns>
			<mx:DataGridColumn headerText="Guru Name" dataField="name"/>
			<mx:DataGridColumn headerText="Guru Level" dataField="level"/>
		</mx:columns>
	</mx:DataGrid>
	<mx:Label x="292" y="21" text="Just Dark Vaders" fontWeight="bold" fontSize="11"/>
	<mx:Label x="292" y="213" text="Just CowBoys" fontWeight="bold" fontSize="11"/>
	<mx:Form x="10" y="36">
		<mx:FormItem label="Name">
			<mx:TextInput id="guruname"/>
		</mx:FormItem>
		<mx:FormItem label="Level">
			<mx:ComboBox id="gurulevel">
					<mx:dataProvider>
							<mx:String>Dark Vader</mx:String>
							<mx:String>Cowboy</mx:String>
							<mx:String>Jedi</mx:String>
							<mx:String>Newbie</mx:String>
					</mx:dataProvider>
			</mx:ComboBox>
		</mx:FormItem>
	</mx:Form>
	<mx:Label x="10" y="10" text="Add New Flex Guru" fontWeight="bold" fontSize="18"/>
	<mx:Label x="501" y="21" text="Just Jedi" fontWeight="bold" fontSize="11"/>
	<mx:Label x="502" y="213" text="Just Newbie" fontWeight="bold" fontSize="11"/>
</mx:Application>

Series of Flex Hacks at glance

1
Filed under General announcements

It’s now 8 hacks with unique content for people who love to hack things. But I’d like suggestions for future hacks and see what my readers would like to read about. I made a little list what we’re planning for the next Hacks series.

- Core Class (We’re hacking things from mx_internal namespace.
- Flex SDK and Compiler ( more 2 unique hacks for both).
- UIControls ( Controls package of Flex 3 SDK has some limitations, we need composition in Flex 3 which will be next Flex 4 adaptation).
-Remoting fast, We’re researching some great open-source projects arround web and found a much more fast Remoting Classes for data comunication, and we did some hacks for theses classes works in Flex 3.2, like response back and collection, render, kind theses fields.

Theses are our research for next hacks and I really enjoy thinking ideas to took us for theses ideas and turn them in real applicable for anyone.

Fore sure I hope a positive feedback.

#8 Flex Hack – Detecting if a user is on-line or off-line in Flex without server-side tricks

5
Filed under Flex, Flex Beyound basic, Flex Hacks

You may saw some techniques to detect if a user is on-line or off-line using httpservices IO requests and define if is on or off. This hack is easy to handle that, because doesn’t use any of theses techniques, all code run in client side as same as Adobe AIR has.

What really happens behind stages? We use the Navigator DOM even for IE4+ and Firefox3 will works this way. Because the DOM allows me to do that.

Level:Intermediate

Requirements: Flex 3.x SDK

How to:



    
        
    

That’s it. You can use your imagination and you can do same technique for apply a status Bar for your navigator, or many other things. Try to do something different reading the DOM reference for Firefox; Is a good start.

#7 Flex Hack – Reading the compilation date of SWF with the magic of ByteArray

17
Filed under Flex, Flex Beyound basic, Flex Hacks

One of interesting things about ByteArray is like a big space, you don’t know what you can do with it. By far is the largest mysterious class I ever seen so far. Adobe should explore and implode a lot of examples about their uses, googling a little bit you will find good material about; but not at latest all the power hidden.

Anyway, this hack uses the ability to read bytes instructions inside a SWF file. To achieve the goal of this hack we needed the specification format for SWF10, released by Adobe some time ago. And the help of Paul Sivtsov an experienced developer from Belarus a country that was part of Soviet union. Thanks a lot Paul and your patience with me to explain some details. Paul was researching to do some similar thing in his solution who inspired him to start from here. A sum of SWF instructions for C++ library.

Level: Expert

Requirements: Flex 3.2 SDK

Tip: The Flex compiler (mxmlc) introduces a lot of information inside a SWF when is compiled, a part from Flash CS4 that gives a limited version of SWF, seems that mxmlc should be adopted in the Flash CS4 to a standard compilation process.

The things happen in this Class:

package org.igorcosta.hacks
{
    import flash.display.LoaderInfo;
    import flash.utils.ByteArray;
    import flash.utils.Endian;

   /**
  * Direct reading of SWF file
  * Distributed under the new BSD License
  * @author Paul Sivtsov - ad@ad.by
  */

	public class SWF
	{
		public function SWF()
		{
		}

    ///////////////////////////////////////////////////////////////////////////
    // Returns compilation date of current module
    public static function readCompilationDate(serialNumber: ByteArray = null): Date
    {
      const compilationDate: Date = new Date;
      const DATETIME_OFFSET: uint = 18;

      if (serialNumber == null)
        serialNumber = readSerialNumber();

      /* example of filled SWF_SERIALNUMBER structure
      struct SWF_SERIALNUMBER
      {
        UI32 Id;         // "3"
        UI32 Edition;    // "6"
                         // "flex_sdk_4.0.0.3342"
        UI8 Major;       // "4."
        UI8 Minor;       // "0."
        UI32 BuildL;     // "0."
        UI32 BuildH;     // "3342"
        UI32 TimestampL;
        UI32 TimestampH;
      };
      */

      // the SWF_SERIALNUMBER structure exists in FLEX swfs only, not FLASH
      if (serialNumber == null)
        return null;

      // date stored as uint64
      serialNumber.position = DATETIME_OFFSET;
      serialNumber.endian = Endian.LITTLE_ENDIAN;
      compilationDate.time = serialNumber.readUnsignedInt() + serialNumber.readUnsignedInt() * (uint.MAX_VALUE + 1);

      return compilationDate;
    }

    ///////////////////////////////////////////////////////////////////////////
    // Returns contents of Adobe SerialNumber SWF tag
    public static function readSerialNumber(): ByteArray
    {
      const TAG_SERIAL_NUMBER: uint = 0x29;
      return findAndReadTagBody(TAG_SERIAL_NUMBER);
    }

    ///////////////////////////////////////////////////////////////////////////
    // Returns the tag body if it is possible
    public static function findAndReadTagBody(theTagCode: uint): ByteArray
    {
      // getting direst access to unpacked SWF file
      const src: ByteArray = LoaderInfo.getLoaderInfoByDefinition(SWF).bytes;

      /*
      SWF File Header
      Field      Type  Offset   Comment
      -----      ----  ------   -------
      Signature  UI8   0        Signature byte: “F” indicates uncompressed, “C” indicates compressed (SWF 6 and later only)
      Signature  UI8   1        Signature byte always “W”
      Signature  UI8   2        Signature byte always “S”
      Version    UI8   3        Single byte file version (for example, 0x06 for SWF 6)
      FileLength UI32  4        Length of entire file in bytes
      FrameSize  RECT  8        Frame size in twips
      FrameRate  UI16  8+RECT   Frame delay in 8.8 fixed number of frames per second
      FrameCount UI16  10+RECT  Total number of frames in file
      */

      // skip AVM2 SWF header
      // skip Signature, Version & FileLength
      src.position = 8;
      // skip FrameSize
      const RECT_UB_LENGTH: uint = 5;
      const RECT_SB_LENGTH: uint = src.readUnsignedByte() >> (8 - RECT_UB_LENGTH);
      const RECT_LENGTH: uint = Math.ceil((RECT_UB_LENGTH + RECT_SB_LENGTH * 4) / 8);
      src.position += (RECT_LENGTH - 1);
      // skip FrameRate & FrameCount
      src.position += 4;

      while (src.bytesAvailable > 0)
        with (readTag(src, theTagCode))
      {
        if (tagCode == theTagCode)
          return tagBody;
      }

      return null;
    }

    ///////////////////////////////////////////////////////////////////////////
    // Returns tag from current read position
    private static function readTag(src: ByteArray, theTagCode: uint): Object
    {
      src.endian = Endian.LITTLE_ENDIAN;

      const tagCodeAndLength: uint = src.readUnsignedShort();
      const tagCode: uint = tagCodeAndLength >> 6;
      const tagLength: uint = function(): uint {
        const MAX_SHORT_TAG_LENGTH: uint = 0x3F;
        const shortLength: uint = tagCodeAndLength & MAX_SHORT_TAG_LENGTH;
        return (shortLength == MAX_SHORT_TAG_LENGTH) ? src.readUnsignedInt() : shortLength;
      }();

      const tagBody: ByteArray = new ByteArray;
      if (tagLength > 0)
        src.readBytes(tagBody, 0, tagLength);

      return {
        tagCode: tagCode,
        tagBody: tagBody
      };
    }
  }
}

How to use:





	
		
	
	

#6 Flex Hack – RichTextEditor to output XHTML 1.1 valid

11
Filed under Flex, Flex 3, Flex Beyound basic, Flex Hacks

The RTE is a great component but for some reason Adobe didn’t compete with best standards to prioritize or has their own way to not include a valid xhtml 1.1 code output to their current RTE. I hope with the next Flex 4 and Text Layout Framework things get better for RTE and really get a little bit more features.

Asides that Keep us with out lovely Flex 3 and enjoy this hack.

Level: intermediate

Requirements : Flex 3.2 SDK

Problems: RTE output a HTML 4.0 style and for some reason is not very acceptable when you are integrating with other technologies like Ajax. For this reason this hack got a simple two methods to do the job, removing that part of there’s no magic in the Regex uses , some elements are still missing like img, didn’t find a way to handle that. But in overall you can do a bunch things already.

The code bellow represents a two static methods that does the job, where you can really on this particular case or if you wish you can create your component or a class for this propose.




	/g;
                       str = str.replace(pattern, "

"); pattern = /

/g; str = str.replace(pattern, "

"); pattern = /

/g; str = str.replace(pattern, "

"); pattern = /<\/p>/g; str = str.replace(pattern, "

"); pattern = //g; str = str.replace(pattern, ""); pattern = /color:(.*?);/g; str = str.replace(pattern, "COLOR=\"$1\" "); pattern = /font-size:(.*?)px;/g; str = str.replace(pattern, "SIZE=\"$1\" "); pattern = /font-family:(.*?);/g; str = str.replace(pattern, "FACE=\"$1\" "); pattern = /text-align:(.*?);/g; str = str.replace(pattern, "ALIGN=\"$1\" "); pattern = /<\/span.*?>/g; str = str.replace(pattern, ""); pattern= /<\/li>
  • /g; str = str.replace(pattern, "
  • "); pattern= /<\/li><\/ul>/g; str = str.replace(pattern, "
  • "); pattern= /
    • /g; str = str.replace(pattern, "
    • "); pattern = //g; str = str.replace(pattern, ""); pattern = /<\/em>/g; str = str.replace(pattern, ""); pattern = //g; str = str.replace(pattern, ""); pattern = /<\/strong>/g; str = str.replace(pattern, ""); pattern = //g; str = str.replace(pattern, ""); pattern = /<\/u>/g; str = str.replace(pattern, ""); // Remove extra white space pattern = / /g; str = str.replace(pattern, " "); return str; } public static function convertToXHtml(str:String):String { var pattern:RegExp; pattern = //g; str = str.replace(pattern, ""); pattern = /<\/TEXTFORMAT.*?>/g; str = str.replace(pattern, ""); pattern = /

      /g; str = str.replace(pattern, "

      "); pattern = /

      /g; str = str.replace(pattern, "

      "); pattern = /

      /g; str = str.replace(pattern, "

      "); pattern = /<\/P>/g; str = str.replace(pattern, " "); pattern = //g; str = str.replace(pattern, ""); pattern = /COLOR=\"(.*?)\"/g; str = str.replace(pattern, "color:$1;"); pattern = /SIZE=\"(.*?)\"/g; str = str.replace(pattern, "font-size:$1px;"); pattern = /FACE=\"(.*?)\"/g; str = str.replace(pattern, "font-family:$1;"); pattern = /ALIGN=\"(.*?)\"/g; str = str.replace(pattern, "text-align:$1;"); pattern = /LETTERSPACING=\".*?\"/g; str = str.replace(pattern, ""); pattern = /KERNING=\".*?\"/g; str = str.replace(pattern, ""); pattern = /<\/FONT.*?>/g; str = str.replace(pattern, ""); pattern= /<\/LI>

    • /g; str = str.replace(pattern, "
    • "); pattern= /<\/LI>/g; str = str.replace(pattern, "
    "); pattern= /
  • /g; str = str.replace(pattern, "
    • "); pattern = //g; str = str.replace(pattern, ""); pattern = /<\/I>/g; str = str.replace(pattern, ""); pattern = //g; str = str.replace(pattern, ""); pattern = /<\/B>/g; str = str.replace(pattern, ""); pattern = //g; str = str.replace(pattern, ""); pattern = /<\/U>/g; str = str.replace(pattern, ""); return str; } ]]>
  • Research found at:http://thanksmister.com/?p=17=4

    #5 Flex Hack – Elegant Visual experience with UI Components

    1
    Filed under Books Review, Experiments, Flex, Flex 3, Flex Beyound basic, Flex Books, Flex Hacks

    flexhackexperience

    The book above has so many hacks that it’s hard to write up in one single post. You should buy yours to know them. I’m not a big fan of design things, I prefer to do things from scratch or connection with back-end.

    But this book gave me an hidden way of hacking things for Flex components UI. I was so excited today with this book that I didn’t have time to write up on blog or even work. Juan, you did a amazing Job. Never imaginate that some styles and a skin in psd could do a tremendous impact.

    What you wont find? How to use degrafa. It’s a missed chapter that should be integrated with the book. But a part of that. The book is awsome.

    Click on the photo above and hack yours too.

    #4 Flex Hack – Add charts to Datagrid without Data Visualization Framework

    6
    Filed under Flex, Flex 3, Flex Beyound basic, Flex Components, Flex Data Visualization Framework, Flex Hacks, Sample Application

    By far Flex is great, you pick up an idea and after that becomes a solution. One of the things I really enjoy in Flex is playing with Charts. People here in Brazil always stay shocked with power of Charts and its simplicity to make.

    Anyway, Bringing Charts in Flex are such power and looks your App really awesome. This hack today is regarding that thing, simplicity without the Data Visualization Framework aka(Flex Charts).

    Also by meaning the real name for that is Gantt Chart like wikipedia says. Which a great colleague of field Andrew Trice dide a good example on how to handle that.[Update] Actually the Dusty explain on the comments that this hack is more micro chart(SparkLine chart) than Gantt Chart.

    What is necessary to it?
    – Flex 3.0.x SDK or Flex 2.0.x SDK
    – Imagination

    Anyway, here’s the result of what this hack can do:

    How is it done?

    Same as Andrew did, but a little simple, I explored the resources of Flex DisplayObject class has and UIComponent has, like draw easy.

    Here’s the code for the Hack:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
     
    	<mx:Script>
    		<![CDATA[
    			import mx.controls.Alert;
    			import mx.collections.ArrayCollection;
     
    			[Bindable]private var productCollection:ArrayCollection = new ArrayCollection();
    			[Bindable]private var product:Object;
     
    			private function addProduct():void {
    				if(pName.text != '' && pPrice.text != '' && pSold.text != ''){
    					product = new Object();
    					product.Name = pName.text;
    					product.Price = pPrice.text;
    					product.Sold = pSold.text;
    					productCollection.addItem(product);
    				}else{
    					Alert.show('Fill out all fields!','Error');
    				}
    			}
    		]]>
    	</mx:Script>
     
    	<mx:DataGrid  dataProvider="{productCollection}" x="30" y="33" width="486" height="306">
    		<mx:columns>
    			<mx:DataGridColumn headerText="Product Name" dataField="Name"/>
    			<mx:DataGridColumn headerText="Price" dataField="Price"/>
    			<mx:DataGridColumn headerText="Sold Itens" dataField="Sold">
    					<mx:itemRenderer>
    						<mx:Component>
    								<mx:HBox horizontalScrollPolicy="off" verticalScrollPolicy="off" width="100%" height="100%">
    									<mx:HBox verticalScrollPolicy="off" horizontalScrollPolicy="off" backgroundColor="#a604e9"
    										 width="{Number(data.Sold)*0.01}" height="100%"/>
    									<mx:Label text="{String(Number(data.Sold)*0.01)}%"/>
    								</mx:HBox>
    						</mx:Component>
    					</mx:itemRenderer>
    			</mx:DataGridColumn>
    		</mx:columns>
    	</mx:DataGrid>
    	<mx:Form defaultButton="{addProductBtn}" x="545" y="24">
    		<mx:FormItem label="Product Name">
    			<mx:TextInput id="pName"/>
    		</mx:FormItem>
    		<mx:FormItem label="Price">
    			<mx:TextInput restrict="[0-9]" id="pPrice"/>
    		</mx:FormItem>
    		<mx:FormItem label="Sold Itens">
    			<mx:TextInput id="pSold" restrict="[0-9]"/>
    		</mx:FormItem>
    	</mx:Form>
    	<mx:Button id="addProductBtn" x="736" y="142" label="Add Product" click="addProduct()"/>
     
    </mx:Application>

    As you see you can reproduce any kind of hack like that, because the power of itemRender mechanism in Flex is very powerful for data representation. By at the end you see that is not a big deal doing that with your project, and the final result looks awesome.

    Playing Effects Too

    Here’s same example but now using Effects.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
     
    	<mx:Script>
    		<![CDATA[
    			import mx.controls.Alert;
    			import mx.collections.ArrayCollection;
    			import mx.effects.easing.Elastic;
     
    			[Bindable]private var productCollection:ArrayCollection = new ArrayCollection();
    			[Bindable]private var product:Object;
     
    			private function addProduct():void {
    				if(pName.text != '' && pPrice.text != '' && pSold.text != ''){
    					product = new Object();
    					product.Name = pName.text;
    					product.Price = pPrice.text;
    					product.Sold = pSold.text;
    					productCollection.addItem(product);
    				}else{
    					Alert.show('Fill out all fields!','Error');
    				}
    			}
    		]]>
    	</mx:Script>
     
    	<mx:DataGrid  dataProvider="{productCollection}" x="30" y="33" width="486" height="306">
    		<mx:columns>
    			<mx:DataGridColumn headerText="Product Name" dataField="Name"/>
    			<mx:DataGridColumn headerText="Price" dataField="Price"/>
    			<mx:DataGridColumn headerText="Sold Itens" dataField="Sold">
    					<mx:itemRenderer>
    						<mx:Component>
    								<mx:HBox horizontalScrollPolicy="off" verticalScrollPolicy="off" width="100%" height="100%">
    									<mx:Resize duration="1500" target="{_grchart}" id="_eff" widthTo="{Number(data.Sold)*0.01}"/>
    									<mx:Script>
    										<![CDATA[
    											import mx.effects.easing.Back;
    										]]>
    									</mx:Script>
    									<mx:HBox  id="_grchart" creationComplete="_eff.play()" verticalScrollPolicy="off" horizontalScrollPolicy="off" backgroundColor="#a604e9"
    										 width="0" height="100%"/>
    									<mx:Label text="{String(int(data.Sold)*0.01)}%"/>
    								</mx:HBox>
    						</mx:Component>
    					</mx:itemRenderer>
    			</mx:DataGridColumn>
    		</mx:columns>
    	</mx:DataGrid>
    	<mx:Form defaultButton="{addProductBtn}" x="545" y="24">
    		<mx:FormItem label="Product Name">
    			<mx:TextInput id="pName"/>
    		</mx:FormItem>
    		<mx:FormItem label="Price">
    			<mx:TextInput restrict="[0-9]" id="pPrice"/>
    		</mx:FormItem>
    		<mx:FormItem label="Sold Itens">
    			<mx:TextInput maxChars="4" id="pSold" restrict="[0-9]" width="162"/>
    		</mx:FormItem>
    	</mx:Form>
    	<mx:Button id="addProductBtn" x="736" y="142" label="Add Product" click="addProduct()"/>
    </mx:Application>

    #3 Flex Hack – Customize your Flex Components view and Standard properties view in Flex Builder

    8
    Filed under Flex, Flex Builder, Flex Hacks

    One of the things I love is hacking, this is a another very handy hack to explore in your flex builder software. And almost forgot, sorry for the big title.

    To start with it, you should have the last version of Flex Builder 3.1.x, or probably maybe works in 3.0 but in my case I don’t have this version, anyway, let’s start.

    This procedure isn’t documented yet, probally will be included in Flex Builder 4.0 after this post (hope so).

    How it works?

    Flex Builder has a great way to organize its components in tree mode, which is very a good way to organize things and make things clear to any user who are coming to Flex world.

    By default, every component you create that is not part of default Flex components you will have placed in the custom directory of Flex Components view in your Flex Builder, which is already know by you.
    The responsible for this is a internal xml file that automaticly generate a tree to use in run-time inside the Flex builder, but you can create manually and place in your .swc to procedure like that.

    First you have to define a file called design.xml that has this structure:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    
     <?xml version=”1.0″ ?>
     
    <design>
     
    <namespaces>
     
    <namespace prefix=”YOUR NAMESPACE” uri=”YOUR URL FOR NAME SPACE” />
     
    </namespaces>
     
    <categories>
     
    <category id=”YOUR CATEGORY” label=”THE LABEL” defaultExpand=”true” />
     
    </categories>
     
    <components>
     
    <component name=”The NAME” namespace=”YOUR NAME SPACE” category=”YOUR CATEGORY” displayName=”THE NICK NAME”>
     
    <mxmlProperties>
     
    </mxmlProperties>
     
    </component>
     
    </components>
     
    </design>

    This guy above is magic, what is create? It’s create the hole directory of your components design to place in Flex Builder components view. Every time you add a .swc in the libs folder of Flex Builder, the Flex Builder internal functions look up for this file, and if it’s missed the Flex Builder generate a new one and get the manifest.xml file for that .swc loaded.
    If we set by our own, Flex Builder will not ignore and render that.

    Let’s get a case to work:

    1 – Create a new Flex Library Project
    2 – Place any Class you have in the src directory for the project.
    3 – Note : Don’t generate now the .swc file
    4 – Let’s define the design.xml and manifest.xml, mine is follow below:

    File: design.xml

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    
    <?xml version="1.0" ?>
     
    <design>
     
    	<namespaces>
     
    		<namespace prefix="FlexHacking" uri="http://www.igorcosta.org" />
     
    	</namespaces>
     
    	<categories>
     
    		<category id="Hacking" label="Hacking" defaultExpand="true" />
     
    	</categories>
     
    	<components>
     
    		<component name="Window" namespace="FlexHacking" category="Hacking"
    			displayName="Window">
     
    			<mxmlProperties>
    				<combo id="footerEnabled" name="Enable Footer:" />
    			</mxmlProperties>
    			<defaultAttribute name="footerEnabled" value="false" />
    		</component>
     
    		<component name="HellowWorld" namespace="FlexHacking"
    			category="Hacking" displayName="HelloWorld">
     
    			<mxmlProperties>
    				<textfield id="phrase" name="Say something:" />
    			</mxmlProperties>
    		</component>
     
    	</components>
     
    </design>

    File manifest.xml:

    1
    2
    3
    4
    5
    
    <?xml version="1.0"?>
    <componentPackage>
        <component id="Window" class="org.igorcosta.hacking.Window"/>
        <component id="HelloWorld" class="org.igorcosta.hacking.HelloWorld"/>
    </componentPackage>

    As you see above I’ve created two simple classes to execute the hack, and see the picture bellow to see the structure of my project.

    You know, remember that I said in the beging of hack to not compile your Flex library project? It’s because we have to include the design.xml into the .swc file. To do that, follow the steps:

    5 – Right Click at your project and select Properties
    6 – In the left choose Flex Library Build Path
    7 – Select the Assets tab and mark to include manifest.xml and design.xml
    8 – Now select the Flex Library Compiler and include your namespace URL
    9 – Include the manifest file .xml that you have.
    10 – Make fire and click Ok.

    That’s it. The file is done and ready to place in any other project like Flex Project and you will see the properties and your own category in Flex Builder.

    Here’s the final result :

    Didn’t follow too much? Missed something? Grab here the Full source code of my solution. Import an existing Project into your workspace.

    [Update 12/19/2008] If you have problems using this technique in Flex Builder 3.0.1 and 3.0.2 . And yours components doesn’t shows up in your Flex Builder, Try to avoid define the namespace in design.xml file and put in the Flex Library Build Path for your Flex Library project by hand typing in the field for it. Also add manually your manifest.xml file to your library. This will works for your Flex Builder 3.0.1 and 3.0.2.

    #2 Flex Hack – Give the focus on SWF when it’s loaded for any navigator

    8
    Filed under Flex, Flex Hacks

    Yes, there are so, so, so, so many developers out there that has this problem, why when I load an application and ask on my textInput or something like that .setFocus() it’s highlighted but I can’t type in no way out.
    Kind of noise the developer perspective, and irritate on bunch of workarounds to do that. But as I like simple things I’ve create a little and tiny version on how to deal with that.

    Problem:

    When I hit the button compile and my browser is opened and I try to type anything I have nothing, the event is only dispatched when I click with the mouse on the application.

    Problem description:

    This happen because browsers keep with the focus itself and doesn’t work out on embed tags properly it’s a problem for any developer that works with flash player platform. FF,IE,Safari, Opera don’t give a property way to deal with that.

    FF has a problem with embed tag and it’s a know issue possible fixed on the next version of navigator that doesn’t allow me to do focus if my swf file isn’t with parameter “wmode=opaque”, by default the Flex Builder uses the wmode=null which gives you this problem, because doesn’t work as you wish.

    Solution:

    If you have Flex Builder plug-in version or stand alone version you should go where your Flex SDK is placed, when you find it, be sure to go to C:\YOUR_SDK_PATH\sdks\3.0.0\templates

    This folder templates has the main templates for applications built-in with SDK.

    When I tried to do this hack I guess that the templates was in some jar files in the eclipse plug-in directory, but I didn’t notice that the Flex Builder uses the templates from the SDK, pretty obvious right now.

    How to process:

    After you did the previous step, you should look at the folder “client-side-detection-with-history” and you will see the index.template.html that’s is necessery to change. Ok by far we did find the file, and we now just change the line that we need to get working with all stuff for Firefox,Safari, Opera, IE, with Focus problem.

    For information only, do the change by yourself, I advice you to create a back-up of theses files before we change it.

    Ok, Open the index.template.html and look for something like html tag, probably will find at line 46 :

    1
    
     <body scroll="no">

    Change the line to :

    1
    
    <body scroll="no" onLoad="window.document.${application}.focus();" onkeydown="window.${application}.focus()" >

    Finish! Not so fast, you also need to change the default wmode parameter that the swf recives, It’s a bug in Firefox specially and wont work if you don’t change the wmode to opaque value. How?

    Continuing in the file index.template.html opened, scroll down and look at lines 73 and 89, you will not delete any of theses lines but press enter and put the param bellow.

    1
    
    "wmode="opaque",

    That’s it, you hacked the file, save and close and start again your flex builder, you will see that now your Flex Builder will generate the changed version and your swf will never loose the focus.

    You can extends more your hack adding this technique to others templates. easy isn’t?! Give me feedbacks.