Archive

Posts Tagged ‘actionscript’

AS3 – Object Oriented Programming – Part3

July 30th, 2011

Wow. It has been way too long since my last post. I feel like a newborn, as a standup comedian at his first important appearance in front of a big crowd having stage freight.

I’ve been working a lot and I put aside my blog, but this is it! The comeback. Haha.

Ok, let’s cut to the chase.

As stated in Part2 of this tutorial, I will talk about inheritance and some more on access specifiers.
We already saw how to create a class, what is a package, class members and methods.. But we also talked about the family of all fruits, how apples are a part of this family, and further more species of apples like Golden Delicious belong to the apples class/family.
So how do we resemble this hierarchy/inheritance (because in it’s essence apples family inherit the attributes of the fruits class, Golden Delicious apples class inherit the attributes of the apples class) in code? This is where inheritance comes in to place. In actionscript only simple inheritance is supported (like in any java like programming languages) as opposed to c++ where multiple inheritance is also available. This makes inheritance very simple and code very easy to understand on one hand, on the other hand though, it can sometimes cause trouble. But we will look into advantages and disadvantages of simple inheritance later on, after we see how exactly is inheritance depicted in code.

Let’s remember our Apple class from the previous part:

package {
  public class Apple {
    private var stones:uint = 4;

    public function Apple() {
     trace("A new apple is constructed!");
    }

    public function getStones() : uint {
        return this.stones;
    }
  }
}

Let’s create class GoldenApple that will have as base class the class Apple. For this we have to extend the class Apple. We will use the keyword extends.
So the GoldenApple class will look like this:

package {
  public class GoldenApple extends Apple {
     public function GoldenApple() {
      trace("a new Golden apple is constructed");
     }
  }
}

That’s it, we have created our class GoldenApple that extends class Apple (or inherits from class Apple, whatever you prefer to say).
We introduced the word base class. This is how a class is called if another class derives (inherits/extends – another term) from it. In our case, Apple is the base class for GoldenApple, and GoldenApple is the derived class.

This now might not look like very helpful, but in fact it is extremely helpful: we can say that an object of the class GoldenApple is of type GoldenApple, but it is also of type Apple! In fact it will have all the functionality of the class Apple, and add it’s own functionality on top of that. This helps with polymorphism, one of the principles of OOP, but we will get to them later in this tutorial. It also helps with code reusing: a trivial example, right from the name of the classes (not a real life use), we say in the class Apple that objects of this class will be apples, we don’t have to say this again in GoldenApple class, because we already know this, since it extends Apple; we only say it’s a Golden one.

Ok. Let’s look at a first example. Let’s create an object of each class and check the output.

var myApple : Apple = new Apple();
trace("myApple stones: ", myApple.getStones());
var myGoldenApple : GoldenApple = new GoldenApple();
trace("myGoldenApple stones: ", myGoldenApple.getStones());

Let’s first notice here that we call getStones methos on myGoldenApple – that’s possible because GoldenApple extends Apple (where getStones method is declared), and the method is declared public. (remember access specifiers from previous part)
The output of this is:

A new apple is constructed!
myApple stones:  4
A new apple is constructed!
A new Golden apple is constructed!
myGoldenApple stones:  4

Let’s now notice the output: the first 2 lines outputted look normal, they are created by the myApple object; we need to pay more attention to the next 3 lines – firstly there is another “A new apple is constructed!” line outputted, although we constructed a GoldenApple object!? – well that is normal, because when the constructor for a derived class is called, this in turn will first call the constructor of the base class; that’s why the first line is “A new apple is contructed!”; after the base class constructor finishes it’s execution, the derived class constructor continues to execute normally, and so it outputs “A new Golden apple is constructed!”; after that the number of stones is outputted as we instructed it to do so with the last trace call.

I should point out that stones member variable is declared private, which means it’s only accessible inside the class Apple, the deriving classes (like GoldenApple) don’t have access to it. Deriving classes can only access public and protected members and methods of the base classes.
As we said in the previous part of this tutorial, internal private public and protected are access specifiers:

  • internal – this is the default access specifier for members/methods/namespaces of a class if the access specifier is not specified; this means that the member/method/namespace is accessible anywhere inside the same package as the package the class is defined in
  • private – this means that the member/method/namespace is only accessible inside the current class
  • protected – the member/method/namespace is accessible inside the current class and by classes the extend this class
  • public – the member/method/namespace is accessible is accessible anywhere

