<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>.:. blog.screenshot.at .:. Flash, Flex, RIA .:. &#187; SDK</title>
	<atom:link href="http://www.screenshot.at/blog/category/sdk/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.screenshot.at/blog</link>
	<description>This blog is about Flash, Flex, RIA related stuff</description>
	<lastBuildDate>Mon, 11 May 2015 18:06:51 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>https://wordpress.org/?v=4.2.38</generator>
	<item>
		<title>Flex 3 vs. Flex 4</title>
		<link>http://www.screenshot.at/blog/2011/03/31/flex-3-vs-flex-4/</link>
		<comments>http://www.screenshot.at/blog/2011/03/31/flex-3-vs-flex-4/#comments</comments>
		<pubDate>Thu, 31 Mar 2011 20:55:42 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[163]]></category>
		<category><![CDATA[Flex 3]]></category>
		<category><![CDATA[Flex 4]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Viers]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=599</guid>
		<description><![CDATA[Jack Viers has posted a great performance comparision between Flex 3 to Flex 4 components. Unfortunately the Flex 4 components suffer from big performance decrease (163% slower). But just read the article it is very profound discussed there.]]></description>
				<content:encoded><![CDATA[<p><a href="http://jackviers.blogspot.com" target="_blank">Jack Viers</a> has posted a great performance <a href="http://jackviers.blogspot.com/2011/03/flex-3-vs-flex-4a-performance.html" target="_blank">comparision</a> between Flex 3 to Flex 4 components.</p>
<p>Unfortunately the Flex 4 components suffer from big performance decrease (<span class="Apple-style-span" style="font-family: Arial,Helvetica,sans-serif;">163% slower). But just read the article it is very profound discussed there.<br />
</span></p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2011/03/31/flex-3-vs-flex-4/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Not easy to use &#8220;usePhasedInstantiation&#8221;</title>
		<link>http://www.screenshot.at/blog/2011/03/23/not-easy-to-use-usephasedinstantiation/</link>
		<comments>http://www.screenshot.at/blog/2011/03/23/not-easy-to-use-usephasedinstantiation/#comments</comments>
		<pubDate>Wed, 23 Mar 2011 23:47:48 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[Applications]]></category>
		<category><![CDATA[Asynchronous]]></category>
		<category><![CDATA[Blog Entry]]></category>
		<category><![CDATA[Containers]]></category>
		<category><![CDATA[Cycle 3]]></category>
		<category><![CDATA[Default State]]></category>
		<category><![CDATA[Execution Model]]></category>
		<category><![CDATA[factoryClass]]></category>
		<category><![CDATA[Flex Components]]></category>
		<category><![CDATA[Frame Delay]]></category>
		<category><![CDATA[Frames]]></category>
		<category><![CDATA[Heavy Weight]]></category>
		<category><![CDATA[LayoutManager]]></category>
		<category><![CDATA[Lifecycle]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Mycmc]]></category>
		<category><![CDATA[Random Components]]></category>
		<category><![CDATA[Real World]]></category>
		<category><![CDATA[UsePhasedInstantiation]]></category>
		<category><![CDATA[validateDisplayList]]></category>
		<category><![CDATA[validateProperties]]></category>
		<category><![CDATA[validateSize]]></category>
		<category><![CDATA[World Application]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=581</guid>
		<description><![CDATA[Have you ever tried to use usePhasedInstantiation? It is not so easy, as you will see&#8230; What is usePhasedInstantiation? This is a property at the LayoutManager which is used to decide if the methods for the 3 Lifecycle phases (validateProperties, validateSize and validateDisplayList) are deferred with 3 (half-)frames or if they are all executed synchronously [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>Have you ever tried to use <a href="http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/managers/LayoutManager.html#usePhasedInstantiation" target="_blank">usePhasedInstantiation</a>? It is not so easy, as you will see&#8230;</p>
<p><span class="hl">What is usePhasedInstantiation?</span><br />
This is a property at the LayoutManager which is used to decide if the methods for the 3 Lifecycle phases (validateProperties, validateSize and validateDisplayList) are deferred with 3 (half-)frames or if they are all executed synchronously in one Frame. So if it is set to true (default state) at an EnterFrame event validateProperties() is called, on the next Render event validateSize() and on the next EnterFrame event validateDisplayList().</p>
<p>As I discussed in a previous <a href="http://www.screenshot.at/blog/2011/01/20/flex-life-cycle/" target="_blank">blog entry</a>, I was wondering why Flex is using a deferred asynchronous execution model. I tried to find out what happens if you change this property.</p>
<p>First I tracked the executed frames and checked out how it behaves with different use cases of Flex applications:<br />
With a simply Flex application with a few random components it was like expected: 1 Frame delay for the whole cycle (3 half frames).<br />
Then i added much more components and also some really heavy weight components like DataGrid, DateChooser or ColorPicker.<br />
Here it took 3 frames, so it seems that there is some code in some of these Flex components which causes additional invalidation cycles (for instance if you call a invalidateProperties method inside of a creationComplete handler you will trigger a new cycle).<br />
At last I measured with our <a href="https://www.mycmc.co.uk/Main.html" target="_blank">Spreadbetting application</a> at CMC Markets. Here it was a bit more difficult because there was more complex stuff going on. I measured the executed frames and time it takes until the application was idle in the login state and waiting for user input. We will compare the results later.</p>
<p>I tried to investigate to change this property to see and measure the effects on performance.<br />
But unfortunately it didn´t had any effect. After stepping into the SDK sources, i found the reason:<br />
It is set to true in the Containers createComponentFromDescriptor method which is called for adding the MXML children inside a Container. So it doesn´t help much if you set it to false at any place in the Application, because it will be overwritten by the adding of the first child at any Container class (Canvas, HBox,&#8230;).<br />
I am not sure if there is a clean solution how to change this default behavior, but for my test case it was enough to simply ignore the value passed into the setter method in the LayoutManager and set the value to false by default.<br />
But to change the LayoutManager is <span class="hl">not so easy</span>. It is setup in the SystemManager and to override this implementation you need to change the SystemManager which can be only defined in an own Application class.</p>
<p>Here are the steps <span class="hl">how to do this:</span></p>
<p>In your MXML Application you use a custom Application class:</p>
<pre>[code lang="actionscript3"]<bootstrap:MyApplication 
  xmlns:mx="http://www.adobe.com/2006/mxml" 
  xmlns:bootstrap="com.test.bootstrap.*" [/code]</pre>
<p>MyApplication defines the custom SystemManager as factoryClass in the "Frame" metadata tag:</p>
<pre>[code lang="actionscript3"][Frame(factoryClass="com.test.bootstrap.MySystemManager")]
public class MyApplication extends Application
[/code]</pre>
<p>MySystemManager overrides the docFrameHandler method and set MyLayoutManager as implementation class for the ILayoutManager:</p>
<pre>[code lang="actionscript3"]public class MySystemManager extends SystemManager {
override mx_internal function docFrameHandler(event:Event = null):void {
  Singleton.registerClass("mx.managers::ILayoutManager",
    Class(getDefinitionByName("com.test.bootstrap::MyLayoutManager")));
  super.mx_internal::docFrameHandler(event);
}
[/code]</pre>
<p>In  MyLayoutManager you can bypass the assignment of the usePhasedInstantiation property:</p>
<pre>[code lang="actionscript3"]public function set usePhasedInstantiation(value:Boolean):void {
  // for simple testing purpose:
  // simply ignore the values coming from Container and
  // set it by default to false
  value = false;

  if (_usePhasedInstantiation != value) {
    _usePhasedInstantiation=value;
    var sm:ISystemManager=SystemManagerGlobals.topLevelSystemManagers[0];
    var stage:Stage=SystemManagerGlobals.topLevelSystemManagers[0].stage;
    if (stage) {
      if (value) {
        originalFrameRate=stage.frameRate;
        stage.frameRate=1000;
      } else {
        stage.frameRate=originalFrameRate;
      }
    }
  }
}
[/code]</pre>
<p>Another interesting detail is that Flex is setting the framerate to 1000 while these phased instantiation is active to speed up the execution (but this could also lead to strange side effects with too fast running animations like we have in our application with a pre-loader animation).</p>
<p>So lets <span class="hl">do the tests again</span> with this new setting:<br />
The simple setup showed that all is executed inside of one frame and the time measured showed a faster startup, but the difference was pretty small.<br />
The setup with the more complex Flex components gave a bigger difference in time and of course all was executed in one frame again.<br />
In our CMC application the startup was 400ms faster (2300ms vs. 2700ms).<br />
So <strong>15% faster startup</strong> with usePhasedInstantiation set to false in our application startup.</p>
<p>To be honest, I was expecting more. Maybe it is related to the fact that at our application startup (until the login screen) there are not many components created.<br />
I also tried to compare the 2 versions after the user has logged in and under heavy load with a lot of modules and windows open. I could not see a distinct difference but that was probably because of the complexity in this setup caused by a lot of network events.<br />
At least i could not see any problems with rendering. The application was not freezing in any state, so the reason why usePhasedInstantiation was introduced to make the startup more fluidly, does not show any effect in our application.</p>
<p><span class="hl">What is the conclusion?</span><br />
It does not improve the startup performance much if this property is changed (15% in our application), but I could imagine, when using a lot of components created all at once at startup time, the difference could be stronger. Maybe there could also be problems with freezing the rendering when setting the flag to false.</p>
<p>Even the result is for our use-case not much improvement, it was interesting to see how it is implemented, and to show that Flex is working fine <span class="hl">without the deferred lifecycle</span> as well. Also the technique how to exchange the SystemManager and how the implementation for a LayoutManager is configured, was an interesting learning.</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2011/03/23/not-easy-to-use-usephasedinstantiation/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Flex Life Cycle</title>
		<link>http://www.screenshot.at/blog/2011/01/20/flex-life-cycle/</link>
		<comments>http://www.screenshot.at/blog/2011/01/20/flex-life-cycle/#comments</comments>
		<pubDate>Thu, 20 Jan 2011 23:41:16 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[Architects]]></category>
		<category><![CDATA[As2]]></category>
		<category><![CDATA[As3]]></category>
		<category><![CDATA[Assumptions]]></category>
		<category><![CDATA[Auto Layout]]></category>
		<category><![CDATA[Bwin]]></category>
		<category><![CDATA[Containers]]></category>
		<category><![CDATA[Developers]]></category>
		<category><![CDATA[Explanations]]></category>
		<category><![CDATA[Flash Player]]></category>
		<category><![CDATA[Life-Cycle]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Performance Bottlenecks]]></category>
		<category><![CDATA[Performance Penalty]]></category>
		<category><![CDATA[Synchronous Code Execution]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=498</guid>
		<description><![CDATA[After working 10 years with Flash and 3 years with Flex I am still not convinced that the Flex Life Cycle is necessary. I discussed this topic already with many developers but nobody could really give me a satisfying answer. So I spread out my thoughts now to the public in the hope to get [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>After working 10 years with Flash and 3 years with Flex I am still not convinced that the <span class="hl">Flex Life Cycle</span> is necessary.</p>
<p>I discussed this topic already with many developers but nobody could really give me a satisfying answer.<br />
So I spread out my thoughts now to the public in the hope to get some valuable feedback.</p>
<p>Of course I am familiar with the concept of the <a href="http://livedocs.adobe.com/flex/3/html/help.html?content=ascomponents_advanced_2.html" target="_blank">Flex Life Cycle</a> and the &#8220;<a href="http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/" target="_blank">elastic racetrack</a>&#8221; behavior of the Flash Player.</p>
<p>The reason why I am not a friend of this concept is because it introduces an <span class="hl">asynchronous code execution</span> where a synchronous code execution would be much easier and faster.</p>
<p>In all my ActionScript based projects it was never necessary to use this pattern and defer code execution to another frame (or Render Event).<br />
At bwin we have built a similar application as the current Flex-based <a href="https://www.bwin.com/de/livebets.aspx" target="_blank">Live Betting application</a> previously in AS2, with a lot of complex components and auto layout containers, without running into any serious problems.<br />
And to be honest the performance of the AS2 project felt somehow the same as the Flex version. But AS3 is about 10 times faster (of course that´s a bit too simple said and we did not measure the difference, but I am not the only one complaining about poor Flex Performance).</p>
<p>So isn´t it valid to <span class="hl">question the concepts Flex is based on?</span></p>
<p>I am sure the architects at Adobe have had good reasons why they decided to introduce this pattern.<br />
In the Docs and Blogosphere one can find several papers about it, but none of these explanations satisfied me, and some are not telling the full truth (that code execution is deferred to another frame).</p>
<p>So I try to discuss <span class="hl">some assumptions</span> for possible reasons:</p>
<ul>
<li>Avoid Performance bottlenecks</li>
<li>Keep the Frame-rendering fluidly</li>
<li>Avoid Performance penalty from unintended repeated method (setter) calls</li>
<li>Pattern for separating different concerns</li>
<li>Problems with reading out the measurements of DisplayObjects before they are rendered on screen</li>
<li>Problems with complex execution flow from auto-layout containers code</li>
</ul>
<p>So let me add my thought to these points:<br />
<strong>Avoid Performance bottlenecks</strong></p>
<p>That was my first assumption when I started with Flex, that this pattern is used to avoid performance bottlenecks. First I thought there is a hidden mechanism for detecting code execution which is running too long and delay this execution to the next frame. After checking out the SDK code I found out that it is simply delaying the 3 phases to 3 &#8220;half-frames&#8221; (Render Events and Enter Frame Events). So if you have really heavy code your player is still freezing up for a certain time and the Life Cycle does not give you any support for solving this problem.</p>
<p>That leads to the next argument:<br />
<strong>Keep the Frame-rendering fluidly</strong></p>
<p>Delaying the render code to the next frame helps the Flash Player running more smoothly and fluidly. That is basically true, but in my opinion 90% of the time the Life Cycle is wasting performance. For me it is a bad trade to get maybe at startup time some more fluidly running pre-loader animation but startup time takes much longer.</p>
<p>Why the Life Cycle is wasting Performance?<br />
Because code which normally would be executed in one frame is now executed over 2 frames (or more).</p>
<p>There is another related issue with performance:<br />
<strong>Avoid Performance penalty from unintended repeated method (setter) calls</strong></p>
<p>Assume that in a large project it could be hard to control the execution flow so that it could happen that setting a text or layout property to a component is not only applied once but unintended multiple times.<br />
For this scenario the Life Cycle helps because the call to the setter of the property is relatively cheap, so if the setter is called 10 times instead of once it will not hurt much. Then at commitProperties the property is only applied once to the component.<br />
Again some weird scenarios with multiple invocations of commitProperties will not hurt much because the applying of the property to the component should be protected by a “changed” flag (see best practice with the Flex Life Cycle).<br />
Also if you need for layout code some measurements the pattern helps to avoid unnecessary and repeated code executions.<br />
BUT &#8211; is poorly written code really the reason why this pattern was introduced? It is true that it gives you some kind of fault tolerance, performance-wise. I guess this argument should not count in professional software development, and in fact it is dangerous because it could hide some deeper problems. If your setters are called more then once, why not look for the reason and clean it up?<br />
I know in complex situations this could be sometimes hard, and under real life circumstances and time pressure you have to deal with something like this. But it should not count as a criteria for such a basic framework design decision.</p>
<p>I made also some measurements to check out the performance penalties for repeatedly called setters:</p>
<p>With 100 000 iterations applying a changing text to a TextField (in a AS3 project) I got these results:</p>
<p>1. Case:<br />
Setting the text property to a variable in a loop and then applying the already stored text to the TextField again in a loop:</p>
<pre>[code lang="actionscript3"]setText(): 119ms
applyStoredText(): 481ms
[/code]</pre>
<p>In contrast to applying the property directly to the TextField:</p>
<pre>[code lang="actionscript3"]
setAndApplyText(): 2879ms
[/code]</pre>
<p>So you can see it is much slower in the 2. Case, so the Life Cycle really helps here, because it only applies the last stored property and not the changing values in between. But again &#8211; setting multiple times unnecessary property values is another problem.</p>
<p>The same test with setting the x position does not deliver such a big difference, in fact it is nearly the same time consumed (40+52 vs. 114)</p>
<pre>[code lang="actionscript3"]setXPos(): 40ms
applyStoredXPos(): 52ms
setAndApplyXPos(): 114ms
[/code]</pre>
<p>Let´s continue with the next point:<br />
<strong>Pattern for separating different concerns</strong></p>
<p>To have a kind of pattern which separates different concerns is basically a cool thing. So you have your code block for setting properties, another method where the properties are applied to the component, a method where the measurement is defined and another one for the layout code.</p>
<p>I have no really argument against this pattern, but I don´t know why it is necessary to defer some code of these phases to the next Frame. The execution of the Life Cycle methods could have been triggered also at the Render Event, then there would not have been any delay to another frame, even it still would add this nasty asynchrony.</p>
<p>So this pattern could make development easier but introduce asynchronous behavior where we lived in a beautiful synchronous Flash world before. In my opinion: Not a good trade.</p>
<p>What else?<br />
<strong>Problems with reading out the measurements of DisplayObjects before they are rendered on screen</strong></p>
<p>Remembering back to some of my Flash projects I have had sometimes strange problems with TextFields and measurement when setting text and using autosize. But I could not reproduce these problems in a test case anymore. So I am not sure if that was caused by some other stuff or maybe by differences in some older Flash Player versions? But at least in my situations these problems could always be solved without deferring code to another Frame. But at this point I am not sure if there are certain use cases where you cannot read out the size of a DisplayObject (TextField) before it is actually rendered to the screen. If there are such cases this would be a valid argument, but then I am wondering why this could not be solved on the Flash Player level instead of solving this problem at a Framework level.</p>
<p>And my last point:<br />
<strong>Problems with complex execution flow from auto-layout containers code</strong></p>
<p>I can imagine that complex situations with nested auto layout containers could be sometimes really tricky to handle. To avoid recursions or unnecessary calls for any possible situation in a generic framework is a tough challenge.</p>
<p>But also in complex situations it is a deterministic behavior, so it should be possible to solve this without the Life Cycle pattern as well. From my experience there was no problems with auto layout containers, but of course in normal project development you have limited use cases and we were not forced to deal with all the possible use cases, like Flex has to do as a generic framework.</p>
<p>So finally I don´t have any idea for the real reason why Adobe has introduced the Life Cycle.<br />
Maybe it seemed that it could help solving a lot of tricky problems (auto layout containers, mixing MXML with AS code,&#8230;) and was considered as a good pattern to make development easier. Maybe the fact that Flash has a strong support for Event driven programming and the Flash developers are already used to handle this asynchrony, led to this decision?<br />
Maybe is was a strategic decision to make Flex easier for new developers without Flash background, who were not familiar with the Flash Players frame-based execution model?</p>
<p>I don´t know. I really would appreciate if someone from the Flex Team could illuminate this topic.</p>
<p>I just have made the experience that many things where much more transparent, cleaner and faster in pure ActionScript then in Flex, and i think the Life Cycle is one of the reasons for that.<br />
I really like the <span class="hl">API of Flex</span> but I am wondering why Adobe don´t give more attention to performance, specially for large scale applications.</p>
<p>Any comments or insights are highly appreciated!</p>
<p>P.S.: Just found an interesting <a href="http://guyinthechair.com/tag/layoutmanager/" target="_blank">post</a> related to this. I 100% agree what Paul Taylor says about UIComponent, but that is another story. Ever heard about <a href="http://reflex.io/" target="_blank">Reflex</a>? Sounds pretty promising!</p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2011/01/20/flex-life-cycle/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>A question of style</title>
		<link>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/</link>
		<comments>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/#comments</comments>
		<pubDate>Fri, 08 Jan 2010 00:03:02 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[Button Color]]></category>
		<category><![CDATA[Button Style]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[Constructor]]></category>
		<category><![CDATA[css]]></category>
		<category><![CDATA[Css Code]]></category>
		<category><![CDATA[Css File]]></category>
		<category><![CDATA[Css Files]]></category>
		<category><![CDATA[CSSStyleDeclaration]]></category>
		<category><![CDATA[Custom Components]]></category>
		<category><![CDATA[Definitions]]></category>
		<category><![CDATA[Developers]]></category>
		<category><![CDATA[External Css]]></category>
		<category><![CDATA[Mx]]></category>
		<category><![CDATA[Mxml]]></category>
		<category><![CDATA[Null]]></category>
		<category><![CDATA[Selectors]]></category>
		<category><![CDATA[Strange Problems]]></category>
		<category><![CDATA[Style]]></category>
		<category><![CDATA[Swf]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=454</guid>
		<description><![CDATA[If you ever had some strange problems with styles in Flex, you might want to know how styles are internally handled and implemented. Ok this post will not cover too much of all the stuff going on there, but a bit of the basics how styles are finding their way from the css file to [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>If you ever had some strange problems with styles in Flex, you might want to know how styles are internally handled and implemented.<br />
Ok this post will not cover too much of all the stuff going on there, but a bit of the basics <span class="hl">how styles are finding their way</span> from the css file to your component.</p>
<p>Lets assume that we have a css file with type selectors and class selectors, a module based application and some custom components which are designed the way that you can use them out of the box and that they can be individually skinned and styled by other developers reusing them. That´s what custom components are for, right?</p>
<p>So the first question is:<br />
<span class="hl">How are the styles compiled into your swf file?</span><br />
Assume that they are defined in an external css file. You know you can compile css files to swf files and load them at runtime or simply compile them into your application at compile time with a simple assignment  like this:</p>
<pre>[code lang="actionscript3"]
<mx:Style source="assets/styles.css"/> 
[/code]</pre>
<p>Here is the content of our simple css:</p>
<pre>[code lang="actionscript3"]
Button
{
	color: #990000;
}
.myCustomStyle1
{
	color: #009900;
}
 /*
     some additional styles here...
     like Button.myCustomStyle2
*/
[/code]</pre>
<p>That´s what we will use for our example here.</p>
<p>In this case the MXML compiler creates a bunch of classes and inserts the css definitions right into a method called from the constructor in the generated Applications class.</p>
<pre>[code lang="actionscript3"]
public function StyleExample() {
	mx_internal::_StyleExample_StylesInit();
}
mx_internal function _StyleExample_StylesInit():void {
	var style:CSSStyleDeclaration;
	// Button
	style = StyleManager.getStyleDeclaration("Button");
	if (!style) {
		style = new CSSStyleDeclaration();
		StyleManager.setStyleDeclaration("Button", style, false);
	}
	if (style.factory == null) {
		style.factory = function():void {
			this.color = 0x990000;
		};
	}
	// myCustomStyle1
	style = StyleManager.getStyleDeclaration(".myCustomStyle1");
	if (!style)
	{
		style = new CSSStyleDeclaration();
		StyleManager.setStyleDeclaration(".myCustomStyle1",
                                           style, false);
	}
	if (style.factory == null)
	{
		style.factory = function():void
		{
			this.color = 0x009900;
		};
	}
	// similar code follows here....
}
[/code]</pre>
<p>I only pasted the relevant code, so this is not complete but should give the basic idea.<br />
So what happens here?<br />
<span id="more-454"></span><br />
A CSSStyleDeclaration is created for the given stylename or class if it´s not already existing in the StyleManager (at a modular application some other application could have already created this style). Then the definitions from the css file (here the color property) are added to the factory function.<br />
It is interesting that the class selectors and type selectors are treated the same way regarding storing the style object in the StyleManager. It is simply the selector name which is used as the key in the _selectors Object (hashtable). Only the &#8220;.&#8221; in the selector name is the visible difference.</p>
<pre>[code lang="actionscript3"]
    public function setStyleDeclaration(
                                selector:String,
                                styleDeclaration:CSSStyleDeclaration,
                                update:Boolean):void
    {
        styleDeclaration.selectorRefCount++;

        _selectors[selector] = styleDeclaration;

        // Flush cache and start over.
        typeSelectorCache = {};

        if (update)
            styleDeclarationsChanged();
    }
[/code]</pre>
<p>The CSSStyleDeclaration has also a defaultFactory which is used if there is no factory defined (no css file). Additionally there is an overrides Object which is used to store styles set at runtime vial setStyle(), but this will not be further considered yet.<br />
This leads us to the next part:<br />
<span class="hl">How should a default style be applied to a custom component?</span></p>
<p>How Flex is handling this? The MXML compiler generates a bunch of style classes:<br />
For instance a style class for the Button:</p>
<pre>[code lang="actionscript3"]
public class _ButtonStyle
{
    public static function init(fbs:IFlexModuleFactory):void
    {
        var style:CSSStyleDeclaration =
                         StyleManager.getStyleDeclaration("Button");
        if (!style)
        {
            style = new CSSStyleDeclaration();
            StyleManager.setStyleDeclaration("Button", style, false);
        }
        if (style.defaultFactory == null)
        {
            style.defaultFactory = function():void
            {
                this.fontWeight = "bold";
                this.paddingTop = 2;
                this.cornerRadius = 4;
                this.textAlign = "center";
                this.verticalGap = 2;
                this.horizontalGap = 2;
                this.skin = mx.skins.halo.ButtonSkin;
                this.paddingLeft = 10;
                this.paddingBottom = 2;
                this.paddingRight = 10;
            };
        }
    }
}
[/code]</pre>
<p>This class is added to the mixins array at the generated _StyleExample_mx_managers_SystemManager class.<br />
The <span class="hl">mixins</span> are a strategy to get injected some code at application startup before anything else is instantiated. It calls the static init method, so it is executed before the actual classes constructor is called.<br />
A similar strategy with a static initializer is used in some classes in the datavisualisation package to pack some default styles into a component, so that there is no dependency that there are some styles assigned to the component from outside.<br />
That´s seems to be a pretty nice way to setup the default style a component needs. If the user of the component wants to set some different styles, it can be applied easily via css, styles set in mxml or at runtime via setStyle (if possible, this should be done in the preInitialize phase to avoid performance penalties).</p>
<p>One thing which should be considered when using styles (specially in a large application with modules) is the fact that the style declarations are stored with the selector name as key in an Object (hashtable). So if 2 developers are using the <span class="hl">same selector name</span> they end up with a conflict that the later instantiated module will use the already created style and not the one which was compiled to the module.<br />
The same applies if you use the same stylename inside one application, the first one used wins.<br />
To get rid of this problem a kind of namespace strategy can be used ([modulename] + &#8220;stylename&#8221;). Unfortunately the Flex framework does not give any support for this problem.<br />
Tell me if you know a more elegant solution!</p>
<div id="gmBFtt" style="border: 1px solid black ! important; margin: 0px ! important; padding: 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; left: 194px ! important; top: 1926px ! important; visibility: visible ! important; display: inline ! important; width: auto; height: auto ! important; position: absolute ! important; text-align: left ! important; z-index: 1410065406 ! important;">
<div style="border-bottom: 1px dotted black ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; padding-bottom: 2px ! important; padding-top: 2px ! important;"><span id="bfconfigButton" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="Language configuration">Lang</span><span id="bfdetectButton" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer;" title="Detect and set language">Detect</span><span id="bflangsSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="From English To German (switch direction)">en&gt;de </span><span id="bfsvcSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: pointer ! important;" title="Translation service: Yahoo (switch service)">Yahoo</span><span id="bfclipboardSpan" style="border: 1px dotted gray ! important; margin: 1px ! important; padding: 0px 2px ! important; background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; cursor: copy ! important;" title="Copy result to clipboard">C</span><img id="bffishImg" style="border: medium none  ! important; margin: 0px ! important; float: none ! important; vertical-align: top ! important; cursor: pointer ! important; display: inline ! important;" title="Click to translate" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABwAAAAOCAYAAAA8E3wEAAAABmJLR0QA/wD/AP+gvaeTAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAB3RJTUUH1QUUDyoqJjAqRwAAAN1JREFUOMu1lMkVwyAMBYe0JGpCNUFNVk3k4AUwxPGS+ILxkzX8jyTH/Sfu9nrmJ3cXlnMASyWRPwd2d5XlHCBZn1BthcbRAdxTZQDI8k3mQzg11rhF+QZ9jdNOcQib6GFQYJYgCFucSRf6GsLU6wEY5yubTFqF2yq1vRwr3INXdQUWG+je1pELX4ED1wDyRAR0WfuAA9gloITyvsFMIMgYInYRqF6rO9Sqz9qkO5ilyo0o3YBwJ+6vrdQonxWUQllhXeHcb/wabMPkP2n81ocAIoLZrMqn/4y2RwP8DcQ+d6rT9ATiAAAAAElFTkSuQmCC" alt="" /></div>
<div style="background: #a8ecff none repeat scroll 0% 0% ! important; font-family: arial ! important; font-size: 12px ! important; color: #000000 ! important; line-height: normal ! important; font-weight: normal ! important; vertical-align: middle ! important; width: auto;">MXML</div>
</div>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2010/01/08/a-question-of-style/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The infamous callLater()</title>
		<link>http://www.screenshot.at/blog/2009/05/05/the-infamous-calllater/</link>
		<comments>http://www.screenshot.at/blog/2009/05/05/the-infamous-calllater/#comments</comments>
		<pubDate>Tue, 05 May 2009 23:03:24 +0000</pubDate>
		<dc:creator><![CDATA[Manfred Karrer]]></dc:creator>
				<category><![CDATA[Actionscript]]></category>
		<category><![CDATA[Flash]]></category>
		<category><![CDATA[Flashplayer]]></category>
		<category><![CDATA[Flex]]></category>
		<category><![CDATA[SDK]]></category>
		<category><![CDATA[anatomy of a frame]]></category>
		<category><![CDATA[Asynchronism]]></category>
		<category><![CDATA[AVM2]]></category>
		<category><![CDATA[CallLater]]></category>
		<category><![CDATA[Half-Fram]]></category>
		<category><![CDATA[Layout Engine]]></category>
		<category><![CDATA[Layout Mechanism]]></category>
		<category><![CDATA[Life-Cycle]]></category>
		<category><![CDATA[Marshalled Slice]]></category>
		<category><![CDATA[Performance]]></category>
		<category><![CDATA[Phased Instantiation]]></category>
		<category><![CDATA[player events]]></category>
		<category><![CDATA[player render]]></category>
		<category><![CDATA[prerender event]]></category>
		<category><![CDATA[Render]]></category>
		<category><![CDATA[Sean Christmann]]></category>
		<category><![CDATA[UsePhasedInstantiation]]></category>
		<category><![CDATA[user code]]></category>

		<guid isPermaLink="false">http://www.screenshot.at/blog/?p=298</guid>
		<description><![CDATA[At my first posts I wrote about my favorite Flex feature: Databinding Now I will take a look at the opposite, IMHO the most precarious &#8220;feature&#8221; in Flex: callLater() If you have a dodgy problem that a certain property is not available when it already should be and you ask someone at flexcoders you often [&#8230;]]]></description>
				<content:encoded><![CDATA[<p>At my first posts I wrote about my favorite Flex feature: Databinding<br />
Now I will take a look at the opposite, IMHO the most precarious &#8220;feature&#8221; in Flex: <span class="hl">callLater()</span></p>
<p>If you have a dodgy problem that a certain property is not available when it already should be and you ask someone at <a href="http://tech.groups.yahoo.com/group/flexcoders/" target="_blank">flexcoders</a> you often get the advice, <em>&#8220;try callLater&#8221;</em> for a quick work-around. Sometimes this helps, but it leaves a bad smell, because often it´s just hiding some other problems in the code.<br />
So when we worked on a large-scale Flex application we have used it sometimes in the beginning, but after a while we decided to avoid callLater. To find and solve the real problem is simply the better solution &#8211; and we never needed it again &#8211; there was always another solution to solve a particular problem (maybe we just have had luck).</p>
<p>Unpleasantly we get confronted with the fact that callLater is used inside the Framework at the <strong>heart of the layout engine</strong>.<br />
We struggled with some strange problems. For instance we got a NullPointer exception in the updateDisplayList method of a custom component, which has already been cleaned up properly and removed from the displayList. It turned out that the layout mechanism delayed with callLater an invocation of updateDisplayList but our stuff there has already been removed and threw an exception.<br />
It was not hard to fix, but it demonstrated us that some asynchronous stuff was going on behind the scenes which was out of our direct control.</p>
<p>So for me callLater leaves always a certain bad smell.</p>
<p>Unfortunately I never found time to really investigate how it´s implemented and what are the concepts behind it.<br />
So it was time to <span class="hl">catch up</span> with this issue:<br />
CallLater is basically a method in UIComponent which delays a passed function to the next <strong>EnterFrame OR Render</strong> event.<br />
Often in den docs it´s just described that it will delay to the next frame, which is not correct because it could be that your function is executed already at the Render Event, which happens in the same frame and is the last opportunity where User code can be executed before the screen is rendered.</p>
<p>For more details about the internal concept of a frame in Flash and the relevant events see the great article by <a href="http://www.craftymind.com/2008/04/18/updated-elastic-racetrack-for-flash-9-and-avm2/" target="_blank">Sean Christmann</a>:</p>
<p>Here is a good illustration from his article about the <strong>anatomy of a frame</strong> in Flash:<br />
<span id="more-298"></span><br />
<img class="alignnone size-full wp-image-308" title="marshalledsliceexport" src="http://www.screenshot.at/blog/wp-content/uploads/2009/05/marshalledsliceexport.png" alt="marshalledsliceexport" width="500" height="220" /></p>
<p>All functions passed to callLater are queued up in an array and are executed at the EnterFrame event or Render event. It is possible that the executed function has some other callLater invocations again, so the final execution sequence could be delayed over several frames.</p>
<p>CallLater is used inside the Flex Framework in several classes. The main use case is probably inside the <strong>LayoutManager</strong>.<br />
There is a concept called <strong>phased instantiation</strong> which means basically that at application start-up the 3 phases in the UIComponents life-cycle (validate properties, validate size and validate displayList) are not executed in one pass, but are delayed with callLater to 3 half-frames. <strong>Half-frame</strong> because the Render event happens in the same frame as the EnterFrame event.<br />
This should reduce performance peaks at application-startup and should increase the UIs responsiveness.<br />
You can also use it later on in your application if you have to render heavy stuff, to balance the load across frames.</p>
<p><span class="hl">So far so good. But&#8230;</span><br />
First let me emphasis that I am sure that the SDK architects has had some good reasons for implementing callLater, but it <strong>introduces an asynchronism</strong> which could be hard to control. Normally with async stuff you have an event driven approach, so you get informed when the async task is done.<br />
With callLater it´s not so clear when the last callLater is really finished. There is an UpdateComplete event in UIComponent and LayoutManager which helps to get informed when the last callLater is executed, but in-between, you don´t have control about the distinct moments of your function calls.</p>
<p>Another issue is that you cannot control if your heavy load is really spread over 2 frames. It could be that it is just executed inside one frame at the EnterFrame event and at the Render event, so it could be that you don´t win anything from the load-balancing perspective.</p>
<p>Performance-wise there could also be perceptible delays caused by repeatedly callLater executions.</p>
<p>I guess there are many special situations in the framework code (probably mostly measurement stuff) which are difficult to handle, but i guess it <em>should</em> be possible (maybe I am too optimistic?).</p>
<p>There seems to be a problem to get the correct measurement when you set a new text in a TextField before the frame is actually rendered (see <a href="http://tech.groups.yahoo.com/group/flexcoders/message/121060" target="_blank"> this post</a> at flexcoders), but if this is an unsolvable problem then it should be urgently fixed in the Flash Player.</p>
<p>References@livedocs:<br />
<a href="http://livedocs.adobe.com/flex/3/langref/mx/core/UIComponent.html#callLater()" target="_blank">callLater()</a><br />
<a href="http://livedocs.adobe.com/flex/3/langref/mx/managers/LayoutManager.html#usePhasedInstantiation" target="_blank">usePhasedInstantiation</a></p>
]]></content:encoded>
			<wfw:commentRss>http://www.screenshot.at/blog/2009/05/05/the-infamous-calllater/feed/</wfw:commentRss>
		<slash:comments>4</slash:comments>
		</item>
	</channel>
</rss>
