Dwarf gets new life and is now open source

 

Dwarf on Git

A recent AIR prerelease drop broke Dwarf. I’m actually not surprised, since it uses a pretty ghetto hack—displaying a transparent window fullscreen and using ‘virtual’ windows. Because Dwarf is such an integral part of my everyday workflow and it’s such a small app, I figured I could easily rewrite it within a day or two. I’ve been on such a code-sharing high, that I started a new Git repository for it where you can find my work in progress. So far, I have a single ruler working with a semi-functional Mac toolbar. Everything should be complete either tonight or tomorrow, so keep an eye out.

On a legal note, the source code is provided under the GNU General Public License (GPL), so you can reuse and modify the code all you want as long as it’s still free. If you’d like to use it for commercial purposes, let’s talk.

EventMap.mapListener bug (and fix!) in RobotLegs

 

This past week, I experienced a bug with RobotLegs where the EventMap.mapListener method would add the listener multiple times if called multiple times. Yesterday, I had some free time to dig a little deeper and managed to pinpoint the problematic code. It turns out the method didn’t check to see if the listener existed prior to adding to the array. This explains why a button click handler in my code would respond twice.

Thanks to the oh-so-wonderful GitHub, I was able to fork the repository, implement the fix, write a unit test to verify it’s safe, and find in the morning that it has been integrated into the actual RobotLegs repository—just like that. If you experienced the bug, be sure to pull the latest commit.

Now, if you’re not on GitHub, do yourself a favor and join today. In the few months I’ve been a member, I’ve met a handful of incredible developers and now feel compelled to share code when I can. Everyone benefits when you share what you know.

Introducing TwitterAspirin: an AS3 Twitter API painkiller

 

A couple months ago, I started working on a Twitter component for my current project at Adobe. I went into this knowing I’d have to finally face the beast… OAuth. Just about every well-known Twitter client out there uses Basic Auth—and for a reason. It’s easy, what the user expects, and gives your app more credibility—there’s no requirement to leave to authenticate through the browser like with OAuth.

About five or six months ago, Twitter decided to enforce the transition. From then on, any application that uses the API must use OAuth in order to see “via [your app]” on tweets published with it—otherwise, it would display “via API.” Since “via” is where apps get probably 90% of their referrals, this was a big deal. Luckily for me, DestroyTwitter existed before that time and Twitter decided not to push the change on the veteran apps. Recently, however, the bad news spread that Basic Auth would be deprecated in June. This means every Twitter app must transition to the pain that is OAuth.

After developing the MAX Companion this past fall and now the more generalized version, I found myself rewriting the Twitter component each time. After a while, the Twitter API code I wrote for DestroyTwitter began to merge with the actual implementation, so it was no longer a standalone library that could easily be used by other projects. These past few months, I’ve been learning a great deal about framework architecture and design patterns. It has led me to realize I need to start fresh.

With all that being said, I’d like introduce a library I started working on two days ago. I call it TwitterAspirin. It’s an AS3 Twitter API library that eases the pain, providing developers with a very powerful tool for communicating with Twitter. Though it’s still a newborn at the moment, I see potential already. The library is built on RobotLegs and uses AS3 Signals instead of events. It’s hosted on GitHub, so the source code will always be available to the public. And, after last night’s commit, its OAuth functionality is complete. Here’s how to use it:

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
package {
	import com.destroytoday.twitteraspirin.Twitter;
 
	import flash.display.Sprite;
 
	public class Test extends Sprite {
		// set application consumer key and secret
		public var twitter:Twitter = new Twitter(consumerKey, consumerSecret);
 
		public function Test() {
			// add signal listeners
			twitter.oauth.requestTokenSignal.add(requestTokenHandler);
			twitter.oauth.accessTokenSignal.add(accessTokenHandler);
			twitter.oauth.verifyAccessTokenSignal.add(verifyAccessTokenHandler);
		}
 
		// click the 'Authorize' button to get the request token
		protected function authorizeClickHandler():void {
			twitter.oauth.getRequestToken();
		}
 
		// upon receiving the request token, open Twitter in the browser to authorize
		protected function requestTokenHandler(oauth:OAuth, token:OAuthToken):void {
			navigateToURL(new URLRequest(oauth.getAuthorizeURL()));
		}
 
		// return with the provided pin and click the 'Activate' button to get the access token
		protected function activateClickHandler():void {
			twitter.oauth.getAccessToken(pin);
		}
 
		// upon receiving the access token, verify it
		protected function accessTokenHandler(oauth:OAuth, token:OAuthToken):void {
			oauth.verifyAccessToken(token);
		}
 
		// done
		protected function verifyAccessTokenHandler(oauth:OAuth, token:OAuthToken):void {
		}
	}
}

