Tutorial: understanding the Flash sandbox - Application Domains

Recommended for you: Get network issues from WhatsUp Gold. Not end users.

The application domain

Application Domains The application domain Application Domain Placement The application domain of the position Application Domain Inheritance Inherit the application domain Child Domains: Definition Versioning Subdomain: 定义的版本管理 Separate Domains: Preventing Conflicts Domain separation: 避免冲突 Same Domain: Runtime Shared Libraries The same domain: 运行时共享库 Getting Definitions Dynamically Dynamic definitions Same-definition Collisions The same definition of conflict Conclusion Summary

Application Domains application domain

And security domain, different security sandbox under SWF has its own independent class definition. The division and management of Lei Dingyi in the security domain (defined below the function, interface and namespace and class like) subdomain is the application domain. The application domain exists only in the security domain, and can only belong to a security domain only. But the security domain can contain multiple application domains.
Application Domains in Security Domains
The application domain security domain
Although the domain security sandbox for protecting data security, application domain is used to divide the sandbox defined. But they are used to solve the conflict and the inheritance relationship definition judgment code.
Between security domains are independent of each other, in contrast, the relationship between application domains is more complicated. The application domain by like display list that hierarchy linked together in Flash. The application domain can contain arbitrary subdomains, the subdomains can have only one parent domain. Subdomain inherited from the parent domain of definition, like the display list of the parent object location and scaling properties of the quilt object inheritance.
The root node of the application domain is a domain, the domain contains the original definition of Flash Player API (Array, XML, flash.display.Sprite etc.). System domain and security domain is one one to one correspondence, when security domain initialization of this unique system domain is also established.
When initializing instance when a Flash Player, SWF file to the security domain and its corresponding. At the same time also created an application domain for this file contains all the compiled ActionScript definition. The application domain became the first sub domain domain domain. The original definition of Flash Player API through the inheritance relationship of all subdomains open.
Child Application Domain
A SWF application domain built in the system domain
We will discuss more about inheritance in the application domain of inheritance section.

Application Domain Placement application domain position

To define the first instantiate the Flash Player SWF file contains always be directly subdomain loaded as domain system. The parent SWF to load when SWF, can be placed within the SWF control definition and position. Optional location consists of the following 4:
The application domain of the parent SWF of the new sub domains (the default) SWF and father SWF application domain as the domain of the parent domain system with the new subdomain system domain in other domain of the new sub three situations are security domain and SWF loaded into the parent domain located, only the fourth is the only one to load the SWF to the other domain.
Application Domain Placement
Loading SWF placed the application domain 4 choices
Another way is not mentioned, you create an application domain for a SWF has been loaded, and the other the definition in the SWF merged into (or inherited) this field conditions. This special place requires the application domain level management complex, you need to master the usage of ApplicationDomain.parentDomain, remind reader beware: this method is usually in the sandbox security under different (local or network) will have different behavior. This approach is not very common, so this is not a deeper discussion.
The applicationDomain property of the LoaderContext object to define the placing application domain way. You can use ApplicationDomain.currentDomain (like in the security domain of SecurityDomain.currentDomain) or with the new keyword to create a new ApplicationDomain instance as a parameter. In the ApplicationDomain constructor to specify the parent domain to the new domain, if this parameter is not specified, said the domain directly as the system domain of schemes.
// The definition is placed into the application domain where the parent SWF (the current application domain)
var current:ApplicationDomain = ApplicationDomain.currentDomain;

// The definition of the application domain into subdomains where the parent SWF
var currentChild:ApplicationDomain = new ApplicationDomain(current);<em>?</em>

// The definition is placed into the system domain application domain where the parent SWF
var systemChild:ApplicationDomain = new ApplicationDomain();
The following code demonstrates how to use the LoaderContext object is passed to the Loader.load method ApplicationDomain examples, the application domain is a subset of SWF loading to the parent SWF of the subdomains by example. Loading behavior is also the default this way.
var context:LoaderContext = new LoaderContext();
// Handle the application domain as the application domain of schemes
var current:ApplicationDomain = ApplicationDomain.currentDomain;
context.applicationDomain = new ApplicationDomain(current);