Now let’s see another example to better depict these access specifiers:
Let’s say that we’d want to change the value of stones inside GoldenApple class like this:

package {
  public class GoldenApple extends Apple {
     public function GoldenApple() {
      trace("a new Golden apple is constructed");
      this.stones = 5;
     }
  }
}

If we’d try to compile now, the compiler will complain about stones variable being inaccessible inside GoldenApple class. And it is right, because stones is private. So to make it accessible inside GoldenApple, we could make the stones variable internal (this way anything from the global package could access it, probably not what we want), public (anything will be able to access it, again not something that we want here) or protected (only the class that declares it – Apple – and classes the extend this class have access it – GoldenApple; this is what we want).
The new Apple class will look like this:

package {
  public class Apple {
    protected var stones:uint = 4;

    public function Apple() {
     trace("A new apple is constructed!");
    }

    public function getStones() : uint {
        return this.stones;
    }
  }
}

Now compilation will run just fine, GoldenApple can set the value of stones to 5. To verify it, try the next example:

var myApple : Apple = new Apple();
trace("myApple stones: ", myApple.getStones()); // this will output 4
var myGoldenApple : Apple = new GoldenApple();
trace("myGoldenApple stones: ", myGoldenApple.getStones()); // this will output 5
Note that “//” in actionscript will depict a line of comment, and everything after // on the same line is treated as such. That means the compiler will ignore what’s on these comments. It’s a good practice to comment out your code, this way you can easily remember later what a piece of code is doing, without having to figure it out from looking at it.

Let’s look at the last example more closely and notice that i’ve set myGoldenApple variable to be of type Apple and assigned to it a GoldenApple object! This is possible and the compiler will be more than happy with it. What makes this possible is that GoldenApple extends Apple and in it’s essence it is an Apple, beside being a GoldenApple also. This is very useful as I said already above and helps us in many ways. For example: we have a list of objects at runtime, we know they all are of some base class type, like Apple, but we don’t know for sure if they are of some inherited class type, like GoldenApple, and so we will treat all the objects as Apple types. Here is an example to clarify this:

var myApple : Apple = new Apple();
trace("myApple stones: ", myApple.getStones()); // this will output 4
myApple = new GoldenApple();
trace("myApple stones: ", myApple.getStones()); // this will output 5

This is the same example as the one above, just modified a bit: in turn of declaring a new variable myGoldenApple : Apple, i’ve used the same already declared variable myApple and assign to it the new GoldenApple object instance. Then the output will be just as above. The ability for something to have many forms, like our myApple variable (at first holds an Apple instance, then holds a GoldenApple instance), is called polymorphism and is one of the principles of OOP: abstraction (data abstraction), encapsulation, polymorphism and inheritance (there are others as well but these are the most important) are the principles of object oriented programming.

Since we’re here at polymorphism, let’s talk a bit about the is operator: this helps us to determine the type of an object at runtime by comparing it to a class type, like this:

var myApple : Apple = new Apple();
if(myApple is Apple) {
  trace("an apple");
}
if(myApple is GoldenApple) {
  trace("a Golden apple");
}

This code will output “an apple” and exit. However if we were to construct a GoldenApple object instead of an Apple, like this

var myApple : Apple = new GoldenApple();
if(myApple is Apple) {
  trace("an apple");
}
if(myApple is GoldenApple) {
  trace("a Golden apple");
}

both traces will be executed: “an apple” and “a Golden apple” will both be outputted. That’s because now myApple is an Apple and is also a GoldenApple, so the is operator correctly returns true on both statements.

Polymorphism is used and exemplified very well in serialization/deserialization of objects (actually is used anywhere), and where object factories are used, that’s why in the next part of the tutorial we’ll have an exercise on building serialization/deserialization for our apples.

