Passing Custom-Classed Parameters to AMF (PHP)

I spent a day or two pulling my hair out and wondering if AMFPHP should be considered abandon-ware (no). I could get data to go back-and-forth. That part was pretty easy. But I wanted to pass a custom configuration object to the server as part of my request and couldn't get any further than it showing up in PHP as an anonymous array.

I gave up, installed the Zend framework (which now includes an AMF implementation), and had similar (although slightly different) issues. After resorting to Charles to figure out what might be going wrong, I found the problem in my remote service class. It turns out my PHP chops were coming up short.

There are a bunch of AMF examples and tutorials out there, and I feel like I looked at most of them ; ) Very few talk about sending custom-classed parameters to the server. Instead, they show you how to pass numbers and strings (if anything at all). The best of these test-your-gateway examples have you send your parameter object to the server as an array. In php, you'd access those (array) properties like this: $config['myParam'].

However, if you've got mapping between Actionscript and PHP classes properly configured, that syntax isn't going to work. Actionscript lets you access an object's child properties via either 'dot syntax' or 'array syntax', but PHP is more picky.

Once you get your custom class mapping working, you need to access (class) properties like this: $config->myParam. Simple to be sure.

So, I thought I'd tried this (and every other syntax combination), but apparently not while I had the class mapping setup correctly. PHP errors in your AMF service class can be notoriously hard to debug. Most of the time when something went wrong with mine, I simply never got a response. But, once I fixed my service class, I could use either Zend or AMFPHP. Rock on.

You may remember my article on scrollRect and getBounds().

Colin Moock just posted a bitmap-based solution. Slower, but very, very effective.

This is foremost a note-to-self. That enticing entry in the ActionScript API for TextField events that looks like you ought to be able to detect changes to the text or htmlText property? That's not how it works. It's for TextFieldType.INPUT fields only. As the user makes changes, the event will fire, but for everything else, you're on your own. I keep managing to forget this and architecting things inappropriately as a result.

Mapping TextFormat Ranges

