Flex MXML ArrayCollection cannot ObjectUtil.compare

The ObjectUtil Class has lots of fun things in it that can make your life easier. When I needed to check to see if an ArrayCollection had changed, I thought to myself, why not use ObjectUtil.compare? Turns out that no matter what you do, every ArrayCollection is unique because they produce a UID parameter in every ArrayCollection instance that differentiates it. What’s the purpose of this? I have no idea, but someone thought it was a good idea.

Sadly, I did not find a solution to this problem, so I ended up using an Array instead of an ArrayCollection.

Determine Goal Width and Height in Image Resizing

I find myself doing image manipulation on a regular basis. One of the common things I have to do is to fit an image into a max width or height. I’ve distilled this as best I can, and I think this is as simple as it gets. It’s in PHP, but the logic should be applicable to any language.

$max_size=200;
$ratio = $image_width/$image_height;
if($ratio>1)
{
	$goal_width = $max_size;
	$goal_height = $max_size/$ratio;
}
else
{
	$goal_width = $max_size*$ratio;
	$goal_height = $max_size;
}

Using Flash’s Date Class in AMF PHP to MySQL

So you’re trying to rectify your dates, eh? Here’s a little funbit. If you want to take a Flash Date, transfer it to AMF, convert it to a PHP date, then insert that into a MySQL database as a DATETIME, you’re in for one hell of a headache. How does flash store it’s date class anyway? How can PHP read it? What about that whole milliseconds to seconds thing? No worries, my friends, I have a solutions for you.

Actionscript:

var d:Date = new Date()

This creates a new date. This can then be passed to AMF using whatever means you feel work best. I’m using a codeigniter port with AMF as the model that was built by my pal, Steve.

PHP to make a DATE in MySQL:
I have passed in an FP object that contains my Date object.

$date = $fp['d']/1000;
$date = date("Y-m-d","$date");

This will output your date as something like 2010-10-18. You can modify the output to be anything you like, such as:
How does it work? Flash automatically encodes Dates as the number of milliseconds since the Unix Epoch. This means that to convert it to the typical date structure in PHP, you have to convert it to seconds, which involves division by 1000. From there we can turn it into a date, but it has to be turned into a string, hence the quotes.

$date = $fp['d']/1000;
$date = date("Y-m-d H:i:s","$date");

This would give you something like 2010-10-18 15:45:30
This number can be used to insert into or compare against MySQL DATETIME entries.

fl.browseForFileURL won’t work across hard drives

In JSFL, when you use fl.browseForFileURL it returns a URI pointing to the file or folder you’ve chosen. On OX, however, the reference is wrong when you choose a file on a hard drive other than your primary.

Example: I have a hard drive on my mac named HD2. If I browse to a file on there, the URI returned will be

file:///HD2/myFile.txt

If you then immediately try a

FLfile.exists('file:///HD2/myFile.txt')

it returns false. This is due to OSX’s referencing system. the correct location is

file:///Volumes/HD2/myFile.txt

so all we have to do is add the word “Volumes/” to the string and the reference will be correct.

public static function browseForFileURI( title:String = "", type:String = "open" ):String
{
   var ar:Array = MMExecute( "fl.browseForFileURL('" + type + "','" + title + "');" ).split("/");
   ar[2] = "/Volumes";
   return ar.join("/");
}

Embed a text/txt file in a Flex/AS3 application

This is actually pretty easy, but it’s not something widely known. Here’s the code:

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
            layout="absolute"
            creationComplete="trace(text);">
   <mx:Script>
      <![CDATA[
         [Embed( source="myTextFile.txt", mimeType="application/octet-stream" )]
         public var MyText:Class
         public var text:String=new MyText().toString();
      ]]>
   </mx:Script>
</mx:Application>

So what is this doing?
The embed tag works to keep the file in your swf. It then binds it to the Class defined on the next line. Since it’s an unrecognized file format (Flex supports swf, mp3, jpg, gif, png), Flex wouldn’t know what to do with it, so we specify a mimeType — a description of how to handle this file.
Then, we create a new variable and set its contents to a new instance of the Class, then convert it to a string.
Finally, I’ve set the Application parameter creationComplete to perform a trace of the text variable’s contents. If all is correct, you should see a trace with the txt file’s contents.
EmbedTXTTest

Helpful JSFL Scripts for Indexing the Flash IDE Stage

Get all of the layers in a timeline

By using JSFL, you can use this code to get a list of all of the layers in a timeline. This is returned as an array of named objects whose data is accessible like this:

var layers = getLayers(fl.getDocumentDOM().getTimeline());
layers[0].name

This will return the first layer’s name.

var getLayers = function(timeline){
   var layers = [];
   for(var l in timeline.layers){
      layers.push({
         name:timeline.layers[l].name,
         layer:timeline.layers[l],
         index:l
      });
   }
   return layers;
};

Get all of the keyframes in a layer

By using JSFL, you can use this code to get a list of all of the Keyframes on a layer. This is returned as an array of named objects whose data is accessible like this:

var keyframes = getKeyframes(fl.getDocumentDOM().getTimeline().layers[0]);
keyframes[0].index;

This will return the first keyframe’s index, allowing you to reference it later using layer.frames[index].

var getKeyframes = function(layer){
   var keyframes = [];
   for(var f in layer.frames){
      if (f==layer.frames[f].startFrame){
         keyframes.push({
            frame:layer.frames[f],
            index:f
         });
      }
   }
   return keyframes;
};