As you can see, it’s extremely easy to use. Not only that, it provides great flexibility. Many libraries are simple to implement, but don’t allow the developer access to certain aspects of the process. With TwitterAspirin, each method returns the loader involved with the operation, giving developers the ability to listen for errors, cancel the operation, or attain the raw API data. The library also uses loader pools to recycle instances, so you can submit a tweet and, while it’s loading, submit another—you don’t have to wait for the first operation to finish. Then, once the operation is complete, the loader is disposed and returned to the pool, which optimizes performance and memory usage.

I’m really excited to see where TwitterAspirin goes and I have nothing but great expectations. Be sure to follow along with development and fork whenever you like.

Introducing the XMLLoader class

 

I started the XMLLoader class a few months back, but didn’t post right away because it needed a lot of cleanup. Not cleanup in the sense of performance improvement or refactoring—it simply used my old programming style, full of dollar signs and underscores. If anyone remembers seeing my code in that form, I deeply apologize for the pain it must have caused your eyes.

So why an XMLLoader class?—because 99% of the data I load with AS3/AIR is in XML format. I stay far from JSON when possible because in AS3 it’s slower than a slug on its day off. XML is native and uses E4X, which lets developers navigate its information just like you would an AS3 tree. I load XML so often, I found myself copying and pasting the same code each time I’d need it—this is the clearest indicator that a class must be written.

Parsing String data to XML poses an issue that many don’t know about. I only discovered it because of the Twitter API. The API is so janked, it sometimes returns the HTML error page instead of the XML response. It wouldn’t be so bad if it weren’t for an image tag in the HTML that isn’t closed. This immediately throws an “XML parser failure: element is malformed” error. Using try/catch is the only way to avoid this. That’s why I wrote it into XMLLoader. It automatically handles the data, attempts to parse it, and, if there are any errors, the load stops and dispatches an error signal.

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
package {
	import com.destroytoday.net.XMLLoader;
 
	import flash.display.Sprite;
 
	public class Test extends Sprite {
		public var loader:XMLLoader;
 
		public function Test() {
			loader = new XMLLoader();
 
			loader.retryCount = 2;
			loader.includeResponseInfo = true;
 
			loader.openSignal.add(loaderOpenHandler);
			loader.completeSignal.add(loaderCompleteHandler);
			loader.errorSignal.add(loaderErrorHandler);
 
			loader.load("http://search.twitter.com/search.atom?q=destroytoday");
		}
 
		protected function loaderOpenHandler(loader:XMLLoader):void {
			trace(loader);
		}
 
		protected function loaderCompleteHandler(loader:XMLLoader, data:XML):void {
			trace(loader, data);
		}
 
		protected function loaderErrorHandler(loader:XMLLoader, error:String, message:String):void {
			trace(loader, error, message);
			trace(loader.responseStatus);
		}
	}
}

Speaking of signals, XMLLoader is the first class in DestroyFramework to use Robert Penner’s AS3 Signals instead of events. If you have to ask why, you haven’t been programming in AS3 long enough. Each XMLLoader instance has signals for open, complete, error, and cancel. The class also includes a retryCount property that indicates how many times to attempt to load a URL before calling it quits. Since some APIs can be down one second, then up the next, this feature really comes in handy. It’s mainly intended for handling the beloved fail whale.

The last two features include a cancel method and an includeResponseInfo property. Sure, URLLoader has a cancel method, close, but an exception is thrown if you call close when no operation is in progress. This makes sense, but the runtime shouldn’t close down shop when it happens. XMLLoader instead cancels and dispatches the cancel signal when the cancel method is called, and if no operations are in progress, it simply does nothing.

The includeResponseInfo property is an incredibly easy way to tell the loader to return the response status code and headers upon success or fail. Without XMLLoader, you could get this information with an event listener and the appropriate handler, but it’s far easier to flick a switch. In all honesty, I’ve neglected to retrieve this info using URLLoader in the past simply because it’s such a verbose process. Now that it only requires setting the property to true, I know I’ll use it more often than not.

As always, the source code is available on GitHub. Be sure to keep watch—my account will be pretty active these next few weeks.

‘Undocumented feature’ in Rob Penner’s AS3 Signals

 

bug_feature

