1////////////////////////////////////////////////////////////////////////////////
2//
3//  ADOBE SYSTEMS INCORPORATED
4//  Copyright 2007 Adobe Systems Incorporated
5//  All Rights Reserved.
6//
7//  NOTICE: Adobe permits you to use, modify, and distribute this file
8//  in accordance with the terms of the license agreement accompanying it.
9//
10////////////////////////////////////////////////////////////////////////////////
11
12package mx.managers
13{
14
15import flash.display.DisplayObject;
16import flash.display.DisplayObjectContainer;
17import flash.display.Graphics;
18import flash.display.InteractiveObject;
19import flash.display.Loader;
20import flash.display.LoaderInfo;
21import flash.display.MovieClip;
22import flash.display.Sprite;
23import flash.display.Stage;
24import flash.display.StageAlign;
25import flash.display.StageScaleMode;
26import flash.events.Event;
27import flash.events.IEventDispatcher;
28import flash.events.MouseEvent;
29import flash.geom.Point;
30import flash.geom.Rectangle;
31import flash.net.getClassByAlias;
32import flash.net.registerClassAlias;
33import flash.system.ApplicationDomain;
34import flash.text.Font;
35import flash.text.TextFormat;
36import flash.ui.ContextMenu;
37import flash.utils.ByteArray;
38import flash.utils.Dictionary;
39
40import mx.core.EventPriority;
41import mx.core.FlexSprite;
42import mx.core.IChildList;
43import mx.core.IFlexDisplayObject;
44import mx.core.IFlexModule;
45import mx.core.IFlexModuleFactory;
46import mx.core.IUIComponent;
47import mx.core.RSLData;
48import mx.core.Singleton;
49import mx.core.IWindow;
50import mx.core.mx_internal;
51import mx.events.SandboxMouseEvent;
52import mx.events.DynamicEvent;
53import mx.events.FlexEvent;
54import mx.events.EventListenerRequest;
55import mx.events.Request;
56import mx.managers.systemClasses.ChildManager;
57import mx.styles.ISimpleStyleClient;
58import mx.styles.IStyleClient;
59import mx.utils.NameUtil;
60import mx.utils.ObjectUtil;
61
62use namespace mx_internal;
63
64/**
65 *  The WindowedSystemManager class manages any non-Application windows in a
66 *  Flex-based AIR application. This includes all windows that are instances of
67 *  the Window component or a Window subclass, but not a WindowedApplication
68 *  window. For those windows, the WindowedSystemManager serves the same role
69 *  that a SystemManager serves for a WindowedApplication instance or an
70 *  Application instance in a browser-based Flex application.
71 *
72 *  <p>As this comparison suggests, the WindowedSystemManager class serves
73 *  many roles. For instance, it is the root display object of a Window, and
74 *  manages tooltips, cursors, popups, and other content for the Window.</p>
75 *
76 *  @see mx.managers.SystemManager
77 *
78 *
79 *  @langversion 3.0
80 *  @playerversion AIR 1.1
81 *  @productversion Flex 3
82 */
83public class WindowedSystemManager extends MovieClip implements ISystemManager
84{
85
86    public function WindowedSystemManager(rootObj:IUIComponent)
87    {
88        super();
89        _topLevelSystemManager = this;
90        topLevelWindow = rootObj;
91        SystemManagerGlobals.topLevelSystemManagers.push(this);
92        childManager = new ChildManager(this);
93        //docFrameHandler(null);
94        addEventListener(Event.ADDED, docFrameHandler);
95    }
96
97	mx_internal var topLevel:Boolean = true;
98
99	private var initialized:Boolean = false;
100
101	/**
102	 *  @private
103	 *  The top level window.
104	 */
105	mx_internal var topLevelWindow:IUIComponent;
106
107	/**
108	 *  @private
109	 *  pointer to Window, for cleanup
110	 */
111	private var myWindow:IWindow;
112
113	/**
114	 *  @private
115	 */
116	private var _topLevelSystemManager:ISystemManager;
117
118    /**
119     *  @private
120     *  The childAdded/removed code
121     */
122    mx_internal var childManager:ISystemManagerChildManager;
123
124	/**
125	 *  @private
126	 *  Whether we are the stage root or not.
127	 *  We are only the stage root if we were the root
128	 *  of the first SWF that got loaded by the player.
129	 *  Otherwise we could be top level but not stage root
130	 *  if we are loaded by some other non-Flex shell
131	 *  or are sandboxed.
132	 */
133	private var isStageRoot:Boolean = true;
134
135    /**
136     *  @private
137     *  Number of frames since the last mouse or key activity.
138     */
139    mx_internal var idleCounter:int = 0;
140
141    /**
142     *  @private
143     *  Whether we are the first SWF loaded into a bootstrap
144     *  and therefore, the topLevelRoot
145     */
146    private var isBootstrapRoot:Boolean = false;
147
148    /**
149     *  Depth of this object in the containment hierarchy.
150     *  This number is used by the measurement and layout code.
151     *
152     *  @langversion 3.0
153     *  @playerversion AIR 1.1
154     *  @productversion Flex 3
155     */
156    mx_internal var nestLevel:int = 0;
157
158	/**
159	 *  @private
160	 *  The mouseCatcher is the 0th child of the SystemManager,
161	 *  behind the application, which is child 1.
162	 *  It is the same size as the stage and is filled with
163	 *  transparent pixels; i.e., they've been drawn, but with alpha 0.
164	 *
165	 *  Its purpose is to make every part of the stage
166	 *  able to detect the mouse.
167	 *  For example, a Button puts a mouseUp handler on the SystemManager
168	 *  in order to capture mouseUp events that occur outside the Button.
169	 *  But if the children of the SystemManager don't have "drawn-on"
170	 *  pixels everywhere, the player won't dispatch the mouseUp.
171	 *  We can't simply fill the SystemManager itself with
172	 *  transparent pixels, because the player's pixel detection
173	 *  logic doesn't look at pixels drawn into the root DisplayObject.
174	 *
175	 *  Here is an example of what would happen without the mouseCatcher:
176	 *  Run a fixed-size Application (e.g. width="600" height="600")
177	 *  in the standalone player. Make the player window larger
178	 *  to reveal part of the stage. Press a Button, drag off it
179	 *  into the stage area, and release the mouse button.
180	 *  Without the mouseCatcher, the Button wouldn't return to its "up" state.
181	 */
182	private var mouseCatcher:Sprite;
183
184    //----------------------------------
185    //  applicationIndex
186    //----------------------------------
187
188    /**
189     *  @private
190     *  Storage for the applicationIndex property.
191     */
192    private var _applicationIndex:int = 1;
193
194    /**
195     *  @private
196     *  The index of the main mx.core.Application window, which is
197     *  effectively its z-order.
198     */
199    mx_internal function get applicationIndex():int
200    {
201        return _applicationIndex;
202    }
203
204    /**
205     *  @private
206     */
207    mx_internal function set applicationIndex(value:int):void
208    {
209        _applicationIndex = value;
210    }
211
212
213    //-----------------------------------
214    //  ISystemManager implementations
215    //-----------------------------------
216
217    //----------------------------------
218    //  allowDomainsInNewRSLs
219    //----------------------------------
220
221    /**
222     *  @private
223     */
224    private var _allowDomainsInNewRSLs:Boolean = true;
225
226    /**
227     *  @inheritDoc
228     *
229     *  @langversion 3.0
230     *  @playerversion Flash 10.2
231     *  @playerversion AIR 2.6
232     *  @productversion Flex 4.5
233     */
234    public function get allowDomainsInNewRSLs():Boolean
235    {
236        return _allowDomainsInNewRSLs;
237    }
238
239    /**
240     *  @private
241     */
242    public function set allowDomainsInNewRSLs(value:Boolean):void
243    {
244        _allowDomainsInNewRSLs = value;
245    }
246
247    //----------------------------------
248    //  allowInsecureDomainsInNewRSLs
249    //----------------------------------
250
251    /**
252     *  @private
253     */
254    private var _allowInsecureDomainsInNewRSLs:Boolean = true;
255
256    /**
257     *  @inheritDoc
258     *
259     *  @langversion 3.0
260     *  @playerversion Flash 10.2
261     *  @playerversion AIR 2.6
262     *  @productversion Flex 4.5
263     */
264    public function get allowInsecureDomainsInNewRSLs():Boolean
265    {
266        return _allowInsecureDomainsInNewRSLs;
267    }
268
269    /**
270     *  @private
271     */
272    public function set allowInsecureDomainsInNewRSLs(value:Boolean):void
273    {
274        _allowInsecureDomainsInNewRSLs = value;
275    }
276
277    //----------------------------------
278    //  cursorChildren
279    //----------------------------------
280
281    /**
282     *  @private
283     *  Storage for the cursorChildren property.
284     */
285    private var _cursorChildren:WindowedSystemChildrenList;
286
287    /**
288     *  @inheritDoc
289     *
290     *  @langversion 3.0
291     *  @playerversion AIR 1.1
292     *  @productversion Flex 3
293     */
294    public function get cursorChildren():IChildList
295    {
296        if (!topLevel)
297            return _topLevelSystemManager.cursorChildren;
298
299        if (!_cursorChildren)
300        {
301            _cursorChildren = new WindowedSystemChildrenList(this,
302                new QName(mx_internal, "toolTipIndex"),
303                new QName(mx_internal, "cursorIndex"));
304        }
305
306        return _cursorChildren;
307    }
308
309    //----------------------------------
310    //  cursorIndex
311    //----------------------------------
312
313    /**
314     *  @private
315     *  Storage for the toolTipIndex property.
316     */
317    private var _cursorIndex:int = 0;
318
319    /**
320     *  @private
321     *  The index of the highest child that is a cursor.
322     */
323    mx_internal function get cursorIndex():int
324    {
325        return _cursorIndex;
326    }
327
328    /**
329     *  @private
330     */
331    mx_internal function set cursorIndex(value:int):void
332    {
333        var delta:int = value - _cursorIndex;
334        _cursorIndex = value;
335    }
336
337    //----------------------------------
338    //  document
339    //----------------------------------
340
341    /**
342     *  @private
343     *  Storage for the document property.
344     */
345    private var _document:Object;
346
347    /**
348     *  @inheritDoc
349     *
350     *  @langversion 3.0
351     *  @playerversion AIR 1.1
352     *  @productversion Flex 3
353     */
354    public function get document():Object
355    {
356        return _document;
357    }
358
359    /**
360     *  @private
361     */
362    public function set document(value:Object):void
363    {
364        _document = value;
365    }
366
367    //----------------------------------
368    //  embeddedFontList
369    //----------------------------------
370
371    /**
372     *  @private
373     *  Storage for the fontList property.
374     */
375    private var _fontList:Object = null;
376
377    /**
378     *  A table of embedded fonts in this application.  The
379     *  object is a table indexed by the font name.
380     *
381     *  @langversion 3.0
382     *  @playerversion AIR 1.1
383     *  @productversion Flex 3
384     */
385    public function get embeddedFontList():Object
386    {
387        if (_fontList == null)
388        {
389            _fontList = {};
390
391            var o:Object = info()["fonts"];
392
393            var p:String;
394
395            for (p in o)
396            {
397                _fontList[p] = o[p];
398            }
399
400            // Top level systemManager may not be defined if SWF is loaded
401            // as a background image in download progress bar.
402            if (!topLevel && _topLevelSystemManager)
403            {
404                var fl:Object = _topLevelSystemManager.embeddedFontList;
405                for (p in fl)
406                {
407                    _fontList[p] = fl[p];
408                }
409            }
410        }
411
412        return _fontList;
413    }
414
415    //----------------------------------
416    //  focusPane
417    //----------------------------------
418
419    /**
420     *  @private
421     */
422    private var _focusPane:Sprite;
423
424    /**
425     *  @copy mx.core.UIComponent#focusPane
426     *
427     *  @langversion 3.0
428     *  @playerversion AIR 1.1
429     *  @productversion Flex 3
430     */
431    public function get focusPane():Sprite
432    {
433        return _focusPane;
434    }
435
436    /**
437     *  @private
438     */
439    public function set focusPane(value:Sprite):void
440    {
441        if (value)
442        {
443            addChild(value);
444
445            value.x = 0;
446            value.y = 0;
447            value.scrollRect = null;
448
449            _focusPane = value;
450        }
451        else
452        {
453            removeChild(_focusPane);
454
455            _focusPane = null;
456        }
457    }
458
459    //----------------------------------
460    //  isProxy
461    //----------------------------------
462
463	/**
464	 *  True if SystemManager is a proxy and not a root class
465	 */
466	public function get isProxy():Boolean
467	{
468		return false;
469	}
470
471	//----------------------------------
472	//  $numChildren
473	//----------------------------------
474
475    /**
476     *  @private
477     *  This property allows access to the Player's native implementation
478     *  of the numChildren property, which can be useful since components
479     *  can override numChildren and thereby hide the native implementation.
480     *  Note that this "base property" is final and cannot be overridden,
481     *  so you can count on it to reflect what is happening at the player level.
482     */
483    mx_internal final function get $numChildren():int
484    {
485        return super.numChildren;
486    }
487
488    //----------------------------------
489    //  numModalWindows
490    //----------------------------------
491
492    /**
493     *  @private
494     *  Storage for the numModalWindows property.
495     */
496    private var _numModalWindows:int = 0;
497
498    /**
499     *  The number of modal windows.  Modal windows don't allow
500     *  clicking in another windows which would normally
501     *  activate the FocusManager in that window.  The PopUpManager
502     *  modifies this count as it creates and destroys modal windows.
503     *
504     *  @langversion 3.0
505     *  @playerversion AIR 1.1
506     *  @productversion Flex 3
507     */
508    public function get numModalWindows():int
509    {
510        return _numModalWindows;
511    }
512
513    /**
514     *  @private
515     */
516    public function set numModalWindows(value:int):void
517    {
518        _numModalWindows = value;
519    }
520//----------------------------------
521    //  popUpChildren
522    //----------------------------------
523
524    /**
525     *  @private
526     *  Storage for the popUpChildren property.
527     */
528    private var _popUpChildren:WindowedSystemChildrenList;
529
530    //----------------------------------
531    //  preloadedRSLs
532    //----------------------------------
533
534    /**
535     *  @private
536     *
537     *  This is a stub to satisfy the IFlexModuleFactory interface.
538     */
539    public function  get preloadedRSLs():Dictionary
540    {
541        return null;
542    }
543
544    /**
545     *  @inheritDoc
546     *
547     *  @langversion 3.0
548     *  @playerversion AIR 1.1
549     *  @productversion Flex 3
550     */
551    public function get popUpChildren():IChildList
552    {
553        if (!topLevel)
554            return _topLevelSystemManager.popUpChildren;
555
556        if (!_popUpChildren)
557        {
558            _popUpChildren = new WindowedSystemChildrenList(this,
559                new QName(mx_internal, "noTopMostIndex"),
560                new QName(mx_internal, "topMostIndex"));
561        }
562
563        return _popUpChildren;
564    }
565
566    //----------------------------------
567    //  noTopMostIndex
568    //----------------------------------
569
570    /**
571     *  @private
572     *  Storage for the noTopMostIndex property.
573     */
574    private var _noTopMostIndex:int = 0;
575
576    /**
577     *  @private
578     *  The index of the highest child that isn't a topmost/popup window
579     */
580    mx_internal function get noTopMostIndex():int
581    {
582        return _noTopMostIndex;
583    }
584
585    /**
586     *  @private
587     */
588    mx_internal function set noTopMostIndex(value:int):void
589    {
590        var delta:int = value - _noTopMostIndex;
591        _noTopMostIndex = value;
592        topMostIndex += delta;
593    }
594    //----------------------------------
595    //  rawChildren
596    //----------------------------------
597
598    /**
599     *  @private
600     *  Storage for the rawChildren property.
601     */
602    private var _rawChildren:WindowedSystemRawChildrenList;
603
604    /**
605     *  @inheritDoc
606     *
607     *  @langversion 3.0
608     *  @playerversion AIR 1.1
609     *  @productversion Flex 3
610     */
611    public function get rawChildren():IChildList
612    {
613        if (!topLevel)
614            return _topLevelSystemManager.rawChildren;
615
616        if (!_rawChildren)
617            _rawChildren = new WindowedSystemRawChildrenList(this);
618
619        return _rawChildren;
620    }
621
622    //--------------------------------------------------------------------------
623    //  screen
624    //--------------------------------------------------------------------------
625
626    /**
627     *  @private
628     *  Storage for the screen property.
629     */
630    mx_internal var _screen:Rectangle;
631
632    /**
633     *  @inheritDoc
634     *
635     *  @langversion 3.0
636     *  @playerversion AIR 1.1
637     *  @productversion Flex 3
638     */
639    public function get screen():Rectangle
640    {
641        if (!_screen)
642            _screen = new Rectangle();
643        _screen.x = 0;
644        _screen.y = 0;
645        _screen.width = stage.stageWidth; //Capabilities.screenResolutionX;
646        _screen.height = stage.stageHeight; //Capabilities.screenResolutionY;
647
648
649        return _screen;
650    }
651
652    //----------------------------------
653    //  toolTipChildren
654    //----------------------------------
655
656    /**
657     *  @private
658     *  Storage for the toolTipChildren property.
659     */
660    private var _toolTipChildren:WindowedSystemChildrenList;
661
662    /**
663     *  @inheritDoc
664     *
665     *  @langversion 3.0
666     *  @playerversion AIR 1.1
667     *  @productversion Flex 3
668     */
669    public function get toolTipChildren():IChildList
670    {
671        if (!topLevel)
672            return _topLevelSystemManager.toolTipChildren;
673
674        if (!_toolTipChildren)
675        {
676            _toolTipChildren = new WindowedSystemChildrenList(this,
677                new QName(mx_internal, "topMostIndex"),
678                new QName(mx_internal, "toolTipIndex"));
679        }
680
681        return _toolTipChildren;
682    }
683    //----------------------------------
684    //  toolTipIndex
685    //----------------------------------
686
687    /**
688     *  @private
689     *  Storage for the toolTipIndex property.
690     */
691    private var _toolTipIndex:int = 0;
692
693    /**
694     *  @private
695     *  The index of the highest child that is a tooltip
696     */
697    mx_internal function get toolTipIndex():int
698    {
699        return _toolTipIndex;
700    }
701
702    /**
703     *  @private
704     */
705    mx_internal function set toolTipIndex(value:int):void
706    {
707        var delta:int = value - _toolTipIndex;
708        _toolTipIndex = value;
709        cursorIndex += delta;
710    }
711
712    //----------------------------------
713    //  topLevelSystemManager
714    //----------------------------------
715
716    /**
717     *  Returns the SystemManager responsible for the application window.  This will be
718     *  the same SystemManager unless this application has been loaded into another
719     *  application.
720     *
721     *  @langversion 3.0
722     *  @playerversion AIR 1.1
723     *  @productversion Flex 3
724     */
725    public function get topLevelSystemManager():ISystemManager
726    {
727        if (topLevel)
728            return this;
729
730        return _topLevelSystemManager;
731    }
732
733    //----------------------------------
734    //  topMostIndex
735    //----------------------------------
736
737    /**
738     *  @private
739     *  Storage for the topMostIndex property.
740     */
741    private var _topMostIndex:int = 0;
742
743    /**
744     *  @private
745     *  The index of the highest child that is a topmost/popup window
746     */
747    mx_internal function get topMostIndex():int
748    {
749        return _topMostIndex;
750    }
751
752    mx_internal function set topMostIndex(value:int):void
753    {
754        var delta:int = value - _topMostIndex;
755        _topMostIndex = value;
756        toolTipIndex += delta;
757    }
758
759    //----------------------------------
760    //  width
761    //----------------------------------
762
763    /**
764     *  @private
765     */
766    private var _width:Number;
767
768    /**
769     *  The width of this object.  For the SystemManager
770     *  this should always be the width of the stage unless the application was loaded
771     *  into another application.  If the application was not loaded
772     *  into another application, setting this value will have no effect.
773     *
774     *  @langversion 3.0
775     *  @playerversion AIR 1.1
776     *  @productversion Flex 3
777     */
778    override public function get width():Number
779    {
780        return _width;
781    }
782
783    //----------------------------------
784    //  window
785    //----------------------------------
786    /**
787     *  @private
788     */
789    private var _window:IWindow = null;
790
791    mx_internal function get window():IWindow
792    {
793        return _window;
794    }
795
796    mx_internal function set window(value:IWindow):void
797    {
798        _window = value;
799    }
800
801
802     //----------------------------------
803    //  height
804    //----------------------------------
805
806    /**
807     *  @private
808     */
809    private var _height:Number;
810
811    /**
812     *  The height of this object.  For the SystemManager
813     *  this should always be the width of the stage unless the application was loaded
814     *  into another application.  If the application was not loaded
815     *  into another application, setting this value has no effect.
816     *
817     *  @langversion 3.0
818     *  @playerversion AIR 1.1
819     *  @productversion Flex 3
820     */
821    override public function get height():Number
822    {
823        return _height;
824    }
825
826    /**
827     * @inheritdoc
828     *
829     *  @langversion 3.0
830     *  @playerversion AIR 1.1
831     *  @productversion Flex 3
832     */
833    public function get childAllowsParent():Boolean
834    {
835        try
836        {
837            return loaderInfo.childAllowsParent;
838        }
839        catch (error:Error)
840        {
841            //Error #2099: The loading object is not sufficiently loaded to provide this information.
842        }
843
844        return false;   // assume the worst
845    }
846
847    /**
848     * @inheritdoc
849     *
850     *  @langversion 3.0
851     *  @playerversion AIR 1.1
852     *  @productversion Flex 3
853     */
854    public function get parentAllowsChild():Boolean
855    {
856        try
857        {
858            return loaderInfo.parentAllowsChild;
859        }
860        catch (error:Error)
861        {
862            //Error #2099: The loading object is not sufficiently loaded to provide this information.
863        }
864
865        return false;   // assume the worst
866    }
867
868    //--------------------------------------------------------------------------
869    //
870    //  Methods: Access to overridden methods of base classes
871    //
872    //--------------------------------------------------------------------------
873
874    /**
875     *  @private
876     *  This method allows access to the Player's native implementation
877     *  of addChild(), which can be useful since components
878     *  can override addChild() and thereby hide the native implementation.
879     *  Note that this "base method" is final and cannot be overridden,
880     *  so you can count on it to reflect what is happening at the player level.
881     */
882    mx_internal final function $addChild(child:DisplayObject):DisplayObject
883    {
884        return super.addChild(child);
885    }
886
887    /**
888     *  @private
889     *  This method allows access to the Player's native implementation
890     *  of addChildAt(), which can be useful since components
891     *  can override addChildAt() and thereby hide the native implementation.
892     *  Note that this "base method" is final and cannot be overridden,
893     *  so you can count on it to reflect what is happening at the player level.
894     */
895    mx_internal final function $addChildAt(child:DisplayObject,
896                                           index:int):DisplayObject
897    {
898        return super.addChildAt(child, index);
899    }
900
901    /**
902     *  @private
903     *  This method allows access to the Player's native implementation
904     *  of removeChild(), which can be useful since components
905     *  can override removeChild() and thereby hide the native implementation.
906     *  Note that this "base method" is final and cannot be overridden,
907     *  so you can count on it to reflect what is happening at the player level.
908     */
909    mx_internal final function $removeChild(child:DisplayObject):DisplayObject
910    {
911        return super.removeChild(child);
912    }
913
914    /**
915     *  @private
916     *  This method allows access to the Player's native implementation
917     *  of removeChildAt(), which can be useful since components
918     *  can override removeChildAt() and thereby hide the native implementation.
919     *  Note that this "base method" is final and cannot be overridden,
920     *  so you can count on it to reflect what is happening at the player level.
921     */
922    mx_internal final function $removeChildAt(index:int):DisplayObject
923    {
924        return super.removeChildAt(index);
925    }
926
927    //--------------------------------------------------------------------------
928    //
929    //  Methods: Initialization
930    //
931    //--------------------------------------------------------------------------
932
933    /**
934	 *  This method should not be called on WindowedSystemManager.
935	 *  It is here as part of the contract for IFlexModuleFactory.
936   	 */
937    public function callInContext(fn:Function, thisArg:Object,
938								  argArray:Array, returns:Boolean = true):*
939    {
940        if (returns)
941            return fn.apply(thisArg, argArray);
942        else
943            fn.apply(thisArg, argArray);
944    }
945
946    /**
947     *  This method is overridden in the autogenerated subclass.
948     *
949     *  @langversion 3.0
950     *  @playerversion AIR 1.1
951     *  @productversion Flex 3
952     */
953    public function create(... params):Object
954    {
955        var mainClassName:String = String(params[0]);
956
957        var mainClass:Class = Class(getDefinitionByName(mainClassName));
958        if (!mainClass)
959            throw new Error("Class '" + mainClassName + "' not found.");
960
961		var instance:Object = new mainClass();
962		if (instance is IFlexModule)
963			(IFlexModule(instance)).moduleFactory = this;
964		return instance;
965	}
966
967	/**
968	 *  @private
969	 *  This is attached as the framescript at the end of frame 2.
970	 *  When this function is called, we know that the application
971	 *  class has been defined and read in by the Player.
972	 */
973	protected function docFrameHandler(event:Event = null):void
974	{
975		removeEventListener(Event.ADDED, docFrameHandler);
976
977        // Register singleton classes.
978        // Note: getDefinitionByName() will return null
979        // if the class can't be found.
980        /*
981        Singleton.registerClass("mx.managers::ICursorManager",
982            Class(getDefinitionByName("mx.managers::CursorManagerImpl")));
983
984        Singleton.registerClass("mx.managers::IDragManager",
985            Class(getDefinitionByName("mx.managers::DragManagerImpl")));
986
987        Singleton.registerClass("mx.managers::IHistoryManager",
988            Class(getDefinitionByName("mx.managers::HistoryManagerImpl")));
989
990        Singleton.registerClass("mx.managers::ILayoutManager",
991            Class(getDefinitionByName("mx.managers::LayoutManager")));
992
993        Singleton.registerClass("mx.managers::IPopUpManager",
994            Class(getDefinitionByName("mx.managers::PopUpManagerImpl")));
995
996        Singleton.registerClass("mx.styles::IStyleManager",
997            Class(getDefinitionByName("mx.styles::StyleManagerImpl")));
998
999        Singleton.registerClass("mx.styles::IStyleManager2",
1000            Class(getDefinitionByName("mx.styles::StyleManagerImpl")));
1001
1002        Singleton.registerClass("mx.managers::IToolTipManager2",
1003            Class(getDefinitionByName("mx.managers::ToolTipManagerImpl")));*/
1004
1005//      executeCallbacks();
1006//      doneExecutingInitCallbacks = true;
1007
1008        // Loaded SWFs don't get a stage right away
1009        // and shouldn't override the main SWF's setting anyway.
1010        if (stage)
1011        {
1012            stage.scaleMode = StageScaleMode.NO_SCALE;
1013            stage.align = StageAlign.TOP_LEFT;
1014        }
1015
1016        var mixinList:Array = info()["mixins"];
1017        if (mixinList && mixinList.length > 0)
1018        {
1019            var n:int = mixinList.length;
1020            for (var i:int = 0; i < n; ++i)
1021            {
1022                // trace("initializing mixin " + mixinList[i]);
1023                var c:Class = Class(getDefinitionByName(mixinList[i]));
1024                c["init"](this);
1025            }
1026        }
1027
1028		c = Singleton.getClass("mx.managers::IActiveWindowManager");
1029		if (c)
1030		{
1031            registerImplementation("mx.managers::IActiveWindowManager", new c(this));
1032        }
1033
1034        // depends on having IActiveWindowManager installed first
1035		c = Singleton.getClass("mx.managers::IMarshalSystemManager");
1036		if (c)
1037		{
1038            registerImplementation("mx.managers::IMarshalSystemManager", new c(this));
1039        }
1040
1041    //  installCompiledResourceBundles();
1042
1043        initializeTopLevelWindow(null);
1044
1045        if (Singleton.getClass("mx.managers::IDragManager").getInstance() is NativeDragManagerImpl)
1046            NativeDragManagerImpl(Singleton.getClass("mx.managers::IDragManager").getInstance()).registerSystemManager(this);
1047    }
1048
1049    /**
1050     *  @private
1051     *  Instantiates an instance of the top level window
1052     *  and adds it as a child of the SystemManager.
1053     */
1054    protected function initializeTopLevelWindow(event:Event):void
1055    {
1056        initialized = true;
1057
1058        // This listener is intended to run before any other KeyboardEvent listeners
1059        // so that it can redispatch a cancelable=true copy of the event.
1060        if (getSandboxRoot() == this)
1061        {
1062            // keydown events on AIR are cancelable so we don't need to add a listener.
1063            addEventListener(MouseEvent.MOUSE_WHEEL, mouseEventHandler, true, 1000);
1064            addEventListener(MouseEvent.MOUSE_DOWN, mouseEventHandler, true, 1000);
1065        }
1066        if (isTopLevelRoot() && stage)
1067        {
1068            // keydown events on AIR are cancelable so we don't need to add a listener.
1069            stage.addEventListener(MouseEvent.MOUSE_WHEEL, mouseEventHandler, false, 1000);
1070            stage.addEventListener(MouseEvent.MOUSE_DOWN, mouseEventHandler, false, 1000);
1071        }
1072
1073        if (!parent)
1074            return;
1075
1076        initContextMenu();
1077        if (!topLevel)
1078        {
1079            // We are not top-level and don't have a parent. This can happen
1080            // when the application has already been unloaded by the time
1081            // we get to this point.
1082            if (!parent)
1083                return;
1084
1085            var obj:DisplayObjectContainer = parent.parent;
1086
1087            // if there is no grandparent at this point, we might have been removed and
1088            // are about to be killed so just bail.  Other code that runs after
1089            // this point expects us to be grandparented.  Another scenario
1090            // is that someone loaded us but not into a parented loader, but that
1091            // is not allowed.
1092            if (!obj)
1093                return;
1094
1095            while (obj)
1096            {
1097                if (obj is IUIComponent)
1098                {
1099                    _topLevelSystemManager = IUIComponent(obj).systemManager;
1100                    break;
1101                }
1102                obj = obj.parent;
1103            }
1104        }
1105
1106        //  if (topLevel && stage)
1107        stage.addEventListener(Event.RESIZE, Stage_resizeHandler, false, 0, true);
1108
1109        var app:IUIComponent;
1110        // Create a new instance of the toplevel class
1111        document = app = topLevelWindow;// = IUIComponent(create());
1112
1113        if (document)
1114        {
1115            if (topLevel && stage)
1116            {
1117            //  LoaderConfig._url = loaderInfo.url;
1118            //  LoaderConfig._parameters = loaderInfo.parameters;
1119
1120                // stageWidth/stageHeight may have changed between initialize() and now,
1121                // so refresh our _width and _height here.
1122                _width = stage.stageWidth;
1123                _height = stage.stageHeight;
1124                //trace("width", _width);
1125
1126                IFlexDisplayObject(app).setActualSize(stage.stageWidth, stage.stageHeight);
1127            }
1128            else
1129            {
1130                IFlexDisplayObject(app).setActualSize(loaderInfo.width, loaderInfo.height);
1131            }
1132
1133            // Wait for the app to finish its initialization sequence
1134            // before doing an addChild().
1135            // Otherwise, the measurement/layout code will cause the
1136            // player to do a bunch of unnecessary screen repaints,
1137            // which slows application startup time.
1138
1139            // Pass in the application instance to the preloader using registerApplication
1140        //  preloader.registerApplication(app);
1141
1142            // The Application doesn't get added to the SystemManager in the standard way.
1143            // We want to recursively create the entire application subtree and process
1144            // it with the LayoutManager before putting the Application on the display list.
1145            // So here we what would normally happen inside an override of addChild().
1146            // Leter, when we actually attach the Application instance,
1147            // we call super.addChild(), which is the bare player method.
1148            addingChild(DisplayObject(app));
1149            childAdded(DisplayObject(app)); // calls app.createChildren()
1150        }
1151        else
1152        {
1153            document = this;
1154        }
1155
1156        // because we have no preload done handler, we need to
1157        // do that work elsewhere
1158        addChildAndMouseCatcher();
1159    }
1160
1161    /**
1162     *  @private
1163     *  Same as SystemManager's preload done handler.  It adds
1164     *  the window to the application (and a mouse catcher)
1165     *
1166     *  Called from initializeTopLevelWindow()
1167     */
1168    private function addChildAndMouseCatcher():void
1169    {
1170        var app:IUIComponent = topLevelWindow;
1171        // Add the mouseCatcher as child 0.
1172        mouseCatcher = new FlexSprite();
1173        mouseCatcher.name = "mouseCatcher";
1174
1175        // Must use addChildAt because a creationComplete handler can create a
1176        // dialog and insert it at 0.
1177        noTopMostIndex++;
1178        super.addChildAt(mouseCatcher, 0);
1179        resizeMouseCatcher();
1180
1181        // topLevel seems to always be true, but keeping it here just in case
1182        if (!topLevel)
1183        {
1184            mouseCatcher.visible = false;
1185            mask = mouseCatcher;
1186        }
1187
1188        noTopMostIndex++;
1189        super.addChild(DisplayObject(app));
1190    }
1191
1192
1193    //----------------------------------
1194    //  info
1195    //----------------------------------
1196
1197    /**
1198     *  @private
1199     */
1200    public function info():Object
1201    {
1202        return {
1203            currentDomain: ApplicationDomain.currentDomain
1204        };
1205    }
1206
1207
1208    /**
1209     *  @private
1210     *  Disable all the built-in items except "Print...".
1211     */
1212    private function initContextMenu():void
1213    {
1214        var defaultMenu:ContextMenu = new ContextMenu();
1215        defaultMenu.hideBuiltInItems();
1216        defaultMenu.builtInItems.print = true;
1217        contextMenu = defaultMenu;
1218    }
1219
1220    /**
1221     * @inheritdoc
1222     *
1223     *  @langversion 3.0
1224     *  @playerversion AIR 1.1
1225     *  @productversion Flex 3
1226     */
1227    public function isTopLevelRoot():Boolean
1228    {
1229        return isStageRoot || isBootstrapRoot;
1230    }
1231
1232
1233    /**
1234     * Go up our parent chain to get the top level system manager.
1235     *
1236     * returns null if we are not on the display list or we don't have
1237     * access to the top level system manager.
1238     *
1239     *  @langversion 3.0
1240     *  @playerversion AIR 1.1
1241     *  @productversion Flex 3
1242     */
1243    public function getTopLevelRoot():DisplayObject
1244    {
1245        // work our say up the parent chain to the root. This way we
1246        // don't have to rely on this object being added to the stage.
1247        try
1248        {
1249            var sm:ISystemManager = this;
1250            if (sm.topLevelSystemManager)
1251                sm = ISystemManager(sm.topLevelSystemManager);
1252            var parent:DisplayObject = DisplayObject(sm).parent;
1253            var lastParent:DisplayObject = DisplayObject(sm);
1254            while (parent)
1255            {
1256                if (parent is Stage)
1257                    return lastParent;
1258                lastParent = parent;
1259                parent = parent.parent;
1260            }
1261        }
1262        catch (error:SecurityError)
1263        {
1264        }
1265
1266        return null;
1267    }
1268
1269    /**
1270     * Go up our parent chain to get the top level system manager in this
1271     * SecurityDomain
1272     *
1273     *
1274     *  @langversion 3.0
1275     *  @playerversion AIR 1.1
1276     *  @productversion Flex 3
1277     */
1278    public function getSandboxRoot():DisplayObject
1279    {
1280        // work our say up the parent chain to the root. This way we
1281        // don't have to rely on this object being added to the stage.
1282        var sm:ISystemManager = this;
1283
1284        try
1285        {
1286            if (sm.topLevelSystemManager)
1287                sm = ISystemManager(sm.topLevelSystemManager);
1288            var parent:DisplayObject = DisplayObject(sm).parent;
1289            if (parent is Stage)
1290                return DisplayObject(sm);
1291            // test to see if parent is a Bootstrap
1292            if (parent && !parent.dispatchEvent(new Event("mx.managers.SystemManager.isBootstrapRoot", false, true)))
1293                return this;
1294            var lastParent:DisplayObject = this;
1295            while (parent)
1296            {
1297                if (parent is Stage)
1298                    return lastParent;
1299                // test to see if parent is a Bootstrap
1300                if (!parent.dispatchEvent(new Event("mx.managers.SystemManager.isBootstrapRoot", false, true)))
1301                    return lastParent;
1302
1303                // Test if the childAllowsParent so we know there is mutual trust between
1304                // the sandbox root and this sm.
1305                // The parentAllowsChild is taken care of by the player because it returns null
1306                // for the parent if we do not have access.
1307                if (parent is Loader)
1308                {
1309                    var loader:Loader = Loader(parent);
1310                    var loaderInfo:LoaderInfo = loader.contentLoaderInfo;
1311                    if (!loaderInfo.childAllowsParent)
1312                        return loaderInfo.content;
1313                }
1314
1315                // If an object is listening for system manager request we assume it is a sandbox
1316                // root. If not, don't assign lastParent to this parent because it may be a
1317                // non-Flex application. We only want Flex apps to be returned as sandbox roots.
1318                if (parent.hasEventListener("systemManagerRequest"))
1319                    lastParent = parent;
1320                parent = parent.parent;
1321            }
1322        }
1323        catch (error:Error)
1324        {
1325            // Either we don't have security access to a parent or
1326            // the swf is unloaded and loaderInfo.childAllowsParent is throwing Error #2099.
1327        }
1328
1329        return lastParent != null ? lastParent : DisplayObject(sm);
1330    }
1331
1332    /**
1333     *  @private
1334	 *  A map of fully-qualified interface names,
1335	 *  such as "mx.managers::IPopUpManager",
1336	 *  to implementation classes which produce singleton instances,
1337	 *  such as mx.managers.PopUpManagerImpl.
1338     */
1339    private var implMap:Object = {};
1340
1341    /**
1342     *  @private
1343	 *  Adds an interface-name-to-implementation-class mapping to the registry,
1344	 *  if a class hasn't already been registered for the specified interface.
1345	 *  The class must implement a getInstance() method which returns
1346	 *  its singleton instance.
1347     */
1348    public function registerImplementation(interfaceName:String,
1349										 impl:Object):void
1350    {
1351        var c:Object = implMap[interfaceName];
1352		if (!c)
1353            implMap[interfaceName] = impl;
1354    }
1355
1356    /**
1357     *  @private
1358	 *  Returns the singleton instance of the implementation class
1359	 *  that was registered for the specified interface,
1360	 *  by looking up the class in the registry
1361	 *  and calling its getInstance() method.
1362	 *
1363	 *  This method should not be called at static initialization time,
1364	 *  because the factory class may not have called registerClass() yet.
1365     */
1366    public function getImplementation(interfaceName:String):Object
1367    {
1368        var c:Object = implMap[interfaceName];
1369		return c;
1370    }
1371
1372   /**
1373     *  @inheritdoc
1374     *
1375     *  @langversion 3.0
1376     *  @playerversion AIR 1.1
1377     *  @productversion Flex 3
1378     */
1379    public function getVisibleApplicationRect(bounds:Rectangle = null, skipToSandboxRoot:Boolean = false):Rectangle
1380    {
1381		var request:Request = new Request("getVisibleApplicationRect", false, true);
1382		if (!dispatchEvent(request))
1383			return Rectangle(request.value);
1384
1385		if (skipToSandboxRoot && !topLevel)
1386			return topLevelSystemManager.getVisibleApplicationRect(bounds, skipToSandboxRoot);
1387
1388        if (!bounds)
1389        {
1390            bounds = getBounds(DisplayObject(this));
1391
1392            var s:Rectangle = screen;
1393            var pt:Point = new Point(Math.max(0, bounds.x), Math.max(0, bounds.y));
1394            pt = localToGlobal(pt);
1395            bounds.x = pt.x;
1396            bounds.y = pt.y;
1397            bounds.width = s.width;
1398            bounds.height = s.height;
1399        }
1400
1401		if (!topLevel)
1402		{
1403			var obj:DisplayObjectContainer = parent.parent;
1404
1405			if ("getVisibleApplicationRect" in obj)
1406			{
1407				var visibleRect:Rectangle = obj["getVisibleApplicationRect"](true);
1408				bounds = bounds.intersection(visibleRect);
1409			}
1410		}
1411
1412		return bounds;
1413    }
1414
1415   /**
1416    *  @inheritDoc
1417    *
1418    *  @langversion 3.0
1419    *  @playerversion AIR 1.1
1420    *  @productversion Flex 3
1421    */
1422    public function deployMouseShields(deploy:Boolean):void
1423    {
1424		var dynamicEvent:DynamicEvent = new DynamicEvent("deployMouseShields");
1425		dynamicEvent.deploy = deploy;
1426		dispatchEvent(dynamicEvent);
1427    }
1428
1429    /**
1430     *  @private
1431     *
1432     *  This is a stub to satisfy the IFlexModuleFactory interface.
1433     */
1434    public function addPreloadedRSL(loaderInfo:LoaderInfo, rsl:Vector.<RSLData>):void
1435    {
1436    }
1437
1438    /**
1439     *  @private
1440     *
1441     *  This is a stub to satisfy the IFlexModuleFactory interface.
1442     *
1443     *  Calls Security.allowDomain() for the SWF associated with this SystemManager
1444     *  plus all the SWFs assocatiated with RSLs preloaded by this SystemManager.
1445     *
1446     */
1447    public function allowDomain(... domains):void
1448    {
1449    }
1450
1451    /**
1452     *  @private
1453     *
1454     *  This is a stub to satisfy the IFlexModuleFactory interface.
1455     *
1456     *  Calls Security.allowInsecureDomain() for the SWF associated with this SystemManager
1457     *  plus all the SWFs assocatiated with RSLs preloaded by this SystemManager.
1458     *
1459     */
1460    public function allowInsecureDomain(... domains):void
1461    {
1462    }
1463
1464    /**
1465     *  Returns <code>true</code> if the given DisplayObject is the
1466     *  top-level window.
1467     *
1468     *  @param object
1469     *
1470     *  @return <code>true</code> if the given DisplayObject is the
1471     *  top-level window.
1472     *
1473     *  @langversion 3.0
1474     *  @playerversion AIR 1.1
1475     *  @productversion Flex 3
1476     */
1477    public function isTopLevelWindow(object:DisplayObject):Boolean
1478    {
1479        return object is IUIComponent &&
1480               IUIComponent(object) == topLevelWindow;
1481    }
1482
1483    /**
1484     *  @inheritDoc
1485     *
1486     *  @langversion 3.0
1487     *  @playerversion AIR 1.1
1488     *  @productversion Flex 3
1489     */
1490    public function getDefinitionByName(name:String):Object
1491    {
1492        var domain:ApplicationDomain = ApplicationDomain.currentDomain;
1493            !topLevel && parent is Loader ?
1494            Loader(parent).contentLoaderInfo.applicationDomain :
1495            info()["currentDomain"] as ApplicationDomain;
1496
1497        //trace("SysMgr.getDefinitionByName domain",domain,"currentDomain",info()["currentDomain"]);
1498
1499        var definition:Object;
1500
1501        if (domain.hasDefinition(name))
1502        {
1503            definition = domain.getDefinition(name);
1504            //trace("SysMgr.getDefinitionByName got definition",definition,"name",name);
1505        }
1506
1507        return definition;
1508    }
1509
1510    /**
1511     *  @inheritDoc
1512     *
1513     *  @langversion 3.0
1514     *  @playerversion AIR 1.1
1515     *  @productversion Flex 3
1516     */
1517    public function isTopLevel():Boolean
1518    {
1519        return topLevel;
1520    }
1521
1522    /**
1523     *  @inheritDoc
1524     *
1525     *  @langversion 3.0
1526     *  @playerversion AIR 1.1
1527     *  @productversion Flex 3
1528     */
1529    public function isFontFaceEmbedded(textFormat:TextFormat):Boolean
1530    {
1531        var fontName:String = textFormat.font;
1532
1533        var fl:Array = Font.enumerateFonts();
1534        for (var f:int = 0; f < fl.length; ++f)
1535        {
1536            var font:Font = Font(fl[f]);
1537            if (font.fontName == fontName)
1538            {
1539                var style:String = "regular";
1540                if (textFormat.bold && textFormat.italic)
1541                    style = "boldItalic";
1542                else if (textFormat.bold)
1543                    style = "bold";
1544                else if (textFormat.italic)
1545                    style = "italic";
1546
1547                if (font.fontStyle == style)
1548                    return true;
1549            }
1550        }
1551
1552        if (!fontName ||
1553            !embeddedFontList ||
1554            !embeddedFontList[fontName])
1555        {
1556            return false;
1557        }
1558
1559        var info:Object = embeddedFontList[fontName];
1560
1561        return !((textFormat.bold && !info.bold) ||
1562                 (textFormat.italic && !info.italic) ||
1563                 (!textFormat.bold && !textFormat.italic &&
1564                 !info.regular));
1565    }
1566
1567
1568    /**
1569     *  @private
1570     *  Keep track of the size and position of the stage.
1571     */
1572    private function Stage_resizeHandler(event:Event = null):void
1573    {
1574        var w:Number = stage.stageWidth;
1575        var h:Number = stage.stageHeight;
1576
1577        var y:Number = 0;
1578        var x:Number = 0;
1579
1580        if (!_screen)
1581            _screen = new Rectangle();
1582        _screen.x = x;
1583        _screen.y = y;
1584        _screen.width = w;
1585        _screen.height = h;
1586
1587
1588        _width = stage.stageWidth;
1589        _height = stage.stageHeight;
1590
1591//trace(_width, event.type);
1592		if (event)
1593		{
1594			resizeMouseCatcher();
1595			dispatchEvent(event);
1596		}
1597	}
1598
1599
1600	/**
1601	 * @private
1602	 *
1603	 * Get the index of an object in a given child list.
1604	 *
1605	 * @return index of f in childList, -1 if f is not in childList.
1606	 */
1607	private static function getChildListIndex(childList:IChildList, f:Object):int
1608	{
1609		var index:int = -1;
1610		try
1611		{
1612			index = childList.getChildIndex(DisplayObject(f));
1613		}
1614		catch (e:ArgumentError)
1615		{
1616			// index has been preset to -1 so just continue.
1617		}
1618
1619		return index;
1620	}
1621
1622
1623    /**
1624     *  @private
1625     *  Makes the mouseCatcher the same size as the stage,
1626     *  filling it with transparent pixels.
1627     */
1628    private function resizeMouseCatcher():void
1629    {
1630        if (mouseCatcher)
1631        {
1632            var g:Graphics = mouseCatcher.graphics;
1633            g.clear();
1634            g.beginFill(0x000000, 0);
1635            g.drawRect(0, 0, stage.stageWidth, stage.stageHeight);
1636            g.endFill();
1637        }
1638    }
1639
1640	/**
1641	 * @private
1642	 *
1643	 * true if redipatching a resize event.
1644	 */
1645	private var isDispatchingResizeEvent:Boolean;
1646
1647    //--------------------------------------------------------------------------
1648    //
1649    //  Overridden methods: EventDispatcher
1650    //
1651    //--------------------------------------------------------------------------
1652
1653	/**
1654	 *  @private
1655	 *  allows marshal implementation to add events
1656	 */
1657	mx_internal final function $addEventListener(type:String, listener:Function,
1658											  useCapture:Boolean = false,
1659											  priority:int = 0,
1660											  useWeakReference:Boolean = false):void
1661	{
1662		super.addEventListener(type, listener, useCapture, priority, useWeakReference);
1663	}
1664
1665	/**
1666	 *  @private
1667	 *  Only create idle events if someone is listening.
1668	 */
1669	override public function addEventListener(type:String, listener:Function,
1670											  useCapture:Boolean = false,
1671											  priority:int = 0,
1672											  useWeakReference:Boolean = false):void
1673	{
1674		if (type == MouseEvent.MOUSE_MOVE || type == MouseEvent.MOUSE_UP || type == MouseEvent.MOUSE_DOWN
1675				|| type == Event.ACTIVATE || type == Event.DEACTIVATE)
1676		{
1677			// also listen to stage if allowed
1678			try
1679			{
1680				if (stage)
1681				{
1682                    // Use weak listener because we don't always know when we
1683                    // no longer need this listener
1684					stage.addEventListener(type, stageEventHandler, false, 0, true);
1685				}
1686			}
1687			catch (error:SecurityError)
1688			{
1689			}
1690		}
1691
1692        if (hasEventListener("addEventListener"))
1693        {
1694            var request:DynamicEvent = new DynamicEvent("addEventListener", false, true);
1695            request.eventType = type;
1696            request.listener = listener;
1697            request.useCapture = useCapture;
1698            request.priority = priority;
1699            request.useWeakReference = useWeakReference;
1700		    if (!dispatchEvent(request))
1701			    return;
1702        }
1703
1704        if (type == SandboxMouseEvent.MOUSE_UP_SOMEWHERE)
1705        {
1706            // If someone wants this event, also listen for mouseLeave.
1707            // Use weak listener because we don't always know when we
1708            // no longer need this listener
1709            try
1710            {
1711			    if (stage)
1712			    {
1713				    stage.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler, false, 0, true);
1714                }
1715                else
1716                {
1717					super.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler, false, 0, true);
1718                }
1719			}
1720			catch (error:SecurityError)
1721			{
1722				super.addEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler, false, 0, true);
1723			}
1724        }
1725
1726		// These two events will dispatched to applications in sandboxes.
1727		if (type == FlexEvent.RENDER || type == FlexEvent.ENTER_FRAME)
1728		{
1729			if (type == FlexEvent.RENDER)
1730				type = Event.RENDER;
1731			else
1732				type = Event.ENTER_FRAME;
1733
1734			try
1735			{
1736				if (stage)
1737					stage.addEventListener(type, listener, useCapture, priority, useWeakReference);
1738				else
1739					super.addEventListener(type, listener, useCapture, priority, useWeakReference);
1740			}
1741			catch (error:SecurityError)
1742			{
1743				super.addEventListener(type, listener, useCapture, priority, useWeakReference);
1744			}
1745
1746			if (stage && type == Event.RENDER)
1747				stage.invalidate();
1748
1749            return;
1750        }
1751
1752		super.addEventListener(type, listener, useCapture, priority, useWeakReference);
1753	}
1754
1755	/**
1756	 *  @private
1757	 */
1758	mx_internal final function $removeEventListener(type:String, listener:Function,
1759												 useCapture:Boolean = false):void
1760	{
1761		super.removeEventListener(type, listener, useCapture);
1762	}
1763
1764	/**
1765	 *  @private
1766	 */
1767	override public function removeEventListener(type:String, listener:Function,
1768												 useCapture:Boolean = false):void
1769	{
1770        if (hasEventListener("removeEventListener"))
1771        {
1772            var request:DynamicEvent = new DynamicEvent("removeEventListener", false, true);
1773            request.eventType = type;
1774            request.listener = listener;
1775            request.useCapture = useCapture;
1776		    if (!dispatchEvent(request))
1777			    return;
1778        }
1779
1780		// These two events will dispatched to applications in sandboxes.
1781		if (type == FlexEvent.RENDER || type == FlexEvent.ENTER_FRAME)
1782		{
1783			if (type == FlexEvent.RENDER)
1784				type = Event.RENDER;
1785			else
1786				type = Event.ENTER_FRAME;
1787
1788			try
1789			{
1790				if (stage)
1791					stage.removeEventListener(type, listener, useCapture);
1792            }
1793            catch (error:SecurityError)
1794            {
1795            }
1796			// Remove both listeners in case the system manager was added
1797			// or removed from the stage after the listener was added.
1798            super.removeEventListener(type, listener, useCapture);
1799
1800            return;
1801        }
1802
1803        super.removeEventListener(type, listener, useCapture);
1804
1805		if (type == MouseEvent.MOUSE_MOVE || type == MouseEvent.MOUSE_UP || type == MouseEvent.MOUSE_DOWN
1806				|| type == Event.ACTIVATE || type == Event.DEACTIVATE)
1807		{
1808            if (!hasEventListener(type))
1809            {
1810			    // also listen to stage if allowed
1811			    try
1812			    {
1813				    if (stage)
1814				    {
1815					    stage.removeEventListener(type, stageEventHandler, false);
1816				    }
1817			    }
1818			    catch (error:SecurityError)
1819			    {
1820			    }
1821            }
1822		}
1823
1824        if (type == SandboxMouseEvent.MOUSE_UP_SOMEWHERE)
1825        {
1826            if (!hasEventListener(SandboxMouseEvent.MOUSE_UP_SOMEWHERE))
1827            {
1828                // nobody wants this event any more for now
1829                try
1830                {
1831			        if (stage)
1832			        {
1833				        stage.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
1834                    }
1835			    }
1836			    catch (error:SecurityError)
1837			    {
1838			    }
1839			    // Remove both listeners in case the system manager was added
1840			    // or removed from the stage after the listener was added.
1841			    super.removeEventListener(Event.MOUSE_LEAVE, mouseLeaveHandler);
1842            }
1843        }
1844	}
1845
1846    //--------------------------------------------------------------------------
1847    //
1848    //  Overridden methods: DisplayObjectContainer
1849    //
1850    //--------------------------------------------------------------------------
1851
1852    /**
1853     *  @private
1854     */
1855    override public function addChild(child:DisplayObject):DisplayObject
1856    {
1857        // Adjust the partition indexes
1858        // before the "added" event is dispatched.
1859        noTopMostIndex++;
1860
1861        return rawChildren_addChildAt(child, noTopMostIndex - 1);
1862    }
1863
1864    //----------------------------------
1865    //  numChildren
1866    //----------------------------------
1867
1868    /**
1869     *  The number of non-floating windows.  This is the main application window
1870     *  plus any other windows added to the SystemManager that are not popups,
1871     *  tooltips or cursors.
1872     *
1873     *  @langversion 3.0
1874     *  @playerversion AIR 1.1
1875     *  @productversion Flex 3
1876     */
1877    override public function get numChildren():int
1878    {
1879        return noTopMostIndex - applicationIndex;
1880    }
1881
1882    /**
1883     *  @private
1884     */
1885    override public function addChildAt(child:DisplayObject,
1886                                        index:int):DisplayObject
1887    {
1888        // Adjust the partition indexes
1889        // before the "added" event is dispatched.
1890        noTopMostIndex++;
1891
1892        return rawChildren_addChildAt(child, applicationIndex + index);
1893    }
1894
1895    /**
1896     *  @private
1897     */
1898    override public function removeChild(child:DisplayObject):DisplayObject
1899    {
1900        // Adjust the partition indexes
1901        // before the "removed" event is dispatched.
1902        noTopMostIndex--;
1903
1904        return rawChildren_removeChild(child);
1905    }
1906
1907    /**
1908     *  @private
1909     */
1910    override public function removeChildAt(index:int):DisplayObject
1911    {
1912        // Adjust the partition indexes
1913        // before the "removed" event is dispatched.
1914        noTopMostIndex--;
1915
1916        return rawChildren_removeChildAt(applicationIndex + index);
1917    }
1918
1919    /**
1920     *  @private
1921     */
1922    override public function getChildAt(index:int):DisplayObject
1923    {
1924        return super.getChildAt(applicationIndex + index);
1925    }
1926
1927    /**
1928     *  @private
1929     */
1930    override public function getChildByName(name:String):DisplayObject
1931    {
1932        return super.getChildByName(name);
1933    }
1934
1935    /**
1936     *  @private
1937     */
1938    override public function getChildIndex(child:DisplayObject):int
1939    {
1940        return super.getChildIndex(child) - applicationIndex;
1941    }
1942
1943    /**
1944     *  @private
1945     */
1946    override public function setChildIndex(child:DisplayObject, newIndex:int):void
1947    {
1948        super.setChildIndex(child, applicationIndex + newIndex);
1949    }
1950
1951    /**
1952     *  @private
1953     */
1954    override public function getObjectsUnderPoint(point:Point):Array
1955    {
1956        var children:Array = [];
1957
1958        // Get all the children that aren't tooltips and cursors.
1959        var n:int = topMostIndex;
1960        for (var i:int = 0; i < n; i++)
1961        {
1962            var child:DisplayObject = super.getChildAt(i);
1963            if (child is DisplayObjectContainer)
1964            {
1965                var temp:Array =
1966                    DisplayObjectContainer(child).getObjectsUnderPoint(point);
1967
1968                if (temp)
1969                    children = children.concat(temp);
1970            }
1971        }
1972
1973        return children;
1974    }
1975
1976    //--------------------------------------------------------------------------
1977    //
1978    //  Methods: Child management
1979    //
1980    //--------------------------------------------------------------------------
1981
1982    /**
1983     *  @private
1984     */
1985    mx_internal function addingChild(child:DisplayObject):void
1986    {
1987        var newNestLevel:int = 1;
1988        if (!topLevel)
1989        {
1990            // non-topLevel SystemManagers are buried by Flash.display.Loader and
1991            // other non-framework layers so we have to figure out the nestlevel
1992            // by searching up the parent chain.
1993            var obj:DisplayObjectContainer = parent.parent;
1994            while (obj)
1995            {
1996                if (obj is ILayoutManagerClient)
1997                {
1998                    newNestLevel = ILayoutManagerClient(obj).nestLevel + 1;
1999                    break;
2000                }
2001                obj = obj.parent;
2002            }
2003        }
2004        nestLevel = newNestLevel;
2005
2006        if (child is IUIComponent)
2007            IUIComponent(child).systemManager = this;
2008
2009        // Local variables for certain classes we need to check against below.
2010        // This is the backdoor way around linking in the class in question.
2011        var uiComponentClassName:Class =
2012            Class(getDefinitionByName("mx.core.UIComponent"));
2013
2014        // If the document property isn't already set on the child,
2015        // set it to be the same as this component's document.
2016        // The document setter will recursively set it on any
2017        // descendants of the child that exist.
2018        if (child is IUIComponent &&
2019            !IUIComponent(child).document)
2020        {
2021            IUIComponent(child).document = document;
2022        }
2023
2024        // Set the nestLevel of the child to be one greater
2025        // than the nestLevel of this component.
2026        // The nestLevel setter will recursively set it on any
2027        // descendants of the child that exist.
2028        if (child is ILayoutManagerClient)
2029            ILayoutManagerClient(child).nestLevel = nestLevel + 1;
2030
2031        if (child is InteractiveObject)
2032            if (doubleClickEnabled)
2033                InteractiveObject(child).doubleClickEnabled = true;
2034
2035        if (child is IUIComponent)
2036            IUIComponent(child).parentChanged(this);
2037
2038        // Sets up the inheritingStyles and nonInheritingStyles objects
2039        // and their proto chains so that getStyle() works.
2040        // If this object already has some children,
2041        // then reinitialize the children's proto chains.
2042        if (child is IStyleClient)
2043            IStyleClient(child).regenerateStyleCache(true);
2044
2045        if (child is ISimpleStyleClient)
2046            ISimpleStyleClient(child).styleChanged(null);
2047
2048        if (child is IStyleClient)
2049            IStyleClient(child).notifyStyleChangeInChildren(null, true);
2050
2051        // Need to check to see if the child is an UIComponent
2052        // without actually linking in the UIComponent class.
2053        if (uiComponentClassName && child is uiComponentClassName)
2054            uiComponentClassName(child).initThemeColor();
2055
2056        // Inform the component that it's style properties
2057        // have been fully initialized. Most components won't care,
2058        // but some need to react to even this early change.
2059        if (uiComponentClassName && child is uiComponentClassName)
2060            uiComponentClassName(child).stylesInitialized();
2061    }
2062
2063    /**
2064     *  @private
2065     */
2066    mx_internal function childAdded(child:DisplayObject):void
2067    {
2068        if (child.hasEventListener(FlexEvent.ADD))
2069            child.dispatchEvent(new FlexEvent(FlexEvent.ADD));
2070
2071        if (child is IUIComponent)
2072            IUIComponent(child).initialize(); // calls child.createChildren()
2073    }
2074
2075    /**
2076     *  @private
2077     */
2078    mx_internal function removingChild(child:DisplayObject):void
2079    {
2080        if (child.hasEventListener(FlexEvent.REMOVE))
2081            child.dispatchEvent(new FlexEvent(FlexEvent.REMOVE));
2082    }
2083
2084    /**
2085     *  @private
2086     */
2087    mx_internal function childRemoved(child:DisplayObject):void
2088    {
2089        if (child is IUIComponent)
2090            IUIComponent(child).parentChanged(null);
2091    }
2092
2093    //--------------------------------------------------------------------------
2094    //
2095    //  Methods: Support for rawChildren access
2096    //
2097    //--------------------------------------------------------------------------
2098
2099    /**
2100     *  @private
2101     */
2102    mx_internal function rawChildren_addChild(child:DisplayObject):DisplayObject
2103    {
2104        childManager.addingChild(child);
2105
2106        super.addChild(child);
2107
2108        childManager.childAdded(child); // calls child.createChildren()
2109
2110        return child;
2111    }
2112
2113    /**
2114     *  @private
2115     */
2116    mx_internal function rawChildren_addChildAt(child:DisplayObject,
2117                                                index:int):DisplayObject
2118    {
2119        // preloader goes through here before childManager is set up
2120        if (childManager)
2121            childManager.addingChild(child);
2122
2123        super.addChildAt(child, index);
2124
2125        if (childManager)
2126            childManager.childAdded(child); // calls child.createChildren()
2127
2128        return child;
2129    }
2130
2131    /**
2132     *  @private
2133     */
2134    mx_internal function rawChildren_removeChild(child:DisplayObject):DisplayObject
2135    {
2136        childManager.removingChild(child);
2137        super.removeChild(child);
2138        childManager.childRemoved(child);
2139
2140        return child;
2141    }
2142
2143    /**
2144     *  @private
2145     */
2146    mx_internal function rawChildren_removeChildAt(index:int):DisplayObject
2147    {
2148        var child:DisplayObject = super.getChildAt(index);
2149
2150        childManager.removingChild(child);
2151
2152        super.removeChildAt(index);
2153
2154        childManager.childRemoved(child);
2155
2156        return child;
2157    }
2158
2159    /**
2160     *  @private
2161     */
2162    mx_internal function rawChildren_getChildAt(index:int):DisplayObject
2163    {
2164        return super.getChildAt(index);
2165    }
2166
2167    /**
2168     *  @private
2169     */
2170    mx_internal function rawChildren_getChildByName(name:String):DisplayObject
2171    {
2172        return super.getChildByName(name);
2173    }
2174
2175    /**
2176     *  @private
2177     */
2178    mx_internal function rawChildren_getChildIndex(child:DisplayObject):int
2179    {
2180        return super.getChildIndex(child);
2181    }
2182
2183    /**
2184     *  @private
2185     */
2186    mx_internal function rawChildren_setChildIndex(child:DisplayObject, newIndex:int):void
2187    {
2188        super.setChildIndex(child, newIndex);
2189    }
2190
2191    /**
2192     *  @private
2193     */
2194    mx_internal function rawChildren_getObjectsUnderPoint(pt:Point):Array
2195    {
2196        return super.getObjectsUnderPoint(pt);
2197    }
2198
2199    /**
2200     *  @private
2201     */
2202    mx_internal function rawChildren_contains(child:DisplayObject):Boolean
2203    {
2204        return super.contains(child);
2205    }
2206
2207	// fake out mouseX/mouseY
2208	mx_internal var _mouseX:*;
2209	mx_internal var _mouseY:*;
2210
2211
2212    /**
2213     *  @private
2214     */
2215    override public function get mouseX():Number
2216    {
2217        if (_mouseX === undefined)
2218            return super.mouseX;
2219        return _mouseX;
2220    }
2221
2222    /**
2223     *  @private
2224     */
2225    override public function get mouseY():Number
2226    {
2227        if (_mouseY === undefined)
2228            return super.mouseY;
2229        return _mouseY;
2230    }
2231
2232    /**
2233     * Return the object the player sees as having focus.
2234     *
2235     * @return An object of type InteractiveObject that the
2236     *         player sees as having focus. If focus is currently
2237     *         in a sandbox the caller does not have access to
2238     *         null will be returned.
2239     *
2240     *  @langversion 3.0
2241     *  @playerversion AIR 1.1
2242     *  @productversion Flex 3
2243     */
2244    public function getFocus():InteractiveObject
2245    {
2246        try
2247        {
2248            return stage.focus;
2249        }
2250        catch (e:SecurityError)
2251        {
2252            // trace("SM getFocus(): ignoring security error " + e);
2253        }
2254
2255        return null;
2256    }
2257
2258    /**
2259     *  @private
2260     *  Cleans up references to Window. Also removes self from topLevelSystemManagers list.
2261     */
2262    mx_internal function cleanup(e:Event):void
2263    {
2264        if (Singleton.getClass("mx.managers::IDragManager").getInstance()
2265                     is NativeDragManagerImpl)
2266            NativeDragManagerImpl(Singleton.getClass("mx.managers::IDragManager").getInstance()).unregisterSystemManager(this);
2267        SystemManagerGlobals.topLevelSystemManagers.splice(SystemManagerGlobals.topLevelSystemManagers.indexOf(this), 1);
2268        myWindow.nativeWindow.removeEventListener(Event.CLOSE, cleanup);
2269        myWindow = null;
2270    }
2271
2272    /**
2273     *  @private
2274     *  only registers Window for later cleanup.
2275     */
2276    mx_internal function addWindow(win:IWindow):void
2277    {
2278        myWindow = win;
2279        myWindow.nativeWindow.addEventListener(Event.CLOSE, cleanup);
2280    }
2281
2282    /**
2283     *  @private
2284     *  dispatch certain stage events from sandbox root
2285     */
2286    private function stageEventHandler(event:Event):void
2287    {
2288        if (event.target is Stage)
2289            dispatchEvent(event);
2290    }
2291
2292    /**
2293     *  @private
2294     *  convert MOUSE_LEAVE to MOUSE_UP_SOMEWHERE
2295     */
2296    private function mouseLeaveHandler(event:Event):void
2297    {
2298        dispatchEvent(new SandboxMouseEvent(SandboxMouseEvent.MOUSE_UP_SOMEWHERE));
2299    }
2300
2301    /**
2302     *  Attempts to notify the parent SWFLoader that the
2303     *  Application's size has may have changed.  Not needed
2304     *  for WindowedSystemManager so does nothing
2305     *
2306     *  @langversion 3.0
2307     *  @playerversion Flash 10
2308     *  @playerversion AIR 1.5
2309     *  @productversion Flex 4
2310     */
2311    public function invalidateParentSizeAndDisplayList():void
2312    {
2313    }
2314
2315    //--------------------------------------------------------------------------
2316    //
2317    //  Event Handlers
2318    //
2319    //--------------------------------------------------------------------------
2320
2321    /**
2322     *  NOTE: The keyDownHandler in SystemManager is not needed in AIR because
2323     *  AIR keyDown events are cancelable.
2324     */
2325
2326    /**
2327     *  @private
2328     *  We want to re-dispatch
2329     *  mouse events that are cancellable.  Currently we are only doing
2330     *  this for a few mouse events and not all of them (MOUSE_WHEEL and
2331     *  MOUSE_DOWN).
2332     */
2333    private function mouseEventHandler(e:MouseEvent):void
2334    {
2335        if (!e.cancelable)
2336        {
2337            e.stopImmediatePropagation();
2338            var cancelableEvent:MouseEvent = new MouseEvent(e.type, e.bubbles,
2339                true, e.localX,
2340                e.localY, e.relatedObject, e.ctrlKey, e.altKey,
2341                e.shiftKey, e.buttonDown, e.delta,
2342                e.commandKey, e.controlKey, e.clickCount);
2343
2344            e.target.dispatchEvent(cancelableEvent);
2345        }
2346    }
2347
2348
2349}
2350}
2351