Now that we have a better grasp of what inheritance is, it’s worth noting that chained inheritance is of course possible. Actually, remember in the first part of the tutorial how we said that any object in actionscript is also of type Object? That’s true. Our apple objects are also Object. That’s because even though we don’t explicitly state that the class Apple extends from Object class, any class will do so automatically. In fact, it is recommended to not explicitly extend the class Object. All the methods and properties of the class Object will automatically be available to your new class.
Because of this possibility of chained inheritance, our GoldenApple class can also be extended by another class, which in turn can also be extended by another class and so on… There’s no limit on the length of this chain.
We said in the beginning that flash supports only simple inheritance and although it makes code much easier to understand, it could also pose serious problems. For this, let’s say that we’d want our GoldenApple to have graphical representation, to be able to add objects of type GoldenApple to the display lists, in essence to became display objects. We know that we can do that only if we use the addChild or addChildAt methods of the DisplayObjectContainer class. But those methods accept parameters of type DisplayObject, which means our class should at least extend the class DisplayObject (in fact we should extend classes that actually have rendering logic, that extend from DisplayObject, like Shape, Sprite, MovieClip…), but unfortunately it doesn’t. What it does, it extends the class Apple. If we don’t extend from Apple anymore and extend Shape, we would end up with a graphical object like we wanted, but we’d loose the methods of the class Apple, and in essence our objects won’t be “apples” any longer, this is not what we want. So here we find ourselves in a bit of trouble. This issue is easily fixed by multiple inheritance, like in c++, where we could extend both classes: Apple and Shape, but unfortunately actionscript doesn’t support it.
So what do we do? We could (and actually this is what it should be done in most situations to avoid these kind of issues) make the class Apple to extend from Shape and GoldenApple extend Apple. This way GoldenApple is an Apple and a Shape (which is a DisplayObject). This is how it’s done in most situations and works perfectly, however it’s not ideal. Why? Let’s think about it for a minute. Apple now is a display object, although Apple is a generic class: it doesn’t know how to draw itself (because it doesn’t know what type of apple it is, it’s size, color, ….) and so it shouldn’t care for being a DisplayObject. But anyway, from a small and simple class Apple, whose objects should be very small, and have a very small memory footprint, it’s now bloated with the intricacies of Shape class even though we don’t need it. And in this case, because we created both Apple and GoldenApple classes and we have access to them, we could change the class Apple to extend Shape, but what if the class Apple was part of a library that we couldn’t modify? What if we later wanted to add interaction capabilities to our GoldenApple class? For that to happen, we’d have to change again the class Apple to extend a class that extends InteractiveObject (like Sprite, MovieClip..), yet another layer of bloating for Apple objects. And what if we wanted later to create another class, RedGalaApple, that extends the class Apple, but we only wanted this class to have visual representation, and not be interactive. We can’t do a thing, the new class will be forced to have interaction capabilities, we would have to switch interaction off by setting mouseEnabled and mouseChildren to false at runtime.
To avoid this bloating of the base class, some use composition patterns, and it is very effective, but we loose the power of inheritance, and the code becomes somewhat awkward. But for devices where we need to squeeze the last bit of memory and power, like mobile devices, this might be the only effective way. I won’t go into detail on how composition looks, but here is a small insight, since we mentioned it: instead of modifying the class Apple, leave it to extend from Object (like completely remove the extends directive); in our class GoldenApple, we add a property visualRepresentation : DisplayObject; we create assign to this property a new Shape and draw whatever we want in it; when it’s time to add our GoldenApple object to the display list, we’ll add the visualRepresentation instead. This is a rough exemplification of how composition works.
Interfaces come to rescue to some degree, implementation of multiple interfaces is allowed. More on interfaces on upcoming parts.
Multiple inheritance would resolve gracefully all these problems, but it will introduce it’s own: the so called Diamond problem – there are 2 classes A and B that extend class C, and you add a class D that extend both A and B: then the C will be duplicated inside D. and others.. Plus the code can be more complicated and more difficult to understand.

