Archive for the ‘Flex’ Category

AS3 can solve more brain teasers than AS2

Wednesday, November 7th, 2007

In one of my flash applications I take in some text (HTML) and do some processing (convert to plaintext). Since this was written in AS2, which doesn’t have regular expressions or a String.replace() function we came up with a simple alternative. split().join(). This worked exactly as we wanted, replacing the text passed to split() with the text passed to join(). Part of this conversion was to compress 3 or more newlines into only 2 newlines. This would be easy with a regular expression but with only split().join() I had to run this through a while loop in order to compress 3 or more newlines into only 2 newlines. This was the code:

while (str.indexOf("\n\n\n") != -1) {
      str = str.split("\n\n\n").join("\n\n");
}

A very simple loop that, if it works correctly, will compress any number of 3 or more consecutive newlines into only 2 newlines. Needless to say it did work correctly in our AS2 application.

In January of this year I started converting our AS2 application to AS3 and Flex. Since we still had need of this conversion and the code should have worked fine in AS3 I copied it over and all seemed well. However, after testing for a while we started to get hangs of the application at a certain point. One of our developers traced it to an infinite loop….the while loop above. He then debugged into the loop, found that the array returned by split() had an empty string in it, and added some code to remove an empty string, should one be found.

When I saw the commit I was baffled. This looked like added code to solve a problem that didn’t exist. After all, this code had worked fine in AS2 and it was self-evident that the number of newlines would always reduce, as 3 newlines were always replaced by 2……or were they?

After a back and forth with the developer in question I had a small reproduction script which would loop infinitely, despite the fact that it was replacing 3 newlines with 2. I decided to write my own simple test case and check the output in AS2 and AS3. To simplify things I used simple characters instead of newlines:

trace("abbbbc".split("bbb").join("bb"));

Run in AS2 I get “abbbc”, a reduction of 1 ‘b’ from the string, as expected. Run in AS3, however I get back the exact same string: “abbbbc”. Curious, I tried the following:

trace("abbbc".split("bb").join("b"));

This produced the same result in both AS2 and AS3, “abbc”, a reduction of 1 ‘b’, as expected. I then tried the next case up:

trace("abbbbbc".split("bbbb").join("bbb"));

This code returned “abbbbc” in AS2, again as expected, but in AS3 returned “abbbbbbc”, an increase of 1 ‘b’!

Well, I had obviously found a regression in AS3 vs AS2. I then tried regular expressions to see if the same thing happened with them:

trace("abbbbc".split(/bbb/).join("bb"));

This, (in AS3 of course, AS2 doesn’t have regular expressions) produced the desired output of “abbbc”. In my searching I also noticed that String has a replace() method in AS3 which will do global replacements if the regex has a ‘g’ modifier. Now that I had found a solution I switched all of our split().join() mess to use replace() with a global regex. Furthermore I replaced the while loop above with a single replace call with a regular expression, as I had wanted to do when I first wrote it, hence:

str = str.replace(/\n\n\n+/, "\n\n");

I also tried replace to see if ir exhibited the same problem as split().join():

trace("abbbbc".replace("bbb", "bb"));

AS3 reported “abbbc”, the wanted output, so the problem is specifically in split() in AS3 and only when used with a string and not a regular expression. Of course this is somewhat obvious as replace() only replaces the first occurance of a string unless a regex with ‘g’ is used.

Further testing revealed an interesting anomaly if my replacement text used a different character than the text I was searching for:

trace("abbbbc".split("bbb").join("zz"));
trace("abbbc".split("bb").join("z"));
trace("abbbbbc".split("bbbb").join("zzz"));

In AS2 this outputs:

azzbc
azbc
azzzbc

leaving the last ‘b’ untouched, as we would expect; but in AS3:

azzzzc
azzc
azzzzzzc

….where did all of the ‘b’s go?

The more algorithmic among you (wait, is anyone actually reading this?) will have figured it out by now but a look at the output of split() makes this much more obvious. If you run:

trace("abbbbc".split("bbb"));
trace("abbbc".split("bb"));
trace("abbbbbc".split("bbbb"));

you get this in AS2:

a,bc
a,bc
a,bc

and this in AS3:

a,,c
a,,c
a,,c

The arrays are the same for all 3 runs but the interesting part is that in AS3 all traces of ‘b’ disappear and we get an empty string in between the “bookend” ‘a’ and ‘b’. From this output we can deduce that AS3 is finding 2 copies of the search string as the resulting array is 3 elements long; vs. AS2’s 2 element array showing that it is finding 1 match. Logically, and from a brain teaser perspective, there are actually 2 “matches” for “bbb” in the string “abbbbc”. There’s the first 3 ‘b’s and the last 3 ‘b’s. This isn’t how we were expecting split() to function, though, as the semantics of split() are supposed to be such that if you do a split() followed by a join() with the same string you should get the same string back again. In the case of AS3 “abbbc”.split(”bb”).join(”bb”) will actually increase the length of the string by one ‘b’.

