kelvinluck.com

a stroke of luck

Dynamic shared fonts in Flash


Shared fonts in Flash have always promised a great deal but failed to deliver due to a confusing and buggy implementation.

Recently I built a site which made extensive use of shared fonts. To make the site load smoothly it is made up of a number of swfs – one for each section. And rather than embedding Helvetica Nueue Bold Condensed (the font used for navigation and headings) in each swf I used a shared font. This means that the 17kb of font information is only loaded once and is then cached and shared between swfs. This seemed to work exactly as advertised with none of the bugs I remember from previous attempts – maybe something was fixed in the Flash Player?

So far so good. But then I ran into a problem… The site is available in a variety of locales including Russia and Poland. These require different versions of the font (the Cyrillic and Central European respectively). The problem is that Flash doesn’t provide a way to dynamically choose a shared font library to load – the location of the shared font is hard coded in the library item in your FLA.

So what do you do? Abandon shared font libraries and dynamically load a different font swf dependant on the locale and use actionscript to apply a text format referencing the correct font to all of the relevant text fields? Pay for the Shared Fonts Manager? Neither seemed like a nice solution so I tried something else…

Instead of pointing your shared font directly to an swf you instead point it to a serverside page (of the technology of your choice – the site above uses .NET while the example below uses PHP). This page reads the current locale from a cookie and passes the correct font swf back based on this value. Surprisingly enough this seems to work perfectly and allows Home of HD to work across different locales while providing only the necessary font to each user.

An example is probably worth a thousand words so you can see this technique in action and download the source files if you want to see how it’s done.

The only other issue is that you want your fonts to show up while developing. No problem. Just rename the default font swf file to the name of the serverside script (e.g. fonts.php in my example) and magically it works. Just remember not to overwrite your actual serverside script with this dummy one when you upload your changes!

Update

While writing this article and looking for links about shared fonts I stumbled across a post by Mario Klingemann where he suggests this exact technique. Back in 2003! Since I already wrote the examples and article I thought I might as well publish it but kudos to Mario for coming up with the idea years before me!



Automatically generating exclude.xml files


I’ve recently been working on a project where a number of swf’s use common classes. The initial swf loaded contains most of these classes but so do the child swfs it loads into itself. This is because they need to be able to call methods in and dispatch events to classes in the main swf. Importing the classes gives me compile time type checking and auto complete (in FDT – my editor of choice).

So I discovered excude.xml files. These allow you to specify classes which you don’t want to be compiled into a given swf. Since all AS2 classes live in the _global scope you can share them between different swf’s. So if your initial swf includes a class that you use in a child swf you load into it then compiling that class into the child swf is redundant.

exclude.xml files are easy enough to understand – simply create a file with the same name as your fla but with _exclude.xml added on (e.g. nav.fla would have an exclude file called nav_exclude.xml) and in it list all the classes you want to exclude from compilation into that swf.

The problem with exclude.xml files is when a class you are excluding has a dependency on other classes the dependant classes aren’t automatically excluded. And manually figuring out the dependency tree in any non-trivial application is tricky to say the least. So what we need is a way to find all of the classes which are included in a given swf. You can then use this to generate an exclude list for any other swfs that will be loaded after it.

I found a program which sounded like they might do just that: sexieR on OSFlash. Unfortunately I got put off by it’s requirements and and didn’t get around to finding out if it could do what I wanted.

Then I realised I could generate the exclude list very easily myself from Actionscript! Since all classes are instantiated as Objects in the _global namespace we can simply recursively loop over this namespace and note all the classes we come across. So I wrote my “IncludedClasses” class, which does the above and outputs a string for you to copy and paste into an exclude.xml file. You simply have to temporarily include this line in your “master” fla (the one which contains the classes you want to access from other flas):

trace(com.kelvinluck.util.IncludedClasses.getInstance().getExcludeXml());

Then in the output window you will find a string which you can copy and paste into an XML file with the correct name and then – bobs your uncle – you’re sorted :)

The IncludedClasses class is shown below or you can download it here.

/**
* Class: IncludedClasses
*
* @author KLuck
*/

class com.kelvinluck.util.IncludedClasses
{
   
   private static var instance:IncludedClasses;
   
   /**
   * Private constructor - Singleton
   **/

   private function IncludedClasses()
   {
     
   }
   
   function getExcludeXml():String
   {
      var classes:Array = _arrayUnique(_getClasses(_global, '', []));
      var r:String = '<excludeassets>' + newline;
      for (var i:Number=0; i<classes .length; i++) {
         r += '<asset name="' + classes[i] + '">' + newline;
      }
      r += '</classes></excludeassets>';
      return r;
   }
   
   function getArrayString():String
   {
      var r:String = '["' + newline;
      r += _arrayUnique(_getClasses(_global, '', [])).join('", "');
      r += '"]';
      return r;
   }
   
   private function _getClasses(obj:Object, path:String, classes:Array):Array
   {
      var ret:Array = [];
      for (var name:String in obj) {

         if (typeof(obj[name]) == 'function') {
            var firstLetter:String = name.substr(0, 1);
            if (firstLetter.toUpperCase() == firstLetter) {
               classes.push(path + '.' + name);
            }
         } else {
            var passPath = path == '' ? name : path + '.' + name;
            classes = classes.concat(_getClasses(obj[name], passPath, classes));
         }
      }
      return classes.concat(ret);
   }
   private function _arrayUnique(a:Array):Array
   {
      var o:Object = {};
      for (var i:Number=0; i<a .length; i++) {
         o[a[i]] = true;
      }
      var r:Array = [];
      for (var i:String in o) {
         r.unshift(i);
      }
      return r;
   }
   
   
   /**
   * @return singleton instance of IncludedClasses
   */