var loader:Loader = new Loader();
var url:String = "child.swf";
loader.load(new URLRequest(url), context);
An instance of ApplicationDomain contains a hierarchical location information is not open in the internal ActionScript. Each instance of ApplicationDomain is a unique reference, each other can't compare.
var current1:ApplicationDomain = ApplicationDomain.currentDomain;
var current2:ApplicationDomain = ApplicationDomain.currentDomain;
trace(current1 == current2); // false
You can't quote system domain through the parentDomain property, only through the new ApplicationDomain (can).

Successor to the Application Domain Inheritance application domain

Inheritance and class definitions to inherit a class like both are defined, children can access the parent class, but not vice versa.
The difference lies in the definition of the application domain, inheritance does not allow the child to override the parent class. If the domain contains definitions and parent domain (which is the fully qualified name, including path). Well defined in the parent domain will replace the subdomain.
Child Application Domain Inheritance
The definition of the parent domain covered by subdomain
This is because the class definitions, you can't change an existing instance. If the new definition in is loaded in the definition has been used before generation examples, then the instance between the original class definitions and new class definition of conflict. So Flash Player protection class definition originally not be rewritten to avoid conflict.
This also means that the original definition of developers can not covered ActionScript API. Because the application domain of SWF is definitely system domain of schemes, and system field contains the definitions of all native. So the name contains the definition of operator SWF, will be covered in the domain of definition system.
When an existing application domains with defined, the same rules apply. Only non conflict and definition of the original domain of definition will be merged.
Adding Definitions in Application Domain
Add to the existing definition does not cover the application domain.
In this case, the conflict but definition is covered completely do not achieve. But if the inheritance way, even if the definition of conflict subdomains are defined in the parent domain of the cover, or by getDefinition methods can be extracted from sub domain, this will get the discussion sections in the dynamic definition.
Loading to the definition in the application domain has been present in the application domain of the life cycle. In the SWF after unloading, will be unloaded from memory for the application domain to preserve this within the SWF. But if the SWF is defined in some other existing within an application domain, so these definitions will remain in the memory, unless the SWF target application domain associated uninstall. If you keep a new definition is loaded into an existing domain, such as the first loaded SWF created domain, then define the memory will always increase. If it is a non-stop loading SWF rolling advertisement application, increasing the definition to the application domains within the same problem caused by memory growth is obviously not the expected results.
Moreover, loading in this way definition not with SWF uninstall unloading, but in the second time when loading the same sub SWF reuse definitions created the first loading of the. This usually does not have what problem, but it means to load the same when the SWF static state does not reset. Static variables may be the last used value it will be, and the first loading in consistent.
So, different situations require different solutions.

Child Domains: Definition Versioning subfields: version management definition

The inheritance mechanism defined subdomains can share the definition of the parent domain is very convenient. Also because of duplicate definition method will be covered in the parent domain causes, the father application domain has control defines which version to use in the domain of power.
Child Application Domain Inherits Parent Definitions
The child application domains is inherited from the parent domain
Consider the following scenario: a SWF site based on the use of different SWF files to represent different pages. The main SWF is responsible for loading the page. Each page SWF the same class library is developed based on like, has the behavior. For example, there is a PageTitle class that represents the title text page.
If in the same domain to another SWF also used the same sub pages, but need to handle the title of the page text is not optional (assuming the original attribute is optional). To achieve this example purposes, in the PageTitle class, we need to put the selectable TextField property to false. But this change will influence the problem is the original SWF file to keep its original behavior.
In order to solve this problem, we can think of each sub page copy and recompile. But doing so will occupy more space and site traffic. The better solution is to compile only second SWF, the PageTitle class definitions updated compiled together. And then to the time of the application domain in the loading in the sub page, the class definition will be defined in the parent domain to cover.
Originally all sub page using PageTitle as follows:
package {
import flash.display.Sprite;
import flash.text.TextField;

public class PageTitle extends Sprite {

private var title:TextField;

public function PageTitle(titleText:String){
title = new TextField();
title.text = titleText;
addChild(title);
}
}
}
Compile the updated version to second main files in the PageTitle class:
package {
import flash.display.Sprite;
import flash.text.TextField;

public class PageTitle extends Sprite {

private var title:TextField;

public function PageTitle(titleText:String){
title = new TextField();
title.text = titleText;
<strong>title.selectable = false;</strong> // changed
addChild(title);
}
}
}
The PageTitle class defines the updated compilation to the new master file, and load all the sub page to the application domain in which they own.
PageTitle; // Although not directly use PageTitle, but we can contain a reference, let it be to compile. 