Another simple test shows that the same thing happens with a multicharacter repeating pattern:

trace("a-_-_-_-_d".split("-_-_-_").join("-_-_"));

A little cogitation reveals how this could happen given a simple splitting algorithm. Here’s some AS code which exhibits the same problem as AS3’s String.split():

function brokenSplit(str : String, needle : String) : Array {
	var output : Array = new Array();
	var lastFound : Number = 0;
	for (var i : Number = 0; i < str.length; ++i) {
		if (str.substr(i, needle.length) == needle) {
			output.push(str.substr(lastFound, i - lastFound));
			lastFound = i + needle.length;
		}
	}
	if (lastFound < i) {
		output.push(str.substr(lastFound, i));
	}
	return output;
}

and here is the same code with only 3 characters added which outputs the same as AS2’s String.split():

function fixedSplit(str : String, needle : String) : Array {
	var output : Array = new Array();
	var lastFound : Number = 0;
	for (var i : Number = 0; i < str.length; ++i) {
		if (str.substr(i, needle.length) == needle) {
			output.push(str.substr(lastFound, i - lastFound));
			lastFound = (i += needle.length);
		}
	}
	if (lastFound < i) {
		output.push(str.substr(lastFound, i));
	}
	return output;
}

The only difference between the two is that fixedSplit() increments the iterator (i) by the length of the needle when a match is found. brokenSplit() naively keeps looking for a match on the very next character even though it is inside a match.

Here is a swf running the various test cases in AS2:

Here is a swf running the various test cases in AS3:

I’ve tested in Flash versions: 9,0,28,0 (debug player for Flex Builder 2), 9,0,47,0 (current release player as of this post), 9,0,60,235 (debug player for Flex Builder 3 beta 2), and 9,0,98,0 (MovieStar). The same output displays in all 3 versions.

I have opened a bug report in Adobe’s bug system: ASC-2936.

UPDATE: fixed the swf links so you should be able to see the tests working again.
UPDATE: My bug was marked a duplicate of ASC-1739, which is slated to be fixed in Flash Player 9.1. I’m glad that others found this issue too.
UPDATE: The bug is fixed in Flash Player 10,0,12,36. It was probably fixed in an earlier version of player 9, but I’m not sure. Regardless, it is better to use the function meant for a specific use instead of a hack.

How do you catch remote FMS method calls with complex prefixes?

Tuesday, October 9th, 2007

Apparently there is no way.

The way to catch server-side Flash Media Server client.call() calls with complex prefixes is not documented. The Flex2 NetConnection docs say that NetConnection.client can be used to catch server-side calls but a call with slashes (as used for the components shipped with FMS) is not documented.

For instance, the cursor.asc server-side component calls:
client.call( this.callPrefix + “attachYourself”, null, clocal.id, cglobal.username, this.layer, cglobal.usercolor);
where this.callPrefix is by default “FCCursor/_DEFAULT_/” so the full call is “FCCursor/_DEFAULT_/attachYourself”.
In AS2 this could be caught by the object in:
netConnection["FCCursor"]["_DEFAULT_"]

The obvious place to catch it in AS3 would be:
netConnection.client["FCCursor"]["_DEFAULT_"] but this does not seem to work.

The LiveDocs also have a comment which asks this same question but the answer is not sufficient.

The only way to work around this seems to make the prefix a parameter in the call instead of prefixing the function name. This takes changing server-side and client-side code and the server code is no longer backwards compatible…..but at least it works.

I have a bug open at Adobe for this one too: FLEXDOCS-94.

Update: The bug has been answered. Slash syntax is, indeed, not supported in AS3.

Grabbing the swf’s URL when the swf is loaded

Tuesday, October 9th, 2007

I finally got fed up with recompiling our Flex application for the different servers I had to deploy to and decided to have it automatically figure out where it is and configure itself. This should have been relatively simple as the swf’s URL is known by the Flash player and was always available in Flash as _root._url (or _root[”_url”]). I knew that Flex had to have this information available so I looked it up.

Sure enough, there is a place in the DisplayObject where you can get this info. DisplayObject.loaderInfo.url. Further looking showed that the Application object should have the loaderInfo. I added some code to test this in a function which was run on the “creationComplete” event and….the loaderInfo object is null.