About OOP principles, we also mentioned abstraction (data abstraction) and encapsulation so what do they mean?
Abstraction is when you use a class (library), you know it’s public interface and you call it’s public methods/members.. but you don’t really care how is the class built on the inside. You don’t know what the code inside the class actually looks. You make abstraction of what’s on the inside, and only use what’s on the outside, the public interface. The actual logic is “hidden” from you, abstracted.
Encapsulation is the ability to compose an entity from more things. A class is constructed from various member variables, methods, constants… but it represents just one entity. It is said that the class encapsulates all of his properties, methods.. Encapsulation may also refer to the ability to restrict access to part of it’s members, methods, and only allow access to what it wants.

Wow, this is getting really long now and we should end this part here, but before we wrap it up, it makes sense to first talk a little about the keyword final.
We saw how a class can be extended and create derived classes from it. But what if we would want that one class to not be extended, to deny the possibility for another class to inherit from it? Let’s say we built a class and we know that this class shouldn’t ever be inherited from, we want this class to be final. Nothing simpler, just set the final attribute for that class. Example:

package {
  public final class GoldenApple extends Apple {
     public function GoldenApple() {
      trace("a new Golden apple is constructed");
      this.stones = 5;
     }
  }
}

Now the class GoldenApple cannot be extended, it is final, and trying to do so will result in a compiler error.
The keyword final is also available as an attribute for class methods and we will see in the next part how and why is used.

Ok this is the end of this part of the tutorial. I hope you find it useful. As always, comments are more than welcome!

Actionscript 3.0, Object Oriented Programming , , , , , ,

Youtube AS3 Wrapper – Changelog

April 27th, 2009

Youtube AS3 Wrapper v0.8.0m

This new version introduces support for multiple videos playback in the same time, on the same stage!
Some changes in the api: All the methods have been added a new parameter, “playerid”, which will represent the id of the player to which the function will apply.
Example:

function loadVideo(id : String, startSeconds : Number = 0, playerid : uint = 0) : void;

The default for this parameter is 0, meaning that by default the function applies to the player with id=0. Which is the first player that is created.
If you use only one player (you don’t create more), you can forget about this parameter.

New methods added:

                 /**
         * Creates a new player
         * @return int the new player's id
         */

        function createPlayer() : int;
       
        /**
         * Sets the alpha [0,1] for the specified player
         */

        function setAlpha(alpha : Number, playerid : uint = 0) : void;
       
        /**
         * Sets the visibility for the specified player
         */

        function setVisible(visible : Boolean, playerid : uint = 0) : void;
       
        /**
         * Sets the position for the specified player
         */

        function setPosition(x : Number, y : Number, playerid : uint = 0) : void;
       
        /**
         * Swaps the depths of the 2 specified players
         */

        function swapDepths(playeridToBeSwapped : uint, playeridToSwapWith : uint) : void;
       
        /**
         * Brings the specified player to front
         */

        function bringToFront(playerid : uint) : void;
       
        /**
         * Sends the specified player to back
         */

        function sendToBack(playerid : uint) : void;
       
        /**
         * Sends the specified the specified player to it's original depth
         * Note that when usign swapDepths the player that is swapped has it's original depth set to the new depth
         */

        function sendToOriginalDepth(playerid : uint) : void;

The createPlayer method creates New player.
Always wait for the previous player the be ready before calling this method!
The method return the new player’s id. The first time the method is called, it will return 1. Because the player with id=0 is created without calling this method.
After calling this method, the PLAYER_READY event will be dispatched when the new player is ready, and event object will have the playerid parameter set to the new player’s id.

The other new methods speak for themselves through their names.

The YoutubeEvent has now a new parameter:

public var playerid : uint;

This parameter says now which player dispatched the event.

Youtube AS3 Wrapper v0.7.2

This new version fixes a bug where adding and removing the player to and from stage repeatedly causes it to crash.

Youtube AS3 Wrapper v0.7.1

Adds Adobe AIR support. The api remains unchanged.

Youtube AS3 Wrapper v0.7

Fixes the volume bug in IE and deprecates the reload():void and destroyAndReload():void methods because the volume works without reloading the player.

Youtube AS3 Wrapper v0.6

The first released version of the Youtube AS3 Wrapper.
Has problems with volume in Internet Explorer. In order to bypass this problem, the ytPlayer needs to be reloaded for every new clip that plays, using reload():void or destroyAndReload():void methods.