   public static function getInstance():IncludedClasses
   {
      if (instance == null)
         instance = new IncludedClasses();
      return instance;
   }
   function toString():String
   {
      return '[com.kelvinluck.util.IncludedClasses]';
   }
   
}

So simply run this script in your “master” fla (or library fla) and then create exlude files for all your “slave” fla’s. In the project I’m working on this knocked 30-40KB of each of the included swf’s which makes it definitely worthwhile.



Flash bug when printing fonts anti-aliased for readablitiy


I just came across an annoying bug in Flash running in a browser which appears when you use PrintJob to print a TextField with embedded fonts where “anti-alias for readability” is selected… The bug manifests itself by drawing a big green box behind these TextFields.
Since a google around didn’t seem to reveal anything I thought that I would make a note of the problem and my solution (such as it is) here.

The Problem
The problem is exhibited in the swf embedded below:

When this is playing in a browser (I tried IE/PC and Firefox on Mac and PC with the Flash 9 player) and you press the print button your printout will looks something like this:

Displays the green box Flash has added behind the text

Hmmmm! Where did that big green box come from?

If you want to recreate this problem yourself you can download the files from this example here. Bear in mind that the bug doesn’t manifest itself when you are testing from the Flash IDE. I’m not sure if this is because it is a bug in the Flash 9 player or in just in the player when it is running in a browser…

The solution
Not much of a solution but as you can see in the test above this bug only bites when you are printing an embeded font which is set to “anti-alias for readability”. So the way to avoid the problem is not to select this method of anti aliasing when you are embeding fonts and printing a movieclip.

Hopefully this page will show up in google and will save someone else the hour I wasted trying to figure out what was going on!



Selfportraitr: An Interactive Exhibition Curating the Flickr Community


A while back I was approached by Stephen Jablonsky from the School of Visual Arts in New York. He was looking for someone to help with a project him and and his colleague Jeremy Chien were doing for the Pace/MacGill Gallery. He had come across Flashr and some of my experiments with it and thought that I may be able to help with the project.

It turned out I could! The project became “Selfportraitr”. The idea is that through ten computers in the gallery itself and through the Pace/MacGill website people can search through the thousands of photographs on flickr tagged with “selfportrait” and can choose the ones they like best to add to the gallery’s favourites. This enables members of the public to act as curators for an exhibition in a major New York gallery. More information on the app and the background to it is available in the official press release.

You can view the exhibition online using one of two applications:
  • Viewr – this application shows a slideshow of self portrait pictures. The interactivity of this application is limited to adding passing images to the gallery favourites.
  • Selfportraitr – this is the full on application as it appears in the gallery. It was designed for display on the Apple 23″ cinema displays in the gallery at a resolution of 1920×1200 so unless you have a massive screen it may appear a bit cramped and some text may be tricky to read. But you will get to play with the full functionality of the app and hopefully find some nice photos :)

This project was featured on the flickr blog, the New York Times (registration required) and even on ABC news which is pretty cool. It also sparked some controversy on the Flickr Central discussion board although in general people seem to appreciate what it is doing.

I built the app in Flash 8 using the bleeding edge version of Flashr. As you will have seen, some of the functionality of the app is pretty advanced and creating this app led to a number of bug fixes and enhancements to the Flashr code. A good by-product of this is that now the long awaited 0.5 release is within sight. It was also interesting to collaborate internationally across time zones on a project as complex as this and all things considered it went remarkably smoothly.



Flash 8 enhanced stroke bug


Update:

This is a very old page imported from my previous blog. If there is missing content below or anything that doesn’t make sense then please check the page on my old blog.

When Flash 8 came out I jumped straight on the bandwagon and started using the IDE at work. Unfortunately I quickly encountered a bug which effects you when creating an swf for an earlier version of the Flash Player. At the time I was surprised that no one else seemed to be having problems with it but I quickly forgot about it when I started working on some Flash 8 projects…

Then, the other day, Scott Fegette from Adobe posted about the problem and I suddenly remembered. And as luck would have it the next day I was working on a little Flash 6 swf and ran into the problem again. Luckily this time I saved a simple file that reproduces the problem and I’ve sent this over to Scott. He has confirmed that he can replicate the problem and forwarded it on to the product team at Adobe. In the meantime I thought that I would post here so that other people who run into the problem can find the workaround.

The Problem
The designers I work with use Illustrator. We’ve found that generally the best way to get graphic assets from Illustrator to Flash is to choose “Export” in the Illustrator file and choose swf as the format. You can then import the generated swf into Flash (and clean it up a bit).

This has always worked fine for me. Until I started using the Flash 8 IDE…

One of the new features of Flash 8 is Enhanced strokes. These are only available if you export as Flash 8. Unfortunately, there is a bug in the IDE where it will add these enhanced strokes to your project when you import an swf (even if your publish settings are already set at flash 6).

So you create a new fla and set the publish settings to Flash 6 (following best practices as outlined by Scott). You then import your Illustrator swf. Now press Ctrl-Enter to test your movie. “Enhanced stroke is not supported in this player”. D’OH!

Note that the problem is not with the swf created by Illustrator. As we shall see, you can import the same swf into an earlier version of the Flash IDE without any problems… The problem is with the import process in the Flash 8 IDE.

If you want to see this in action then you can download my simple Illustrator file and try it out.

The workaround
I have only managed to find one workaround for this problem so far. It is simple but a little annoying. Basically, you can import the Illustrator into a previous version of the Flash IDE (I still have MX2004 installed luckily). You can then save it as an fla which you can open from Flash 8 and do what you like with. No enhanced strokes. Yay!

Hopefully MacromAdobe will fix this bug in a point release – in the meantime I hope the workaround helps someone. If anyone knows any other ways of avoiding the problem then I am all ears!