Showing posts with label coding. Show all posts
Showing posts with label coding. Show all posts

Monday, June 28, 2010

ActionScript: the htmlText, CSS and embedded fonts fiesta

Actionscript is usually great for simple font embedding and rendering purposes. Use the text property of a TextField with an embedded font and a TextFormat, and it works great. If, however, you want to get all ninja and use htmlText with CSS with embedded fonts, you're in for a bumpy ride.

Firstly, you may experience the unnerving phenomenon of text not appearing at all, as soon as you set the embedFonts property to true on the TextFormat object. Fear not, for Flash nuisances are easily tweakable. Check your css file and wherever you have more than one font enumerated in the 'font-family' property, just make it one single font name: the font you embedded. In the article linked above, adobe mention:

If using CSS styles to set fonts for TextFields, set the font-family CSS property to the name of the embedded font. The font-family property must contain a single name and not a list of names if you want to specify an embedded font.

What this might do for you is to show regular text, but completely omit formatted text (bold or italic), or simply replace it with unformatted text. If that happens, you have probably not embedded all the font faces. Read this article to find out how to embed all versions of a font (regular, bold, italic and bold-italic) within the same font family. If your embedded font already has these formatting inside the font file, try these tricks. If you're using the Flash IDE, it should be really similar. This forum thread might help.

The next problem which is very likely to occur is for the font to look aliased (i.e. blurry, hard to read). The solution is simply to create a TextFormat object with the font defined in the CSS style and assign it to the defaultTextFormat property of the TextField. Makes sense, right? No! I found this after considerable digging. Let me know if it works for you too.


Update:
if you're using multiple SWFs or RSLs and have issues with fonts, check out Alex's great post about that.

Thursday, September 10, 2009

Javascript injection from Flex into the HTML wrapper - problems with IE, of course

Here are some tips which might save someone some headaches (which you inevitably get when you start working with Internet Exploder).

First and foremost, if you want to communicate from Flex to (regular) Javascript using ExternalInterface in Internet Exploder (I was testing on version 6), you had better put an id attribute on the [object] and [embed] elements, or else it will either silently fail, or give you the wonderfully descriptive and logical error message 'null' is null or not an object. If I didn't know any better, I'd say it's rather philosophical. Oh, and it's always at character 118, line 1. I dare you to find it :)
You find this information if you read the first note on the Adobe documentation page for ExternalInterface.

When I said 'regular' earlier, I meant javascript that's already embedded in the page. Now, if you want to do nifty stuff like Javascript injection, you would probably use Abdul Qabiz's fantastic component. The reason I needed it was that our Flex application needed to be completely independent of the html wrapper it happened to find itself in, but also needed to open IFrames and move them around and do all kinds of nifty stuff (you can tell I like this word). That meant that the script would have to be embedded at runtime in the page by Flash.

Sounds doable, right? In Firefox, yes. In IE, haha, you've got another thing coming. IE and 'simplicity' have proven to be at opposite ends of the spectrum, time and time again.

I won't drone on about the specifics too much. But here are some major points to keep in mind:
For me the workaround didn't work yet... I'm trying to tweak it somehow to get it going. And it's great how you feel completely in the dark when it comes to these things, as the documentation seems to be lacking. It would have been great if IE6 had had the public bug tracking application IE7 and 8 do. But it would have probably crashed very early on, due to overuse.

Monday, August 10, 2009

Running the ftp ant task in eclipse with version 2.0 of the Apache Commons-Net library

...doesn't work!