// Loading sub page to the application domain in which they own.
// Loading SWF will be defined in the PageTitle parent domain, replace them with
function addChildPage(url:String):void {
var context:LoaderContext = new LoaderContext();
var current:ApplicationDomain = ApplicationDomain.currentDomain;
context.applicationDomain = new ApplicationDomain(current);

var loader:Loader = new Loader();
addChild(loader);
loader.load(new URLRequest(url), context);
}
Change the kind of behavior that can recompile sub content in different, this is all because of definition application domain will cover the definition domain.
Note in the example above can also use the LoaderContext is omitted, the effect is the same.
Even without a SWF multi purpose, definition updates in the primary file than update all the sub documents easier. In fact, sub file even can not completely contain these definitions, depends only on the main document. This is what we will be in the same domain: runtime shared libraries section will be discussed.

Separate Domains: Preventing Conflicts domain separation: avoid conflict

In some cases, you may not want to sub loaded SWF content is defined application domain in the effect of inheritance. Because maybe you don't even know what is defined in the parent domain. In either case, best to avoid defining the main SWF and the sub sharing in SWF. In this case, should be defined by SWF into the system domain new subdomains under.
Child SWF Domain as Child of System Domain
The different sub domains of application domain system
Because the inheritance relationship between father and son did not define SWF SWF, so this time even in the presence of the same definition does not cause conflict, because the two belong to different sandbox.
For example: if you have a training program, by loading an external SWF to represent different training modules. This procedure has been for some years, many developers have created hundreds of training module. These modules, and even training program itself are developed for different versions of the code base based on. So the main program to ensure that their own use of the code base will not cause is not compatible with the other module case. This must take these training module is loaded to the system of their domain independent of subdomain, instead of making them loaded into the following main application domain of schemes.
trainingapplication.swf:
var moduleLoader:Loader = new Loader();
addChild(moduleLoader);

// The module is loaded into the system domain of schemes, and separate application domain area at present
function loadModule(url:String):void {
var context:LoaderContext = new LoaderContext();
context.applicationDomain = new ApplicationDomain();

moduleLoader.load(new URLRequest(url), context);
}
Unfortunately, this definition is not the way to divide completely isolated. Because in the same domain content are in the same region, any definition of system domain changes will affect all application domains with a domain. Even though the SWF is loaded into a separate system domain of schemes, the parent SWF changes to the system domain will affect its.
We can verify this by changing the XML.prettyIndent property: no matter in which SWF application domain level to make changes to the definition of system domain, will affect all the files under the same security domain.
parent.swf:
trace(XML.prettyIndent); // 2
XML.prettyIndent = 5;
trace(XML.prettyIndent); // 5

var loader:Loader = new Loader();

var context:LoaderContext = new LoaderContext();
// A new independent of the application domain
context.applicationDomain = new ApplicationDomain();

var url:String = "child.swf";
loader.load(new URLRequest(url), context);
child.swf:
trace(XML.prettyIndent); // 5
So the best practice is to change to the definition should be promptly after use reduction, which can avoid the influence of other documents.
var originalPrettyIndent:int = XML.prettyIndent;
XML.prettyIndent = 5;
trace(myXML.toXMLString());
XML.prettyIndent = originalPrettyIndent;
Similarly, you must pay attention to class like such value there may be outside of your program is the change.

Same Domain: Runtime Shared Libraries the same domain: runtime shared libraries