There are several reasons you might want to know where one TextFormat ends and another begins. If your application supports any HTML authoring, you'll likely need something like this, even if your HTML support is fairly basic. I've been working on a font loading management utility, so I needed something to detect which portions of the text use which font. Once I have this, I can use Font.hasGlyphs to determine whether I need to load a deeper subset of glyphs or can get away with a more minimal unicode range. (You can quit drooling. That code will be posted here when it's ready.)

Doing this requires two classes. The first determines whether two TextFormat instances are equal.

  1. package {
  2. import flash.text.TextFormat;
  3. public class TextFormatUtil {
  4. public static var defaultPropertySet:Array /* of String property names */ = ['font', 'size', 'color', 'underline', 'bold', 'italic', 'url'];
  5. public static var fontOnlyPropertySet:Array /* of String property names */ = ['font'];
  6. public static function equals (f1:TextFormat, f2:TextFormat, propertySet:Array=null)
  7. {
  8.   if (propertySet == null)
  9.   {
  10.     propertySet = defaultPropertySet
  11.   }
  12.   var match:Boolean = true
  13.   for (var i:String in propertySet)
  14.   {
  15.     var prop = propertySet[i]
  16.     //trace (i + " " + prop + " " + f1[prop] + " " + f2[prop])
  17.     if (f1[prop] != f2[prop])
  18.     {
  19.       match = false
  20.       break
  21.     }
  22.   }
  23.   return match
  24. }
  25. }
  26. }

Easy enough. Now, you could just walk through each character in the TextField one at a time testing for TextFormat equality. But that's really inefficient. Instead, I implemented a binary search.

  1. package {
  2. import flash.text.TextFormat;
  3. import flash.events.Event;
  4. import flash.text.TextField;
  5. public class TextFormatMapper {
  6. private var charsInTextFormatAtIndex : Array /* of int */;
  7. private var textField : TextField;
  8. public function TextFormatMapper() {
  9. }
  10. public function setTextField(tf:TextField)
  11. {
  12.   textField = tf
  13.   textField.addEventListener(Event.CHANGE, onTextFieldChanged)
  14. }
  15. protected function onTextFieldChanged (event:Event) {
  16.   mapTextFormat()
  17. }
  18. public function mapTextFormat()
  19. {
  20.   charsInTextFormatAtIndex = new Array()
  21.   var startIndex = 0
  22.   while (startIndex < textField.text.length)
  23.   {
  24.     var hi:int = textField.text.length
  25.     var lo:int = startIndex+1
  26.  
  27.     var format1:TextFormat = textField.getTextFormat(startIndex, startIndex+1)
  28.     while (lo < hi) {
  29.       var mid:int = Math.ceil (lo + ((hi - lo) / 2))
  30.       var format2:TextFormat = textField.getTextFormat(startIndex + 1, mid)
  31.       if ( TextFormatUtil.equals (format1,format2, TextFormatUtil.fontOnlyPropertySet) )
  32.       {
  33.         //try a larger span if possible
  34.         lo = mid //+ 1
  35.       }
  36.       else
  37.       {
  38.         //try a smaller span if possible
  39.         hi = mid - 1
  40.       }
  41.     }
  42.     var charsInTextFormat:int = hi - startIndex
  43.     charsInTextFormatAtIndex.push ( charsInTextFormat )
  44.     startIndex = hi
  45.   }
  46. }
  47. public function getCharsInTextFormatAtIndex() : Array {
  48.   return charsInTextFormatAtIndex;
  49. }
  50. }
  51. }

To use it, you create a new TextFormatMapper and pass your TextField to the setTextField method. You can see I'm automatically calling the mapTextFormat method when the Event.CHANGE fires on the TextField. For testing, I hardcoded it to only test against the font property, but you can see how to easily change this to another property set on line 44. Once it's finished, you can call getCharsInTextFormatAtIndex to get an array containing the length (in characters) of each distinct TextFormat (in this case, distinct font) encountered in the TextField.

This class will change a bit as I move forward with it, but I was really pleased to get this far.

mod_rewrite trouble

I'm going to keep my eyes open for an actual explanation for this behavior, but I thought I'd share a problem (and solution?) I ran into with mod_rewrite.

I was going about my business, doing the classic mapping of http://mydomain/subdir/var1/var2 to http://mydomain/subdir/index.php?id=var1&id=var2

I had two rules, one to handle a single variable, and another to handle two variables. The idea, of course, being to drill down to a deep link. It was working great for the single variable rule, as long as I didn't include a trailing slash. Even though my rewrite regular expression clearly stated that the trailing slash was optional. To taunt me even more, if I changed the rewrite to a redirect, it worked fine.

As it turned out, the page in question contains a frameset (I know, I know) and the frame source parameters were relative paths. Even though the page source URL had been re-written, the frame source URLs were attempting to load pages that weren't there. Changed the paths to absolute and everything works great.

Just something else to look at if you're having trouble with mod_rewrite, especially if some rules appear to work, and others don't. The frameset situation is going to be pretty rare, but the same problem might manifest with missing images, style-sheets, etc.

Smarty File Size Modifier

Here's a simple Smarty modifier that will format an integer that represents the number of bytes in a file as a human readable string.

Usage:
{$fileSizeInBytes|file_size}

Example:
{assign var=fileSizeInBytes value=10485760}
{$fileSizeInBytes|file_size}

{assign var=fileSizeInBytes value= 768000}
{$fileSizeInBytes|file_size}

{assign var=fileSizeInBytes value=303}
{$fileSizeInBytes|file_size}

Output:
10 MB
750 Kb
303 bytes

<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */

/**
 * Smarty file_size modifier plugin
 *
 * Type:     modifier<br>
 * Name:     file_size<br>
 * Purpose:  format file size represented in bytes into a human readable string<br>
 * Input:<br>
 *         - bytes: input bytes integer
 * @author   Rob Ruchte <rob at thirdpartylabs dot com>

 * @param integer
 * @return string
 */
function smarty_modifier_file_size($bytes=0)
{
    $mb = 1024*1024;

    if ($bytes > $mb)
    {
        $output = sprintf ("%01.2f",$bytes/$mb) . " MB";
    }
    elseif ( $bytes >= 1024 )
    {
        $output = sprintf ("%01.0f",$bytes/1024) . " Kb";
    }
    else
    {
        $output = $bytes . " bytes";
    }

    return $output;
}

/* vim: set expandtab: */

?>

,

Flash HTML Textfields – Kick it Old-School

Most professional-grade fonts don't register the bold & italic outlines with the same postscript name. For example, "Berthold Akzidenz Grotesk BE", "Berthold Akzidenz Grotesk BE Bold", "Berthold Akzidenz Grotesk BE Italic" So to get these to work, you've got to either use stylesheets or explicitly set the text to use the correct face.

I updated my portfolio recently, and I didn't have time to implement a new shell (unfortunately) or code the whole thing over (as much fun as that is). Nor did I feel like tracking down a bug that kept me from publishing the swf to target anything above Flash Player version 6. Yeah, 6.

There wasn't any StyleSheets class back then. Add to this my crazy text-layout-in-a-circle routine, and adding bold, italic, and link support is an absolute nightmare. But I did it, and now I can show you how.

1st, parse the html as xml and replace the <b> and <i> tags with <font face=""> expressions that will actually target the correct font. I actually wrote a class that lets you map any tag to any other tag.

Next, stick all the html in a temporary textfield and map out where all the TextFormat changes occur. I wrote another class that can compare two TextFormats for equivalence.

My text-in-a-circle code adds words one-at-a-time, effectively creating a custom word-wrap routine. However, I had trouble when I attempted to use a single TextField, so each row uses a separate one. If you're up to something like this, you have to keep track of how many characters you've already used in previous fields. At first, I was getting lots of off-by-one errors and found a carriage-return character (character code 13) kept slipping into my input. Funny, I didn't put that there...

Flash also doesn't do a great job rendering things like <b>word</b> <b>second word</b>. It likes to collapse that and the space disappears. I swapped the spaces for non-breaking-spaces (&nbsp;) Feels dirty, but gets the job done.

And remember all those posts about entity problems with HTML coming from XML? The big reason for this undertaking was so I could support links in my portfolio project descriptions. When I linked to google maps, guess what happened to the query parameter ampersands in the href ...

The code is so crufty, even I won't post it. Drop me a line and I'll send you a private peek.

Helpful Automator Workflows for Developers

I love OS X. For me, it's the ideal development platform. I primarily build web applications that run on the LAMP stack, so having a POSIX compliant UNIX like OS for my daily driver is extremely convenient. My development environment works just like the environments I deploy to, so I don't have to worry very much about platform inconsistencies. OS X is the perfect balance of elegance and power. I only wish Finder didn't suck so hard.

There are some actions I need to perform on files on a regular basis that are not supported in Finder. For example, recursively deleting files in a tree of directories, but leaving the directory structure intact. I have a code generation tool that scaffolds out a boatload of PHP classes based on MySQL database. During heavy development, I need to blow away the files on a regular basis without deleting the output directories. Finder simply cannot do this. Luckily Apple has provided a way to add Automator actions to the context menu in Finder. I put together a simple workflow to recursively delete files in a tree of folders, here is is for your convenience:

DeleteFolderContents.zip - MD5: 5d0ad832e9e998dbefd70d49f2a07b52

Unzip, and copy the workflow file to Library/Workflow/Applications/Finder/ in your home directory. If all has gone well, you should have a new option in the context menu when you right-click a folder in Finder:

Automator Workflow As Finder Plugin

Automator Workflow As Finder Plugin

Another Finder deficiency that was bugging Jon recently is the inability to copy the filesystem path of a folder in Finder to your clipboard. I put together a little workflow that does just that:

CopyPathToClipboard.zip - MD5: b64558cf3afb7aecdec63faccb5986ba

Follow the same steps outlined above to copy the workflow to the proper location.

Note that these workflows are compatible with OS X version 10.5, and will not run in Automator on 10.4 or previous systems.

, , ,

SEO Presentation for NCSU Web Developer Group

Jon and I delivered a presentation about SEO to the NCSU Web Developer Group this afternoon. If you were in attendance, thanks very much for coming to see us, we hope you found it informative. We talked about a lot of useful online resources during the presentation, all of the links are in the slide deck that we've posted for your convenience. You can download a PDF of the slides here, or view them on SlideShare

Please feel free to post comments and questions here.

ActionScript a:hover Event

The only (easy) way to do a:hover styles is to apply a styleSheet. You don't get an event though, you just get a style change from the regular <a> style to the a:hover style.

I was hoping to find a way to set the window status message like you'd get in HTML. And I did find a way, even though implementing it will mean another trip into the dark world of HTML-as-XML parsing.

If (that's a mighty big if) you know the character indexes for your link characters, you can use TextField.getTextFormat and the Enter_Frame event to determine whether the link is in one color state or the other. Now the only problem is...figuring out those character indexes. It doesn't take an ActionScript whiz to figure out that your TextField.htmlText won't match your TextField.text; depending on your tags (and your whitespace, whitespace settings, etc) finding those indexes could be a major pain ... worthy of another post.