(In case you are not familiar with running ant in eclipse, read both parts of the very good O'reilly article on that topic: part1, part2).

Now, if you want to use the ftp ant task in eclipse (which is not a core ant task), you will need to install some more java classes. Read this article for the details. However, keep in mind that you need version 1.4.1 of the Apache Commons-Net library, and not 2.0, which at the time of writing is the latest version (I'm using eclipse 3.4.0). If you use version 2, however, and you get something like this from eclipse:

Could not create type ftp due to java.lang.UnsupportedClassVersionError: org/apache/commons/net/ftp/FTPClientConfig (Unsupported major.minor version 49.0)

it means you're stubborn :). So use version 1.4.1.

UPDATE
Courtesy of Gary, a Java informed friend, here's the real reason for the error:
"The error 'Unsupported major.minor version 49.0' means that java 5 is required. Its possible that you have configured somewhere to use java 1.4 (v4).
if you make sure you have java 5 installed and configure eclipse to use this version then you should be okay."

Friday, March 6, 2009

Flash preloader mayhem. bytesTotal equals 0 or bytesLoaded and the misterious missing Content-Length header

There are times in programming when when the simplest of things turn out to be the most difficult to achieve.

I experienced this some days ago when I wanted to implement a preloader for a game I'd been working on.

After an unsatisfactory attempt at a first-frame preloader (the combination with PureMVC was to be fatal to me :), I went for the external one. Namely, there is a very small swf, which is the 'host', and which loads the actual game while displaying the loading progress. With no more fuss from PureMVC, and everything working fine, the progress bar appeared at 0%, as expected. It was good, simple and quick, like a preloader should. I happily deployed the game and test it in the browsers.

None of them worked! All of them displayed an empty progress bar, and after some seconds the game suddenly appeared. My gosh, what could it be, I wondered. I placed some strategic traces, only to learn that the bytesTotal property of the Loader.contentLoaderInfo object was either equal to the bytesLoaded property (only in Firefox), or simply 0. This was the strangest thing I'd seen in quite a bit of time...


After some extensive Googling around, I found some hints of what might be wrong. The Adobe documentation for the URLLoader class (which I had not used) mentioned that "a missing Content-Length header will result in bytesTotal being indeterminate" (nothing of the sort was mentioned for the Loader class, which I had used). This prompted me to open Charles and spy on the headers returned by the server for the loader and for the game itself. Indeed, there was a single difference between them: the game's response was missing a "Content-Length" header. Eurika!

This, in turn, called for an .htaccess file to set things straight (I was using Apache 2). I dug some more and I discovered mod_proxy_http in the Apache documentation. They mention that the variables proxy-sendcl and proxy-sendchunks are responsible for the Content-Length header, which apparently works in conjunction with an operation called 'chunking', performed by Apache when serving larger files, whereby it starts sending the file to the requester before buffering it (which would allow it to know its size), making the whole process quicker. I presently set out to alter them, by using the SetEnv command: setenv proxy-sendcl 1. I put this in the .htaccess, and I made sure the variables were set by using a phpinfo() call in a test php script. Nothing changed! Then I added the other one: setenv proxy-sendchunks 0, hoping to finally force Apache to cut it out with the chunking. Didn't work this time etiher, everything looked pretty much the same. It dawned on me at this point that I didn't know the correct values for these variables (maybe it wasn't numbers, but rather some predefined enums? the documentation didn't say). But I had already wasted too much time on a preloader and decided to call for help from our hosting company. They suggested, quite strangely, that I turn gzipping off, by using this line in the .htaccess: SetEnv no-gzip dont-vary. I was quite sceptical of the solution, because the loader swf was being gzipped by Apache anyway and it did have its "Content-Length" header where it needed it. However, surprise surprise, the preloader started working! It was smooth and silky, as I was hoping.

Now, I still don't understand what gzipping had to do with proxy-sendcl. I have sent them an email back for clarification, I will be forever grateful if they can illuminate me. And I shall undoubtedly share my findings, so keep posted - or, if you know and are willing to help, drop a comment!

I hope this saves someone some precious time.

Thursday, February 5, 2009

Pure MVC - the good, the bad and the ugly

I just finished my first Flash game built with PureMVC for ActionScript3.0 (sorry, it's a work project and not released yet).

I'm going to share some bad experiences and some good experiences about it. Let's start with the bad ones, because they're most fun to read.

As Tony says, PureMVC makes you write quite a bit of boilerplate code in the beginning. I expected that anyway, sice I had just learned the system. But it's true, it is far from a pleasant prospect to imagine having to write it again. If I will use it in the future, I will most probably copy the entire project and start changing, or even create a 'blank setup', with all the initialization code ready for ordinary applications.

One of the complications is that when sending messages through the facade (a similar publish /subscribe mechanism to Cairngorm Events), any command and any mediator can respond and act upon them (proxies can't). This makes it difficult to know who and what is doing at certain stages of the application, especially when the project is getting bigger. There is no central point to see who is doing the work at "APPLICATION_INIT", for instance, because any and all mediators can listen to this event, and that signaling code is in the particular classes (through the listNotificationInterests method). I found myself using Ctrl+H in Eclipse (which searches through all project files) more often than should be the case for a good framework (or for a programmer with good memory - I should eat more fish).

A subsequent, unforseen oddity comes to life when linking to other mediators in a mediator. I wonder if this verges on bad practice, but on a few occasions I needed to link mediators directly, and in one instance I realised I had circular referencing between two mediators. This would generally be no particular problem, but the way PureMVC recommends registering Mediators is not compatible with such referencing. Namely, you register them in sequence in the top-level ApplicationMediator, as part of an application initializing command. This means that the circular referencing will break, because the second mediator will not have been created yet when we attempt to retrieve it in the constructor of the first.
My way around this was to move the mediators registration code at the end of the application initialization and then to send a "MEDIATORS_REGISTERED" message, which could be listened by all mediators who may be in danger of circular linkage. This had the nice effect of bloating almost all my mediators' class code.

Also, when coding commands which need to wait for view components to finish animating, it becomes cumbersome when other entities (commands or mediators) need to act when that animation finishess. For instance, a card placeholder needs to change colour when the card reaches it. You don't want to lose state in the command by just registering a new command to execute at the end of the animation, because you need to use previously obtained information. You basically have to dispatch two 'messages' in the view component's mediator -> one through the facade (eg. "CARD_RECHED_DESTINATION"), for the interested mediators, and the other, a regular Flash event (for instance Event.COMPLETE). The command will then respond to the Flash event and continue its functionality. (Alternatively you can dispatch the facade message in the waiting command; but what if that animation is at other times triggered by different commands as well? You still need the message to be sent out...).

Now moving on to good things.

What's cool is that once you've gone through the initial scaffolding, it is very easy to add bits of functionality in the application. That is, if you leverage copy-paste, because something like _cardsMediator = CardsMediator(facade.retrieveMediator(CardsMediator.NAME)); is not fun to write 5-10 times per class. Also, the linking between visual components becomes a breeze, because most of the times they will respond to existing notifications.

Also, if I am to think about my application generally, I feel it is very solid, robust. I have had very few bugs caused by my misusing the framework, so from this point of view PureMVC does not stand in your way.

Will post back with more insights.

Monday, May 12, 2008

How to clone (duplicate) an object in ActionScript 3

For a project I needed to clone an object of unknown type. And by clone I mean to create a new instance of that same type and then fill out all its properties (including getters and setters) to mirror the original object.

Thanks to a friend, I discovered the describeType function in AS3. But this alone will only take care of the copying part. To create an object of the same type as another one we use getDefinitionByName.

Although Flash reflection is pretty basic, with a little work it will do the trick.

Get the application files.

Here's the code:




<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" xmlns:local="*" creationComplete="init()">

<mx:Script>
<![CDATA[

import mx.controls.Alert;

private var source:DataObject = new DataObject();
private var cloneObject:DataObject;


private function init():void {

source.name = 'John Doe';
source.howMany = 4.5;
source.when = new Date(0);
source.complexProp = new DataObject();
source.complexProp.name = 'Name in sub-object';

cloneObject = UtilFunctions.clone(source) as DataObject;

Alert.show("Clone:\nname = " + cloneObject.name + "\nhowMany = " + cloneObject.howMany + "\nwhen = " + cloneObject.when + "\ncomplexProp.name = " + cloneObject.complexProp.name);
}

/**

* describeType will produce this (for a DataObject instance):
*
* <type name="DataObject" base="Object" isDynamic="false" isFinal="false" isStatic="false">

<extendsClass type="Object"/>
<accessor name="isHandicap" access="writeonly" type="Boolean" declaredBy="DataObject"/>

<variable name="howMany" type="Number"/>
<accessor name="complexProp" access="readwrite" type="DataObject" declaredBy="DataObject"/>

<variable name="name" type="String"/>
<variable name="when" type="Date"/>

</type>
*
* */

]]>

</mx:Script>
</mx:Application>


And the UtilFunctions.as file:




package
{
import flash.utils.describeType;
import flash.utils.getDefinitionByName;
import flash.utils.getQualifiedClassName;

public class UtilFunctions
{


public static function newSibling(sourceObj:Object):* {
if(sourceObj) {

var objSibling:*;
try {
var classOfSourceObj:Class = getDefinitionByName(getQualifiedClassName(sourceObj)) as Class;
objSibling = new classOfSourceObj();
}

catch(e:Object) {}

return objSibling;
}
return null;
}

public static function clone(source:Object):Object {

var clone:Object;
if(source) {
clone = newSibling(source);

if(clone) {
copyData(source, clone);
}
}

return clone;
}

public static function copyData(source:Object, destination:Object):void {

//copies data from commonly named properties and getter/setter pairs
if((source) && (destination)) {

try {
var sourceInfo:XML = describeType(source);
var prop:XML;

for each(prop in sourceInfo.variable) {

if(destination.hasOwnProperty(prop.@name)) {
destination[prop.@name] = source[prop.@name];
}

}

for each(prop in sourceInfo.accessor) {
if(prop.@access == "readwrite") {
if(destination.hasOwnProperty(prop.@name)) {
destination[prop.@name] = source[prop.@name];
}

}
}
}
catch (err:Object) {

;
}
}
}
}
}

Sunday, April 20, 2008

Funny quotes

I thought I'd share some nice quotes I keep saving online (using the eSnips toolbar).

  • It's OK for you to make noise. Otherwise, we feel like we are fucking a ninja (Craigslist)
  • Cel mai necinstit lucru, in viatza, este modul in care aceasta se termina. Adica viatza e grea si-tzi ocupa tot timpul. Ce capetzi la sfarshitul ei? O moarte. Asta ce-i, un bonus??? Eu cred ca ciclul vietzii e de-a-ndaratelea. Ar trebui intai sa mori, apoi sa mergi intr-un azil de batrani. Esti dat afara de acolo pe motiv ca esti prea sanatos, te duci, iti iei pensia, apoi, cand incepi sa lucrezi, primeshti un ceas de aur in prima zi de lucru. Munceshti patruzeci de ani pana devii suficient de tanar. Te apuci de baut, mergi la show-uri, si esti gata pentru liceu, apoi scoala primara, devii copil, te joci, n-ai responsabilitatzi, devii bebelush, apoi itzi petreci ultimapoi itzi petreci ultimele noua luni plutind cu toate facilitatzile dupa care termini totul printr-un orgasm (mass mess)
  • Of course, if they have time machines in the future they'll probably have a separate reference manual just for Cambridge. This has always been a fussy place, a town of i dotters and t crossers, where you're liable to get both your grammar and your ideas corrected in the same conversation. (Paul Graham - What you Can't Say)
  • I've seen occasional articles about how to manage programmers. Really there should be two articles: one about what to do if you are yourself a programmer, and one about what to do if you're not. And the second could probably be condensed into two words: give up. (Paul Graham - Great Hackers)

Friday, March 21, 2008

How to get the Class of any Object in ActionScript 3 and Flex

Here's a small trick I recently learned. It's very helpful in some situations.

If you need to know the class of a random object:

private function getObjectClass(obj:*):Class {
var className:String = getQualifiedClassName(obj);
var classOfObj:Class = ApplicationDomain.currentDomain.getDefinition(className) as Class;

return classOfObj;
}


And creating another instance of that object is just a step forward:

private function newInstanceOf(obj:*):Object {
var objectClass:Class = getObjectClass(obj);

if(objectClass) {
return new objectClass();
}

return null;
}



Notice: this last trick will work only if you know for sure that the constructor for those objects don't need any parameters (either have none defined, or all have default values). If you're not sure, consider wrapping the code inside a try-catch block. If, however, you know that the constructor will require arguments, please tell me how you solved this, I'm still thinking about an elegant solution.

Here's a full working example written for Flex3.

Hope it helps.

Friday, January 11, 2008

My first haxe project

Today I started work on my first haxe project (first after "hello world", that is). It is (will be) a website which will show all the events in the town I live in at any given time.

Working in haxe (the neko part) seems to be surprisingly straightforward. Although it didn't simplify the work needed a lot more than php does, for instance, haxe has more appeal to me; it appears lightweight, while php seems heavy. It kept me up until this hour and I'm eager to learn more.

However appealing though, I will refrain from using haxe for the javascript part. I have come to this decision after quite a heated debate with myself. The reasons:

  • First, it's a pretty small project, at least at the beginning. We want to get it out as soon as possible and then build features on it as it grows.
  • Second, although haxe itself is easy to use, it only offers the basic functionality as javascript is concerned. It cannot be compared to a javascript framework such as prototype or extjs. I don't expect that from it either - it's not meant to be such a library (yet, I hope). I also thought about integrating haxe for js and one of these frameworks, but it's too complicated for what I need right now. Maybe in the future.
  • Third, I want to learn extjs :)
I want to have a word with the author of hxBlog, maybe I can learn some things quicker and skip some trial and error iterations :) After having studied the source code that is (it's there, on the website, in case you're interested).

Saturday, October 20, 2007

Lisp is alien. Cool!

On hearing a statement that anything in a Lisp program is recursive (which I though was an exaggeration), I opened up its respective Wikipedia page and started reading.

The article is merely meant as an overall introduction to the language (just as I expected), and that's pretty much what I got. What I was left with upon finishing the article was that Lisp is all about lists - all the examples involve them, although they do say in one place that
Because conses and lists are so universal in Lisp systems, it is a common misconception that they are Lisp's only data structures. In fact, all but the most simplistic Lisps have other data structures – such as vectors (arrays), hash tables, structures, and so forth.
I assume therefore that when you want arrays, or other data structures, you write them as lists too. Strange.

Here's something interesting I found out on the same page:
The now-ubiquitous if-then-else structure, now taken for granted as an essential element of any programming language, was invented by McCarthy for use in Lisp, where it saw its first appearance in a more general form (the cond structure). It was inherited by Algol, which popularized it.

Now, for someone coming from such programming languages as Java, ActionScript, or C (which they all inherit, to some extent), a lisp program is hideously difficult to read.
I suppose I should learn Lisp, but it seems so foreign. (Paul Graham, '83)

You've read my mind there, Paul. However, it's all the more incentive for me to learn it. But not just now, I'm still tinkering with Java (I'm learning it in paralell to ActionScript development). I wonder how long it takes to get used to reading Lisp. I mean, there were some examples spanning 4 lines and they took me the equivalent of a 50 lines class in any of the above languages. In any case, I'm almost positive (although it's more of a hunch than a documented certainty) that Lisp is more difficult to read through than Java, for instance, for equally advanced programmers in the respective languages. But it seems that it's also shorter, so there's a chance that the overall lecture of a source code might be shorter for Lisp. I wonder...

I might get some answers from Paul Graham's articles - I've seen he has one where he compares Lisp to other major programming languages, which must be an interesting lecture.

In any case, the article got me interested. It is so different from anything I've wrote code in that I'm attracted to it - it might be similar to going back to the point where people invented the wheel and then inventing something else, completely different, paradigim-wise. It might be a good chance to expand my programming horizons and simply to try something totally new.

As for my recursion issue, the answer is that not everything in Lisp is recursive:
Programmers in the Scheme dialect often express loops using tail recursion. Scheme's commonality in academic computer science has led some students to believe that tail recursion is the only, or the most common, way to write iterations in Lisp; this is incorrect. All frequently-seen Lisp dialects have imperative-style iteration constructs, from Scheme's do loop to Common Lisp's complex loop expressions.
[...]
Lisp syntax lends itself naturally to recursion.

Thursday, October 11, 2007

The 'this' keyword - a plea for revival

Give 'this' a chance!

I'm here to make a point for the revival of the use of the keyword 'this' in programming (in the languages where it exists, that is).

But first of all, why revival? Is it dead, extinct, forgotten? I certainly hope not. But I think it's falling in disgrace in the programmer community.

I'm an ActionScript programmer myself and last night I was reading 'Essential ActionScript 3.0', by Colin Mook (which book, by the way, I received from what I believe was the first Romanian Flex Camp - thanks, guys). There was an entire subheading dedicated to the use or omittance of the keyword this (strangely named 'Omitting the this keyword'), and the main idea I got from it was that since the compiler is smart enough to detect member variables even when this is omitted, then why should programmers go through all the trouble writing it?. Their supporting argument was that writing this 'can be laborious and can lead to clutter' and that a this-free code 'improves readability'. To this point I was already pretty annoyed witht their reasoning; next came the only reference to the quasi-positive aspects they see in using this: 'However, some programmers always prefer to use this simply to distinguish instance variables and instance methods from local variables'. Not cool!

This having been said, here are my arguments for the use of this:
  • it's compiler friendly
As Colin explained, when encountering an identifier, the Flash / Flex compiler starts to look for matching variables or functions in this order: parameters passed to the currently executing function; locally declared variables; nested function (function within function); instance variables or methods. This means that when you omit the this keyword, the processor goes through 3 redundant cycles until it finds the instance variable or function which you referenced. It's that simple. This is pretty similar to simplifying constants as much as possible (such as writing 2.5 in the source code instead of calculating 5 /2), because when you take the time to type this, you are actually skipping three useless checks, thereby improving the speed of your application, even if by a meager margin.
  • using this is [usually] more readable than not
I can imagine that this is probably a pretty bold statement, but I think it's true, for the following reason: when you read a piece of code yourself, whether it's yours or not, and stumble upon an identifier, your brain does pretty much the same thing the compiler does: checks whether the identifier is a function or variable (you understand that from context), then looks to find whether it's local (passed as an argument or defined in the function - it's important to note that unless the identifier is familiar to you, you will actually move your eyes above the current line, scanning for a local instance declaration, until you find the function signature and check that too - which, needless to say, is time consuming) or whether it's an instance member (in which case you usually hit Ctrl+Home and check to see if the identifier is a member of the current class). Yes, this can be pretty quick for small classes and functions, but when an instance function spans for 20 or so lines and the class has many instance variables (for me this is not a rare occasion) and at a given point you see the line 'index = oldIndex;' for example, you have to start digging for scope and parenthood. Who is index and who is oldIndex, is any of them an instance variable and so on. Had the line been written 'this.index = oldIndex' (and had the convention been applied that all identifiers which don't have a 'this.' attached to them are local), you would have just moved on, as both variables' scope would have been obvious.

Ok, and what about the supposition that writing this all the time 'can be laborious and can lead to clutter'? What's interesting is that there is a certain similarity between this and public - they're both self-understood, aren't they? Yet, as much as I know, almost no-one omits public. Why might that be? Why would people go through the trouble of writing something which is self-understood? I think it's that because it saves you a brain cycle - you don't have to go through thinking that 'if the scope identifier is missing, then it must be public, since that's the default'. And my contention is that the same applies for this. It speeds up reading and clearly specifies parenthood and scope. As for clutter, I think it's quite a trivial argument - there are 5 extra characters. Indeed, when using many instance variables on the same line it might lenghten it to some extent, but I think - and this is actually my overall contetion - that the benefits far outweigh the costs of using the keyword this in your code.

What do you guys say about this? I'd love to hear about your coding practices.