I then looked further to see if there was another object that maybe had the loaderInfo I needed. The root proprty is supposed to give you the root object of the SWF and this should have the right loaderInfo, right? Nope, still null on “creationComplete”.

I now got suspicious and added some code to look at the URL on the click of a button. Sure enough this code was able to access the loaderInfo and hence get the URL.

So why is the loaderInfo not loaded when the application is created? If I can’t get the URL I can’t do my configuration as there is no other event I know of which I can listen for to set the configuration.

I now dove into the Application code in the Flex framework. I soon found the _url property which is declared as mx_internal. I remembered reading Daniel R’s blog post about mx_internal and quickly set up my code to use mx_internal::_url. Success, this is set on creationComplete.

Now to ask Adobe why we don’t have access to loaderInfo until after the creationComplete event….

UPDATE: After more searching I found the FlexEvent.APPLICATION_COMPLETE event. If you try to access Application.loaderInfo.url when this event is called it is set.

Bindings to E4X don’t work as expected

Tuesday, October 9th, 2007

Our current application uses a large XML structure to send data back and forth between the frontend and backend. This is a legacy interface which was created 2-3 years ago by the developers of a Flash 6 version of the same application and has stuck with the system since then. If I had my druthers I’d use Flex Data Services to retool this into asynchronous micro-transfers to speed up the whole process but we haven’t been able to convince anyone to buy a license for FDS yet.

To get the data into and out of the XML structure I decided to try Flex’s Bindings. This would mean we’d just have to specify the relationships and whenever the values changed the data/UI would be automatically upated. This worked fine for each individual page I created but once I started running through the entire application each additional page created caused the application to slow down noticeably. By the 20th page or so the UI was nearly unresponsive when touching any element attached to a binding. Typing text into a TextInput was a laborious character-by-character process.

It was obvious that adding the bindings has caused this but at first I couldn’t understand why. Each element was tied to its specific place in the XML and so should have been firing a single binding. Looking closer I noticed that all of the bindings from the XML to the UI were getting fired *every time* a bound UI element changed.

It appears that the reason for this is that an E4X XML object fires a change event on the top-level XML object whenever anything inside it is changed and that bindings which have an E4X source fire when the top level changes. This means that every time I updated a UI element and the binding into the XML changed the value that all of the bindings *out* of the XML to the UI were fired, causing a huge slowdown.

I ended up writing the “bindings” as simple “=” statements and calling them when a page is navigated to or away from. This introduced extra work to make sure these happen at the right time, but it’s far faster and will be simpler to maintain given the structure of the code.

Only one Validator per element??

Tuesday, October 9th, 2007

Further work with Flex Validators has lead me to find yet another limitation. You can have only one Validator per element. If you attempt to apply multiple Validators for one element you end up with the last one fired usually taking precedence as its errorString and valid/invalid events are the last set/fired. I do see the framework limitations making this happen but it is still very frustrating to not be able to combine Validators to their full potential. Things get even worse when you attempt to use a single-field validator and a multi-field validator on one element. This leads to nasty work-arounds which are nearly as bad as rewriting the validation code manually. I’ve filed two bugs with Adobe, SDK-11973 and SDK-11974.

RadioButtonGroup is not an IValidatorListener

Tuesday, October 9th, 2007

While building out a new framework for a series of highly form-centric applications in Flex 2 I ran into a strange problem. Seeing as I’m now using Flex I wanted to do things the right way and use a Validator to make sure that a value was selected. Imagine my surprise when the validation didn’t seem to happen. After some debugging and tracing through the Flex framework’s code I finally found that the Validator was firing and getting the correct result but failed to set the errorString property or fire the invalid event on the RadioButtonGroup being validated. Further tracing lead to the problem. The RadioButtonGroup was failing a test for “is IValidatorListener”. In other words, the RadioButtonGroup, which is conceptually a form element, does not respond at all to the events fired by a Validator.

Eventually through documentation and perusal of the RadioButtonGroup code I also realized that the RadioButtonGroup is not a UIComponent. This is understandable as the concept of a RadioButtonGroup is not linked to a specific layout of the radio buttons and the “group” really has no set physical presence. This explains why the IValidatorListener interface isn’t implemented in the same way as the other form elements as the UIComponent base class implements this for most of them. It doesn’t explain why the RadioButtonGroup does not implement it itself, however.

Of course you can always set the listener on the Validator to one of the radio buttons but I’d rather have all of the radio buttons show the error to let the user really know what’s happening.

To this end I created a RadioGroup class which implements IValidatorListener and sets the errorString and fires the valid/invalid events on each of the radios within the group.