Youtube, Youtube Wrapper , , , ,

AS3 – Object Oriented Programming – Part1

April 16th, 2009

We talked a lot about classes and objects in the introductory part, now let’s look how we can create a class.

In AS3, a class must be created in a separate .as file, with the name of the class being the name of the file.
Also, a class must be contained in a package. We’ll discuss in the next part more about packages.

To define a class in actionscript we have the keyword class.

To write our first class, named Apple, create a file named Apple.as, open it in a text editor and paste in the next code (make sure you edit with a text editor and not a word processor like MS Word):

package {
  public class Apple {
  }
}

There it our first class, however is quite empty; it has no functionality.
Notice that i’ve used the keyword package. That way I defined the package for the Apple class. But more on packages in the next part of this tutorial.
Also notice another keyword introduced: public. This is an access specifier.
An access specifier sets the visibility for a class, method, property or namespace.

A method is a function defined inside a class.
A property or member is a variable defined inside a class.
A namespace is like a package, controls the visibility of definitions, but it’s not directly related to classes, so it won’t be discussed in this tutorial.

In our case, the public specifier sets the class to be visible and accessible anywhere. Without specifying public, the class would be visible only inside the package, because the default access is internal.
A class can only be defined public or internal, however there are 2 other access specifiers: private and protected.
Private means that the property or method is only visible and accesible inside the class. About protected we’ll talk a bit later.

With this said, let’s add a method and a property to our class:

package {
  public class Apple {
    private var stones:uint = 4;

    public function Apple() {
    }
  }
}

Now our Apple class has a property of type uint, named stones, which is declared private (this means that only methods of the class Apple can access this property) and has a default value of 4.
It also has a method, declared public, named Apple. Notice the name of this method is exactly the name of the class. A method with the same name as its class is named constructor.
In actionscript 3.0 a constructor can only be declared public. Also a constructor cannot have a return type (cannot return a value).
It is named “constructor” because when an object is created this method will be called. So it is a good place to put here any initializing code.

With these being said we can construct our first object of the class Apple, but first some words about the import statement.
Before we can use our class, we must import it where we want to use it. For that, we have the “import” statement, so we can use it like this:

import Apple;

Ok. Now we’re ready.
Open the Flash IDE, create a new Flash Actionscript 3.0 File, save it to a name of your choice and copy the Apple.as file in the same directory as your .fla file.
On the timeline, select the first keyframe and open the Actions window (Windows->Actions or press F9), and write the next lines:

import Apple;
var myApple : Apple = new Apple();

That’s it! Your first object is created out of your first class! You can test your file now, but really there isn’t much to see…
Notice the new keyword: it is used to construct new objects.

So let’s add something so that we can see what’s going on.
Add a trace action inside our constructor.
Our class should look like this:

package {
  public class Apple {
    private var stones:uint = 4;

    public function Apple() {
      trace("A new apple is constructed!");
    }
  }
}

Now run again your movie and you should see “A new apple is constructed!” in the Output window. That’s because when we construct our object using the new statement, the constructor of our class is called, thus the trace method is called.
If you would construct more objects, you will see that the message is outputted once for every object.

Next, let’s say we would like to know how many stones has our apple object. But the stones property is private, which means we can’t access it from outside the class. So, to access it let’s add a new method, named “getStones”, that will return the number of stones, and make it public.

package {
  public class Apple {
    private var stones:uint = 4;

    public function Apple() {
      trace("A new apple is constructed!");
    }

    public function getStones() : uint {
      return this.stones;
    }
  }
}

Make note of this keyword. “this” refers to the “current object”.

Now we can call the new method on our object like this:

myApple.getStones()

In Flash, change the code with this one:

import Apple;
var myApple : Apple = new Apple();
trace("myApple has "+myApple.getStones()+" stones.");

When you run your movie you should see in the output 2 lines.

That’s about all on this first part of the tutorial.
In the next part we’ll discuss more about packages.

Actionscript 3.0, Object Oriented Programming , , , , , , ,

Youtube AS3 Wrapper v0.7