Last week, I started replacing events in DestroyFramework with Rob Penner’s AS3 Signals. They’re faster, shorter, and include a few methods that developers have been dying for. Unfortunately, the first implementation, into my new Group class, didn’t work. I was puzzled to say the least. After literally hours of testing and debugging, I discovered the culprit.

It turns out, the remove(listener) method lacks a check for listener existence in the listeners array. When the method is called, if the index of the listener returns -1, the array splices the first listener. I forked the Git repository and implemented the fix on the Signal, NativeSignal, and DeluxeSignal classes. And because a fix isn’t a fix without proper unit testing (says Joel Hooks), I added the unit tests as well.

Where to find the right fontName

 

To preface, I embed fonts using the Embed metatag and fontName parameter with an SWF as the source. If you’re unfamiliar with this method, it looks like this:

1
2
[Embed(source="assets/fonts.swf", fontName="Helvetica")]
protected static const HELVETICA:String;

This past week, I came across the same issue twice. Up until now, I only worked with fonts that used the fontName as it appears in Flash’s properties panel. Sure, this works for fonts with simple names, but when you start getting fancy, things get messy. I needed to embed Alternate Gothic No. 2 and Flash labeled it as “AlternateGothic” with “No2″ as the style. I set the fontName as “AlternateGothic No2″ and was presented with this familiar gem:

fontname_error

I get shivers each time I see it. After a few minutes of failed guess and check, I set out for a solution. I opened FontExplorer X and discovered that the font is labeled as “AlternateGothic-No2″.I gave it a shot and boom went the dynamite. From then on, I thought that would be the correct fontName—the font’s label in Font Explorer X.

fontname_fontexplorer

I was wrong. This week, I needed to embed Helvetica Neue Roman, which is labeled as “12 pt Helvetica* 55 Roman 05472″ in FontExplorer X—freaky, eh? I tried it out and the error returned. At first, I was bummed because I thought I had a foolproof solution. I was close, but no cigar. I opened Font Book to get a second opinion. Apparently, the font’s true name is “12 pt Helvetica* 55 Roman 05472″, which means FontExplorer X removes redundant whitespace, found in our example between “Roman” and “05472.” I tried it out and, sweet sassy molassy, it worked.

fontname_fontbook

From now on, I’ll consult Font Book when embedding a new font.

Introducing the AsyncLoop class

 

Out of my recent work, I’m especially proud of and excited about the AsyncLoop class. It’s a serious performance enhancer that takes heavy processes and spreads them out over time, preventing stalls and possible lockups. I originally wrote it to deal with a for loop that contained a complex process and iterated 1000 times. Needless to say, the beach ball made an extended stay each time the loop ran. After implementing AsyncLoop, the beach ball disappeared and animations played smooth throughout.

AsyncLoop works around a timer limit. The developer sets the maximum number of milliseconds to loop through the process function. Once the timer exceeds that limit, it carries over to the next frame and repeats. The loop can be ended a number of ways, providing great flexibility. A limit can be placed on the loop count, mimicking common for loop usage. The loop can return the AsyncLoopAction.BREAK constant. When using that method, AsyncLoopAction.CONTINUE is used to tell the loop to continue to the next tick. Each loop provides analytics, keeping track of its duration, loop count, and frame count. Here are two ways you can use it:

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
// new AsyncLoop(callback:Function, countLimit:int = -1, timerLimit:int = 20);
var loop:AsyncLoop = new AsyncLoop(tick, 1000);
 
loop.addEventListener(Event.OPEN, loopOpenHandler);
loop.addEventListener(Event.CHANGE, loopChangeHandler);
loop.addEventListener(Event.COMPLETE, loopCompleteHandler);
 
loop.start();
 
function tick():void {
	// heavy process
}
 
function loopOpenHandler(event:Event):void {
	// loop started
}
function loopChangeHandler(event:Event):void {
	// loop carries over to next frame
 
	trace(loop.duration); // incomplete loop running time
	trace(loop.currentCount); // number of callback calls
}
function loopCompleteHandler(event:Event):void {
	// loop complete
 
	trace(loop.duration); // completed loop duration
	trace(loop.frameCount); // frames needed to complete
}
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
var loop:AsyncLoop = new AsyncLoop(tick);
 
loop.start();
 
stage.addEventListener(MouseEvent.CLICK, clickHandler);
stage.addEventListener(MouseEvent.DOUBLE_CLICK, doubleClickHandler);
 
function tick():String {
	// heavy process
 
	if (loopShouldEnd) {
		return AsyncLoopAction.BREAK;
	}
 
	return AsyncLoopAction.CONTINUE;
}
 