The additions to the existing definition of the application domain may be useful application domain the biggest. Because the inheritance can only be defined on the parent domain sharing in the field, and with the definition to the application domains within the same can all use this domain of SWF sharing, including parent and child.
Parent Domain Adds Child Definitions
Application domains include the definition of SWF
Runtime shared libraries (RSLs) is the use of this mechanism. RSLs is independent of the code base can be loaded at run time. Through the RSLs, other SWF can share the code without the need for compilation into itself, thereby eliminating redundancy, reducing the file content, also make the code easier to maintain. We loaded in the main application field of RSL, which can share the definition in the entire program.
Need to do some preparation work before the use of RSLs. First of all, the ActionScript compiler needs in the release of SWF file to know which definition does not need to be compiled.
Flash Player API defines a native does not need to compile. Although the definition of each SWF needs to use the native (Array, XML, Sprite), but these definitions exist only in the Flash Player executable file, do not need never be compiled into a SWF file. The compiler uses a special SWC called playerglobal.swc (pre compiled SWF Class Library) is defined to identify the primary. It contains a primary defined interfaces, including the definition of name and data type. The compiler to compile the SWF through it, and will not put these definitions are compiled into the final SWF.
The compiler can also refer to other types of like playerglobal.swc libraries like SWC. These libraries as "external" library, which contains the definition is used to compile, not included in the SWF internal.
Here does not discuss in detail how the database link in editing tool set. Different versions of the editor is somewhat different, specific methods please refer to the Flash documentation.
Although we use SWCs to compile the SWF, but in fact they itself is a SWF file, and the other is loaded SWF content like. When the base compiler, and generated SWF and SWC files. SWF used to run when loaded at compile time, and SWC used as an external library.
Compiling a Shared Library
The compiler uses the SWCs shared library, SWF shared library is loaded at run time
Another preparation work need to write code. When using an external database, define library contains no release in SWF. If the Flash Player trying to run the code, will produce the verification error, the entire SWF basically paralyzed.
Flash Player will be in first parity used its definition. If this definition does not include the application domain, then check the error will be generated.
In fact, the lack of definition to create error two. Parity error is two in the worst, said a catastrophic failure class does not work. Another kind is quoting errors, when a certain data type is referenced but not available in case of occurrence. Although the lack of definition will cause a quoting error, but the error would have been like in internal check interrupt the normal process execution of code.
var instance:DoesNotExist;
// VerifyError: Error #1014: Class DoesNotExist could not be found.
// When calibration error occurred in the Flash contains the definition of class Player check
var instance:Object = new DoesNotExist();
// ReferenceError: Error #1065: Variable DoesNotExist is not defined.
// When the code is executed when a reference error
The main difference is that the parity error and class definitions, and quoting errors and code implementation. Within the class code to perform before, we must first pass the examination. Instance object declaration in the example above is of type Object, check can be normal by (but will be in the implementation when quoting errors).
Note: Strict Mode note: strict mode;
External library reference definitions and don't need to be compiled into a method in SWF. Another method is to shut down the strict mode, which will greatly ease the use of variable inspection. For the type of use, you can refer to a nonexistent without cause a compiler error. You can't directly to the absence of class as variable types (this will generate parity errors at run time), but you can like the above "bug" case to refer to. In the non strict mode, the compiler may have some errors that may occur is not detected, so usually do not recommend using this model.
The use of the RSLs SWF file must guarantee the loading of RSLs, can use the external definition. We should be prior to the start of execution in the main application with a pre loader to load RSLs.
The following presentation of a SWF that contains the Doughnut class loading external RSL example. While SWF direct reference to this class, but it was compiled in the external database, and through the SWC way to reference. RSL is loaded in before the class Doughnut is used for the first time, it will not cause error.
Doughnut.as (compiler for the doughnutLibrary.swc and doughnutLibrary.swf):
package {
import flash.display.Sprite;

public class Doughnut extends Sprite {
public function Doughnut(){

// draw a doughnut shape
graphics.beginFill(0xFF99AA);
graphics.drawCircle(0, 0, 50);
graphics.drawCircle(0, 0, 25);
}
}
}
ShapesMain.as (Master Shapes.swf):
package {
import flash.display.Sprite;

public class ShapesMain extends Sprite {
public function ShapesMain(){

// Although not compiled into Shapes.swf,
// But we through the doughnutLibrary.swc external library
// You can obtain a reference to the Doughnut class
var donut:Doughnut = new Doughnut();
donut.x = 100;
donut.y = 100;
addChild(donut);
}
}
}
Shapes.swf (RSL loader):
var rslLoader:Loader = new Loader();
rslLoader.contentLoaderInfo.addEventListener(Event.INIT, rslInit);

// The definition in the RSL loaded into the current application domain
var context:LoaderContext = new LoaderContext();
context.applicationDomain = ApplicationDomain.currentDomain;

var url:String = "doughnutLibrary.swf";
rslLoader.load(new URLRequest(url), context);