March 29th, 2009

A new version of Youtube AS3 Wrapper is available: v0.7

This new version fixes the volume and mute methods thus making the use of destroyAndReload method obsolete. This means you no longer have to destroy and reload the player in Internet Explorer.

The new version is available for download Youtube AS3 Wrapper – Downloads

Also, the test harness player has been update to use the new wrapper. The code that’s not needed, due to deprecation of destroyAndReload method, is commented out.
You can download the sources for the new Test Harness Player at the same link above.
Enjoy!

Youtube, Youtube Wrapper , , ,

Step-by-step installing

March 8th, 2009

This is a tutorial that shows how to install the Contact Form with Mail Attachments component.
Contact Form with Mail Attachments is a Flash, actionscript 3, mail contact form component that suppports multiple mail attachments. The server side script is in php.

Customize globals.php

 

Set here the server details that match your identity.

  • $TO : Set this to be the email address to which the message will be sent  (likely your email)
  • $SUBJECT : Set here the subject of the mail (sent to the $TO address);  <NAME> will be replaced by code with the name of the sender (filled in the ‘Your Name’ field of the form)
  • $CONFIRMATION_SUBJECT : The subject of the confirmation mail (the confirmation mail will be sent to the mail address of the sender: filled in the ‘Your Email’ field of the form)
  • $CONFIRMATION_MESSAGE : Set in this variable the body of the confirmation mail (the confirmation mail will be sent to the mail address of the sender: filled in the ‘Your Email’ field of the form, it confirms that his mail was successfully sent; it also contains a copy of his original message)
  • $CONFIRMATION_NAME : Set here your name; will appear in the header of the mail in front of $CONFIRMATION_MAIL (John Doe [mail@example.com])
  • $CONFIRMATION_MAIL : Set this to be your mail (will apprea near your name: John Doe [mail@example.com])

 

Install the scripts

 

  • Inside the directory where you want to install your app, create a subdirectory ’scripts’. Make the directory permissions 775: rwx-rwx-r-x (this is because flash player will directly access the scripts and php will need r-w permissions here: creates directories and stores uploaded files, then deletes them after the email is sent)
  • Copy all the php scripts inside this newly created directory. Make each file’s permissions 644: rw–r—r–

Install the flash files

 

  • Inside the directory where you want to install the contact form, outside the ’scripts’ directory (you don’t need to install where the scripts directory is, you can install anywhere as the paths to the scripts can be configured in contact.xml file): copy all the necessary files – contact.swf, AC_RunActiveContent.js, contact.html and data directory
  • Make sure that the files have 644 permissions, data directory should have 755, and contact.xml from inside data directory should also be 644

Customize data/contact.xml file

 

  • Open data/contact.xml file in a text editor (notepad will do great, don’t use a word processor like MS Word)
  • Inside this file, the <php> tag must be edited to reflect the real script paths: <mailscript> tag, set it’s path attribute to be the path to the ’sendmail.php’ script; <upload_script> tag, set it’s path attribute to be the path to the ‘upload_file.php’ script – these paths can be relative or absolute;

 For example:

<php>
<mailscript path="scripts/sendmail.php" />
<upload_script path="scripts/upload_file.php" />
</php>

This assumes that the ’scripts’ directory is in the same directory as ‘contact.swf’ file

  • Everything else in the xml file is optional, meaning it can be left as it is
  • <title> : The Title that appears at the top of the contact form
  • <yourname>, <yourmail>, <message> : <caption> – ‘optional’ attribute specifies whether the current field is optional or required when validating the form: valid values “true” – meaning optional, “false” – meaning required; The text inside the <caption> tag is  the text that will appear next to the corresponding text field;