Get all of the instances in a keyframe

By using JSFL, you can use this code to get a list of all of the instances on a keyframe. This is returned as an array of named objects whose data is accessible like this:

var instances = getInstances(fl.getDocumentDOM().getTimeline().layers[0].frames[0]);
instances[0].index;

This will return the first instance’s index, allowing you to reference it later using frame.instances[index].

var getInstances = function(keyframe){
   var instances = [];
   for(var e in keyframe.elements){
      if(keyframe.elements[e].elementType == 'instance'){
         if(keyframe.elements[e].libraryItem.itemType != 'compiled clip'){
            instances.push({
               instance:keyframe.elements[e], 
               index:e
            });
         }
      }
   }
   return instances;
};

JSFL and compiled clips

I’ve run into a number of issues trying to reconcile JSFL and compiled clips. Some of the features of a library object are unavailable when inspecting a compiled clip, leading to the wonderful JavaScript Errors we’ve come to love.

The particular oddity I’ve been wrestling with is that CompiledClipInstance objects don’t have a timeline, so if I try and walk the display list, digging into items as I find them, when I hit one of these, the reference to instance.timeline throws an error. The only solution is to exclude these kinds of items from your search.

Using Flex SWFs as Component UI or in J2EE Tapestry

Flex and Flash swfs have some small differences in how they work. While Flex produces a 2-frame swf, it doesn’t work quite right in certain situations. If you’ve got a project where Flash or an AS3 project in Flex/FlashBuilder produces SWFs that work just fine and Flex/Flashbuilder MXML-based swfs don’t (if you can right click your partially loaded MXML-based swf and say play and it works), this will probably solve your problem.

Anyone building Custom UI components in Flash might be thinking about using Flex, which, until today would prove difficult. I’ve got some other tutorials out there on how to use Flex UIs in Flash, but they were missing a big part–embedding capability.

Now that we can bypass the preloader in flex, we can use this same process to kick-start our Flex files when using them in Flash or in Tapestry (I assume Tapestry works, please let me know if it doesn’t).

Bypassing the Flex Preloader

Ahh, one of those holy grail type posts. After days of searching to answer a problem, I’ve managed to solve it by completely bypassing the preloader in Flex. It can be done, and here’s how:

Flex uses a 2-frame configuration to display its content. The Preloader is put on the first frame, and is downloaded immediately. It then waits for the rest of the content to load and fires its complete event. Then the SystemManager jumps to frame 2 and everything’s ready to go. To turn this off, we need to do two things:

1: Create a preloader shim file named PreloaderShim.as:

package
{
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.utils.Timer;
 
	import mx.managers.SystemManager;
	import mx.preloaders.DownloadProgressBar;
 
	public class PreloaderShim extends DownloadProgressBar
	{
		private var delay:Timer = new Timer(1);
 
		override public function set preloader(value:Sprite):void
		{
			SystemManager(value.parent).gotoAndStop(2);
			delay.addEventListener(TimerEvent.TIMER, go);
			delay.start();
		}
 
		public function go(e:TimerEvent):void{
			delay.stop();
			delay.removeEventListener(TimerEvent.TIMER, go);
			delay = null;
			dispatchEvent(new Event(Event.COMPLETE));
		}
 
	}
}

2: Use this in our Flex file:

<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
				preloader="PreloaderShim">

We override the set preloader function of the DownloadProgressBar class. This is automatically set to the preloader instance in Flex. This instance’s parent is the SystemManager. The SystemManager has a gotoAndStop method that allows us to skip to the next frame. Almost immediately, we can fire the complete event. I think that Flex needs a single millisecond to begin its download process, so we wait that long before firing the complete. After that, Flex loads, no preloader perceived.

The Flex part is easy–just point your Flex project to have this new class as a preloader. Just drop your PreloaderShim.as file in with your mxml files and you’re off and running!

Note, I’ve only tried this on local files, and have NO idea how it would work in a real, downloading production file. It works fine for me, but please test it before you go breaking things.

Flash IDE CS4 crashes on any AS3 file close after profiling in Eclipse FlexBuilder 3

Recently I felt the need to work with the Flex Builder 3 Profiler. I found, as many OSX people do that the profiler didn’t work out of the box. I modified my mm.cfg file with the following line

PreloadSwf=/Users/mengel/Documents/workspace/.metadata/.plugins/
	com.adobe.flash.profiler/ProfilerAgent.swf?host=127.0.0.1&port=9999

This allowed the profiler to talk to pretty much every swf I load and was working great. What I didn’t know is that when you get your profiler working, it starts modifying your Flash Player preferences in a way that the Flash IDE may not like. It specifically added a folder:

/Users/mengel/Library/Preferences/Macromedia/Flash Player/#Security

This folder, coupled with my project settings, produced a configuration file that, every time I closed anything remotely AS3 related, crashed Flash, never to return. Since this is a bug in Flash player, uninstalling/reinstalling CS4 does nothing.
Even opening the projects panel and closing it breaks Flash as the IDE uses the player to display it. The solution is to remove the #security folder, drop your mm.cfg, and work without the profiler until you absolutely need it.

A friend of mine also tells me that the beta of FlashBuilder 4 may solve this problem as well. Your mileage may vary.