function rslInit(event:Event):void {
// Only when the definition into RSL in the current application domain
// We can use the Doughnut defined by checking ShapesMain class
addChild(new ShapesMain());
}
In this example, Shapes.swf is the main program, when the RSL is loaded after instantiating the class ShapesMain. If there is no definition into RSL, will create an instance of ShapesMain because they can not get the corresponding class in the application domain and the occurrence of checksum error.
Note: Flex RSL
The method discussed here is the bottom, should not be used in the development of Flex. There is a set of RSLs processing mechanism under the framework of Flex, more and more about the application of RSL in Flex, please refer to the Flex Runtime Shared Libraries (Flex 4).

Getting Definitions Dynamically dynamic definitions

We can use the Application.getDefinition method to obtain not defined in the application domain, or by the parent domain definition. This method returns the definition of the application domain and any parent domain references. The use of the getDefinition method in the current application domain effect is equivalent to the global function getDefinitionByName.
We can use SWF LoaderInfo.applicationDomain to obtain the application domain in addition to ApplicationDomain.currentDomain. In the example below, we use Loader to load a SWF file, and then the definition of class com.example.Box extraction in the application domain of loading.
try {
var domain:ApplicationDomain = loader.contentLoaderInfo.applicationDomain;
var boxClass:Class = domain.getDefinition("com.example.Box") as Class;
var boxInstance:Object = new boxClass();
}catch(err:Error){
trace(err.message);
}
The above example contains two knowledge points. First of all, the getDefinition method returns value is an explicit conversion to Class type, this is because the default getDefinition returned is of type Object, may represent in addition to other types of class type (other than function, namespace, interface). Secondly, this operation should be put in the try-catch function in vivo, because if getDefinition find definitions of failure will throw an error. Or you can before using getDefinition detection using ApplicationDomain.hasDefinition method is able to find a definition of success.
Defined by a dynamic way to get, but not those in the current application domain (and inherited program domain) definition, can not be used as variables of type. Just like RSL, found in the application domain of the class definition in the check time error. So in the example above the boxInstance variables declared as Object type instead of Box type, it is because the definition of class Box in the application domain does not exist.

Same-definition Collisions the same definition of conflict

Some may happen when you cross reference definition is matched to the definition and application domain of. This will produce the following types of forced conversion error:
TypeError: Error #1034: Type Coercion failed: cannot convert
com.example::MyClass@51e1101 to com.example.MyClass.
You can see the definition in different memory space with the @ symbol of distinction. Although their internal code may be exactly the same (or different), but because they have different application domains (or domain), so they are two different definitions.
Only Object like native Flash Player definition can be located in different domains (even across security domains associated) definition. In fact, when most of the time to declare a cross domain variable types need to use Object type.
Although we can use the generic type definition Object to solve the conflict errors, in fact we should be more rational arrangement of the application domain of the position to eliminate this situation does not match.

Conclusion summary

This tutorial contains a lot of information. The first part discussed the security domain of what is, and how it impacts from different fields. Flash Player in this sandbox security mechanism to protect user data. Flash developers should understand and use the reasonable restriction.
The second part discusses the application domain -- one for the partition ActionScript is defined in the security sandbox sandbox type. The application domain level mechanism provides a method definition share directly in different SWF and reuse.
There are many mistakes in the concept of security domain and application domain. Hope this tutorial to help you get ready. You should not only understand their mode of operation, but also know how to use them correctly in order to achieve the effect you want.

Translator's note:

Through the translation of this article, I truly understand the translation work is difficult to do. Although usually see English data speed is quite fast, but Chinese with repeat need to spend tens of times. In this tutorial translation, I do not use the translation tool, completely by playing, while translation again understand the intention of the author. I have learned more than simply watch it again to some.
This knowledge is very important, especially some traps developed from the AS2 era of developers is very easy to fall into the. To fully grasp the architecture of this part of knowledge to design module, memory management, and other aspects of great help. This will once again thank the original author senocular has such a wonderful tutorial for us.
Please respect copyright, reprint please indicate the source.

This entry was posted in Develop and tagged ActionScript, Flash, tutorial on 2010/11/30.

Reprint
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Posted by Adelaide at December 06, 2013 - 8:36 PM