<text> – ‘default’ attribute sets the default text that appears inside the corresponding input text field; when this textfield receives focus, this text will be cleared; ‘clearOnClose’ attribute specifies whether the text inputted will be cleared when the form is closed or not: valid values “true” – meaning the text will be cleared, “false” – the text will remain uncleared, so that when the form is reopened, the last text inputted in this filed it’s still there

  • <error>:  <messages> – sets the error messages when the form is not filled correctly
    • <yourname>, <yourmail> and <message>: ‘empty’ attribute – this error will be displayed when the input textfield is empty and the textfield has been declared as required (see previous point)
    • <yourmail>: ‘notValidated’ attribute – this error appears when the email entered in the <yourmail> tag is not a valid email address
  • <close>: if  ‘visible’ attribute on <button> tag is ‘true’, the close button is visible, if it’s ‘false’, it’s not visible
  • <submit>: <event> : ‘closeFormUponSubmit’ – valid values: ‘true’ – meaning the form will be closed if the form is successfully submitted, ‘false’ the form will not be closed
  • <files> : <upload_file> : ‘max_file_size’ set this the maximum allowed file size in KiloBytes; if the file is bigger than this value, the file will not be added to upload list
    • <file_filter>:  ‘type’ attribute – Set the type of files allowed by this filter; accepts wildcards (*): to allow mp3 files ‘*.mp3′; to allow more types by one filter: ‘*.mp3;*.wav’; ‘description’ attribute – Sets the description associated with this filter; These filters work based on file extensions!

 

 

To set file attributes in terminal:

chmod UGO file

Where UGO is the file perrmission: U – user permission (owner)

G – group permission

O – others permission (public)

1 – execute

2 – write

4 – read

Example: 644 – U=2+4=write+read

G=4=read

O=4=read

Components, Contact Form With Attachments v1.1 , , , , , , ,

Flash CS4 TextField: embedded fonts

March 4th, 2009

Embedding a font in AS3 in Flash CS4 seems more challenging than at a first glance.

Flash had problems with fonts and texts for a very long time, but the new editor adds up problems rather then removing them.

Soo, here is what should always work when creating a textfield dynamically:

Firstly, embed the font you want to apply for your textfield inside the editor: in the library, right-click, select New Font…

Set a name for the font (you can leave it  as it is), choose the font you want from the Drop down, select a style (if any is available), if not you can check the appropriate Faux box..

The size property has effect only if you select the Bitmap option: this option specifies that the font will be embed as bitmap rather then vector

Since we’ll use this font in code, we must set a Linkage for it: check Export for actionscript, leave checked Export in frame 1, and in the Class field set a name you want: let’s say MyFont, leave the base class to be Font and click ok

A warning popup should appear saying that there’s no class MyFont found in the classpath and Flash will create one for us: that’s ok, that’s exactly what we want

Soo, the class MyFont will be created by Flash and it will have the base class Font.

ok.

Now we can create the textfield in code

You can write the code on the first frame or on a separate file inside a class.

I’ll just create a new class that extends MovieClip and set this class as the document class for my swf

package textfield{
import flash.display.MovieClip;
import flash.utils.getDefinitionByName;
import flash.text.TextFieldAutoSize;
import flash.text.TextField;
import flash.text.TextFormat;
import flash.text.Font;

public class Main extends MovieClip {
public function Main() {
super();
this.createTextField();
}

private function createTextField() : void {
// create the textField object
var text : TextField = new TextField();
// optionally set a name for the textfield, so we can refer to it, if we need to, later
text.name = "text";
// set the autosize option to "left"; using constants is more error proof
text.autoSize = TextFieldAutoSize.LEFT;
// set the the multiline property to be true; so we can have multiple lines in it
text.multiline = true;
// true so that line wrap at words end (at white characters)
text.wordWrap = true;
// the key to whether the font will be embedded (true) or not (false) in the swf
text.embedFonts = true;
// set size and positions of the text field
text.width = 200;
text.height = 150;
text.x = text.y = 100;

// we get a reference to the definition of the MyFont class (the class of our font created in the library)
// we could have just used 'MyFont' directly, but some editors, like FDT, complain about it, saying that the specified definition does not exist, and if we have errors, the editor will not give us code completion... corectly; the point is we can do without it
var MyFontClass : Class = getDefinitionByName("MyFont") as Class;
// create an instance of our font class
var myFont : Font = new MyFontClass() as Font;

// in order to specify what font we'll use for our textfield, we need a textformat object
var textFormat : TextFormat = new TextFormat();
// set it's font property (String) to the name of our font
// you might notice that we could have passed in the name of the font directly, hard coded; and it would have worked; but it's safer this way; fonts may have different names on different OSs, so when compiling the fla on a different OS, the font might not be found, thus the text will not be displayed; although you might argue that the font is there; also it's easier to change the font; only change it in library and recompile
textFormat.font = myFont.fontName;
// set font size
textFormat.size = 16;
// set font color
textFormat.color = 0xff0000;

// apply the text format to the text; this only works if you're not using the stylesheet property of the textfield
// also, using defaultTextFormat property instead using setTextFormat method seems to work better; i couldn't find a reason for that, all i can think of, is that when setting the defaultTextFormat property, it takes only the values that are NOT NULL from the text format, and when using setTextFormat method, it sets all the values even if they are NULL; anyway, not even the old way, a combination of getTextFormat, setting the values needed, and setTextFormat, doesn't work anymore
text.defaultTextFormat = textFormat;

// set some text to see our text field; htmlText also works
text.text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";

// Add the text field in the display list of our document
this.addChild(text);
}
}
}