function clickHandler(event:MouseEvent):void {
	if (loop.running) {
		loop.pause();
	} else {
		loop.start();
	}
}
function doubleClickHandler(event:MouseEvent):void {
	loop.cancel();
}

I’m really happy with the class and how far it has come since its original form as fLoop. As always, the source code is on GitHub, so take it and run! If you find it useful, feel free to share how you used it, or simply let me know what you think.

Introducing the ApplicationUtil class

 

Yesterday, during my weekly football “service”, I spent a few minutes starting the ApplicationUtil class. So far, it consists of only two methods, getVersion and closeOpenWindows. The first accesses the application descriptor and returns the application’s version. closeOpenWindows is a necessity I learned in the Apollo days from Christian Cantrell. I had issues with my first AIR app, DestroyFlickr, where it wouldn’t quit, even if all of the visible windows were closed. I commonly use window visibility to show/hide utility windows, so the invisible ones were hanging around, keeping the app open. This method runs a quick loop to close all open windows, visible or not. It also includes an andQuit argument that, when true, sets autoExit to true, which quits the app upon close of the windows. Here’s some unnecessary example code to give this post more character:

1
2
3
4
5
6
7
8
9
10
var version:String = ApplicationUtil.getVersion();
trace(version); // v1
 
trace(NativeApplication.nativeApplication.openedWindows.length); // 3
ApplicationUtil.closeOpenWindows();
trace(NativeApplication.nativeApplication.openedWindows.length); // 0
 
// suppose three windows are open again
ApplicationUtil.closeOpenWindows(true); // closes windows and quits before trace is called
trace(NativeApplication.nativeApplication.openedWindows.length);

Introducing the Scale9Bitmap class

 

scale9bitmap

The Scale9Bitmap class applies a scale9Grid to a Bitmap. It takes advantage of a technique I used for DestroyTwitter’s window drop shadow, scaling nine Bitmap instances. When developing the MAX Companion, I tried Didier Brun’s ScaleBitmap class, but discovered a costly memory leak in which it instantiates a new BitmapData instance with every resize call. This wouldn’t be a big deal for a once-and-done resize, but as a window drop shadow, memory skyrockets.

I decided to start from scratch and develop a class that is super fast and slim as can be. The Bitmaps are only updated when the BitmapData is set. After that, the only process that takes place is the resizing of each Bitmap—no BitmapData manipulation needed. Setup requires a single method to set the BitmapData and the Rectangle that indicates the stretchable portion of the Bitmap. BitmapData can be changed on the fly and there is a scale property that sets both scaleX and scaleY.

The source code is on GitHub, so feel free to give it a whirl.

Introducing the Console class and debug package

 

I realized I need a more…official…way of debugging my apps, so I wrote the Console class. It’s primary function is to record activity to a specified log file. So far, I have a few methods that write entries—success, error, cancel, and print. I definitely plan to add more, but these are the main ones I intend to use in the near future. Since the name “trace” is off limits in AS3, I referenced my PHP background and named the trace method, “print”.

The class also includes the ability to automatically trace entries to Eclipse’s console along with writing them to a file. Files are written asynchronously, but I also added a delay property that combines entries, so the writing process is less likely to slow down the app. Taking advantage of AIR 2.0’s UncaughtErrors feature, the Console automatically logs fatal errors and their stack traces, if possible. Here’s an example of its usage:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
var path:String = File.applicationStorageDirectory.nativePath;
 
// params: log file path, LoaderInfo
// automatically writes a session start entry to the log
Console.init(path, loaderInfo);
 
Console.delay = 1000;
Console.traceError = true;
 
// params: id, message
Console.success("wp post", "wrote blog post");
 
// params: id, message
Console.error("wp post", "previous post was depressing");
 
// params: id, message
Console.cancel("Christmas", "why would you want to do that?");
 
// params: message
Console.print("this is a test");
[Fri Dec 18 00:31:31 GMT-0500 2009] Session Start
[Fri Dec 18 00:31:31 GMT-0500 2009] [success] [wp post] wrote blog post
[Fri Dec 18 00:31:31 GMT-0500 2009] [error] [wp post] previous post was depressing
[Fri Dec 18 00:31:31 GMT-0500 2009] [cancel] [Christmas] why would you want to do that?
[Fri Dec 18 00:31:31 GMT-0500 2009] [print] this is a test

I do expect to build the class over time, eventually adding TextField support. In the meantime, the source code is available on GitHub.