Where your fla is situaded on the file system (in the classpath) create a folder named ‘textfield’, inside this folder create a new file ‘Main.as’ and paste in the code above;
In your fla, set the Class property of the document to “textfield.Main”.
Compile and run the app, you should see the text in red.

If the text doesn’t appear, it means that the font is not embedded properly

Notice that i didn’t set the antiAliasType Property of the text field to be “advanced”, that’s because i noticed on some fonts, setting this property breaks the embedding mecanism, the text won’t show, the font will not be embedded.
however on most of the fonts it works, so you should try and see the result first.
You should keep in mind however, if the text doesn’t show, try not setting the property and see if it works without it.

You can check if your font is embedded: use the static method enumerateFonts of the Font class, which returns an Array of fonts: all the fonts installed on the system or only the fonts embedded in the swf, depending on the value of the enumerateDeviceFonts parameter
Here is the declaration of the method

static public function
enumerateFonts(enumerateDeviceFonts:Boolean = false):Array

if

enumerateDeviceFonts

is

true

, then it will return the list of all the fonts installed on the local machine
if it’s false will return an Array of all embedded fonts in the current swf

Hope it helps anyone

Actionscript 3.0 , , , , , ,

Simple XML Loading example

February 10th, 2009

Hi,

This is a very simple “tutorial”, more like a how-to, just to practice my writing skills.

First of all we must create an

object:

But to be able to do this, we need to import it, and also import URLRequest, like this:

import flash.net.URLLoader;
import flash.net.URLRequest;

also import the next classes we’ll use:

import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.events.SecurityErrorEvent;

create the loader object:

var loader : URLLoader = new URLLoader();
// listen for the COMPLETE event
loader.addEventListener(Event.COMPLETE,
this.onLoadComplete);
// add error event handler
loader.addEventListener(IOErrorEvent.IO_ERROR,
this.onIOErrorEvent);
loader.addEventListener(
SecurityErrorEvent.SECURITY_ERROR,this.onSecurityErrorEvent);

Now that we’re done initializing the loader object, we must create an URLRequest object that will be passed as the request parameter for the load method:

var request : URLRequest = new URLRequest("path_to_file.xml");
// load the file
loader.load(request);

// Now we must create the functions (event handlers) :
function onIOErrorEvent(event : IOErrorEvent) : void {
// handle the error here
// for now just trace the error
trace(event);
}

function onSecurityErrorEvent(event : SecurityErrorEvent) : void {
// handle the error here
// for now just trace the error
trace(event);
}

function onLoadComplete(event : Event) : void {
// the loaded data is in event.target.data
// so create a new XML object
// the XML constructor throws a catchable error if the xml we
// loaded is mallformed
// thus we'll use a try-catch block

var xml : XML;
try {
xml = new XML(event.target.data);
} catch (e : Error) {
// just ouptut the error for now
trace(e);
}

if (xml != null)
{
// our xml is created; use it here
}
}

This is a common way of loading any data, not just xml, if you don’t need access to the bytes loaded until the loading is complete.

Actionscript 3.0 , , , , , , ,